Flask URL return to endpoint arguments +

What would be the appropriate way to allow the URL in Flask to get the link to the endpoint, as well as a dictionary of all arguments?

To provide an example, given this route, I would like to allow '/user/nick' to profile , {'username': 'nick'} :

 @app.route('/user/<username>') def profile(username): pass 

From my research so far, all routes in Flask are stored in app.url_map . The map is an instance of werkzeug.routing.Map and has a match() method, which basically will do what I'm looking for. However, this method is internal to the class.

+6
source share
2 answers

This is what I hacked for this purpose by looking at url_for() and changing it:

 from flask.globals import _app_ctx_stack, _request_ctx_stack from werkzeug.urls import url_parse def route_from(url, method = None): appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError('Attempted to match a URL without the ' 'application context being pushed. This has to be ' 'executed when application context is available.') if reqctx is not None: url_adapter = reqctx.url_adapter else: url_adapter = appctx.url_adapter if url_adapter is None: raise RuntimeError('Application was not able to create a URL ' 'adapter for request independent URL matching. ' 'You might be able to fix this by setting ' 'the SERVER_NAME config variable.') parsed_url = url_parse(url) if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name: raise NotFound() return url_adapter.match(parsed_url.path, method) 

The return value of this method is a tuple, with the first element is the name of the endpoint, and the second is a dictionary with arguments.

I did not test it extensively, but it worked for me in all cases.

+10
source

I know that I come later with the answer, but I ran into the same problem and found an easier way to get it: request.view_args . For instance:

In my opinion:

 @app.route('/user/<username>') def profile(username): return render_template("profile.html") 

In profile.html : {{Request.view_args}}

When I visit the URL http://localhost:4999/user/sam I get: {'username': u'sam'} .

You can also get the name of the function that got your view using request.endpoint .

+2
source

Source: https://habr.com/ru/post/956854/


All Articles