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'))
Related
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.
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)
Well i've this in my flask app :
#app.route("/changeip/<ip>")
def change_ip(ip) :
return ip
Now if i invoke it like :
http://127.0.0.1:5000/changeip?ip=1.2.2.2
It spits out "URL not found"...what is that i'm doing wrong here?
The first route describes a url with a value as part of the url. The second url describes a route with no variables, but with a query parameter in the url.
If you are using the first route, the url should look like http://127.0.0.1/changeip/1.2.2.2.
If you are using the second url, the route should look like /changeip, the function should be def change_ip():, and the value should be read from request.args['ip'].
Usually the route should describe any arguments that should always be present, and form or query params should be used for user-submitted data.
You should use:
app.route('/something/<ip>')
def function(ip):
And when you are using url_for, you should pass value of ip aswell:
url_for('function', ip='your_ip_address')
The accepted answer is correct, but I wanted to add the method that it appears the OP was originally trying in his http request.
Another way to pass in variables is through the question mark that separates variables in the url, and using requests.
import requests
Then in the method,
#app.route("/changeip")
def change_ip():
return requests.args.get('ip', '')
For the url, you pass the variable in using the question mark delimiter, the way you were originally trying.
http://127.0.0.1:5000/changeip?ip=1.2.2.2
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.