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)
Related
Why am I able to call to and return variable (HTTP request) properties from this function without passing a parameter first?
How does the f in f"abc123" work?
import requests
def oauth(r):
r.headers["Authorization"] = f"abc123"
r.headers["User-Agent"] = "v2TweetLookupPython"
return r
my_json = requests.request("GET", url, auth=oauth).json()
The call to the oauth function in auth=oauth is successful, without having to pass its parameter, r. With the requests module, is the single character 'r' an implicit reference to a requests object?
Because you're not calling the function oauth, but just passing the object oauth as parameter to the optional argument auth of requests.request.
The requests.request itself calls the oauth when appropriate passing the r parameter. Look at what the documentation says about the optional parameter auth from requests.request:
Default Authentication tuple or object to attach to Request.
You only call a function when you use parenthesis at the end.
auth is taking in a function as a parameter value.
This is allowed in Python, as functions are first-class. That function may be called somewhere in the requests package, but this is a detail that packages are meant to abstract away; all you need to know is that the auth parameter is given as a function that takes in one parameter.
The f refers to a format string -- but in this case, the f is redundant since there aren't any dynamically evaluated expressions to be placed inside the string.
1.) The requests.request function takes a function as its auth argument and evaluates the first argument of the function with a request. So, you pass your oauth function to requests.request function and it automatically evaluates this function with the request as the argument you call r.
You can see this if you just print r inside oauth when you run the code:
import requests
url = 'https://httpbin.org/get'
def oauth(r):
print(f'r is {r} of type {type(r)}')
r.headers["Authorization"] = f"abc123"
r.headers["User-Agent"] = "v2TweetLookupPython"
return r
my_json = requests.request("GET", url, auth=oauth).json()
print(my_json)
Note that I'm just using a test url here.
2.) A letter before a string modifies the type of string. So f'string' makes this a "formattable" string. For example, suppose I wanted a function that takes a string variable with a person's name and outputs a hello message based on that string variable. I could do something like:
def helloMessage(name):
return f'Hello {name}, welcome.'
If I called helloMessage('Bob') it would return 'Hello Bob, welcome.'
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
I'm using the requests module in my code (obviously to do requests), and my code is quickly getting out of hand because of redundant parameters that I need to include for each request:
def one(url, data, headers, cert):
...
return requests.post(url, json=data, headers=headers, verify=cert)
def two(otherurl, otherheaders, cert):
...
response = requests.get(otherurl, headers=otherheaders, verify=cert).json()
Is there a way to tell every request to use verify=cert without having to include it within every request statement? I'm thinking session() should be able to do this, although I have no idea how to use it. I'm just trying to minimize the repeating of things that maybe could be set globally within my script. Maybe this is not possible or how it actually works? thanks in advance.
You can use functools.partial to override these functions with verify=cert passed as an argument by default:
from functools import partial
requests.post = partial(requests.post, verify=cert)
requests.get = partial(requests.get, verify=cert)
Or if you look at the source code of requests, you'll find that both of these two functions are simply wrappers to the requests.request function, which in turn is a wrapper to the requests.Session.request method. You can therefore override requests.Session.request instead to have all the HTTP methods overridden with one statement. Since it's a method and not an unbound function, however, you have to use functools.partialmethod instead:
from functools import partialmethod
requests.Session.request = partialmethod(requests.Session.request, verify=cert)
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.