beginner's question:
is it possible to pass GET request parameters to a route function in Flask using add_url_rule?
I am getting the error message that the verify_username_route function I declare later (that takes 1 parameter) is called without any parameters passed.
self.application_.add_url_rule(self.path_ + '/verify', 'verify', self.verify_username_route, methods=['GET'])
To fetch query string parameters, you use request.args.get('argname') in your function. Nothing is passed in -- it's all done through the globals.
To pass any parameters in your URLs, you can use Flask's built-in patterns. These work for both #app.route decorators and add_url_route methods. Here is your code, with a parameter:
self.application_.add_url_rule(self.path_ + '/verify/<int:val>', 'verify', self.verify_username_route, methods=['GET'])
The important part from this is the exact route: /verify/<int:parameter>. This tells Flask that you want the route to be in the format of /verify/something, where something is any integer. Whatever integer is entered here when the request is made gets passed to your self.verify_username_route as a parameter called val.
Read more about this here.
Related
In url.py I have set up a new path within the main urlpatterns list:
path('ko/', views.ko),
I learned that I need to write this function in views.py to get the webpage going:
def ko(request):
return HttpResponse("It's a page")
My question is why doesn't the function work when I leave the parameter blank instead of request?:
def ko():
return HttpResponse("It's a page")
Running the page when I delete the request parameter outputs a TypeError:ko() takes 0 positional arguments but 1 was given.
If I don't have a request input on the function call of views.ko then why is the request parameter necessary when writing the initial function, what is the request parameter doing, and where is this request parameter going into? What are its attributes? I would really appreciate a thorough response on its qualities.
A view function, or view for short, is a Python function that takes a Web request and returns a Web response. So every view must accept an request parameter.
The request object contains metadata about the request, for example what HTTP request method used, The IP address of the client etc. You find the list of HttpRequest here
Also from the documentation.
Once one of the URL patterns matches, Django imports and calls the
given view, which is a Python function (or a class-based view). The
view gets passed the following arguments:
An instance of HttpRequest.
If the matched URL pattern contained no named groups, then the matches
from the regular expression are provided as positional arguments.
The keyword arguments are made up of any named parts matched by the
path expression that are provided, overridden by any arguments
specified in the optional kwargs argument to django.urls.path() or
django.urls.re_path().
Each view function takes an HttpRequest object as its first parameter, which is typically named request
My function is below:
def do(self, text, disable=['ner'], all_tokens=False, char_match=True, channels=use_channels)
Now I am using a Flask http call to make post requests to the function, and the function parameters are passed through the http call. The results of parameters is in a dict:
parameters = {'disable':['ner', 'lst'], 'all_tokens':True, 'char_match':False}
My question is, how to apply the parameters in the dict to the function 'do'?
If I'm understanding you correctly, all you need to do is unpack the parameters object in the 'do' function. E.g.
do(**parameters)
If you're talking about how to pull the parameters from the URL-
You'll need to get them one at a time IIRC, but as follows:
from flask import request
disable = request.args.get('disable')
all_tokens = request.args.get('all_tokens')
...
do(..., disable=disable, all_tokens=all_tokens)
I have a question about Django and it's routing system. I believe that it can be powerfull, but right now I am struggling with one issue I don't experience when working in other frameworks and I can't seem to get a grip on it. Worth to mention that I don't have much experience with Django at this point.
The issue is simple - I have a view which takes two optional parameters, defined like this
def test_view(id=None, grid=None):
Both parameters are optional and frequently are not passed. Id can only be an integer and grid will never be an integer (it is a special string to control datagrid when I don't want to use sessions). I have a route defined like this:
url(a(r'^test_view (\/(?P<id>\d+))? (\/(?P<grid>[^\/]+))? \/?$'), views.test_view, name='test_view'),
This works great and I am not having trouble with using one-way routes. But when I try to use the reverse function or url template tag, following error occurs:
Reverse for 'test_view' with arguments '('20~id~desc~1',)' and keyword arguments '{}' not found.
In this example I tried to find reverse without the id, just with the grid parameter. I have tried various methods of passing parameters to the reverse function:
(grid, )
(None, grid)
('', grid)
{id=None, grid=grid}
All of them result in same error or similliar one.
Is there a way to implement this in django? Maybe just disable the cool URL for the grid parameter. That is how I do it in for example Nette framework for PHP, isntead of having an url like this: 'localhost/test_view/1/20~id~desc~1' I have url like this: 'localhost/test_view/1?grid=20~id~desc~1'. This would be completely sufficient, but I have no idea how to achive this in Django.
As you note in your question, the best way to achieve this is to use standard GET query parameters, rather than doing it in the path itself. In Django you do that exclusively in the view; the URL itself is then just
url(r'^test_view$', views.test_view, name='test_view'),
and you request it via localhost/test_view?id=1&grid=20~id~desc~1. You get the params from request.GET, which is a dictionary-like object; you can use .get so that it does not raise a KeyError when the key is not provided.
def test_view(request):
id = request.GET.get('id')
grid = request.GET.get('grid')
I am trying to call a function when an http GET request is sent to a specific route, but I would like to pass parameters to the given function. For example, I have the following:
self.app.route('/here', ['GET'], self.here_method)
where self.here_method(self) is called when a GET request is sent to the /here route. Instead, I would like to call the method self.here_method(self, 'param'). How can I do this? I tried self.app.route('/here', ['GET'], self.here_method, 'param'), but it does not work. I reviewed this documentation, but I could not find any answers.
It's not clear whether you're asking how to associate your route with a closure, or simply with a function that takes a parameter.
If you simply want to take parameters as part of your your URI, use Bottle's dynamic path routing.
If, on the other hand, you want to "capture" a value that's known at the time of route definition, and bake that into your route handler, then use functools.partial.
Here's an example of both.
from bottle import Bottle
import functools
app = Bottle()
# take a param from the URI
#app.route('/hello1/<param>')
def hello1(param):
return ['this function takes 1 param: {}'.format(param)]
# "bake" in a param value at route definition time
hello2 = functools.partial(hello1, param='the_value')
app.route('/hello2', ['GET'], hello2)
app.run(host='0.0.0.0', port=8080)
And an example of its output:
% curl http://localhost:8080/hello1/foo
127.0.0.1 - - [11/Jul/2015 18:55:49] "GET /hello1/foo HTTP/1.1" 200 32
this function takes 1 param: foo
% curl http://localhost:8080/hello2
127.0.0.1 - - [11/Jul/2015 18:55:51] "GET /hello2 HTTP/1.1" 200 38
this function takes 1 param: the_value
I have no experience with bottle, but it seems that route expects a callback function that does not take any parameters. To achieve this, you could create some throw-away wrapper around your method, which does does not accept any parameters. This is done typically using an anonymous function defined by a lambda expression, something like:
self.app.route('/here', ['GET'], lambda: self.here_method(self, 'param'))
Sample Bottle.py code:
#route('/show_<name>')
def show(name):
return ''
My question is:
Given a URL, how do we get the view function? E.g. the URL is /show_magic, I need to know the show() function is responsible for this request URL
Given a route (not Router!!) and parameters, how to get the URL? e.g. I need a function called reverse which reverse(default_app().routes[0], name='me') == '/show_me'
you might want to consider named routes
#route('/show_<item_name>', name='item_show')
def show(item_name):
return ''
now given the route name and params how to get the URL? we use get_url
get_url('item_show', item_name='my_item')
http://nongraphical.com/2012/08/using-bottle-py-in-production/
For your first question, use Bottle.match. Given a path (i.e. '/show_magic') and the method (GET or POST or whatever), the following will return a tuple containing a Route object and its parameters:
default_app().match({'PATH_INFO': path, 'REQUEST_METHOD': method})
The function called is the Route object's callback or call attribute.
For your second question, use the router's build method with the route's rule and kwargs:
default_app().router.build(route.rule, name='me')
That doesn't seem to be documented, but it works.