I have a flask-RESTful endpoint defined by:
class SearchEvents(Resource):
def get(self, name, start_date, end_date):
#do stuff
api.add_resource(endpoints.SearchEvents, '/events/<string:name>/<string:start_date>/<string:end_date>')
I'm testing it manually with Postman. I'd like to pass in null values for start_date and end_date. However:
I've tried modifying the url to:
http://127.0.0.1:5000/events/test/ / #<--Spaces
and
http://127.0.0.1:5000/events/test/""/""
To no avail.
Ended up solving this by using the flask-restful request object, which has an args property which retrieves query params from the request url:
from flask_restful import request #import request from flask restful
class SearchEvents(Resource):
def get(self):
args = request.args #retrieve args from query string
api.add_resource(endpoints.SearchEvents, '/events')
And then making the requests like: http://127.0.0.1:5000/events?param1=value1¶m2=value2
Or to pass null values: http://127.0.0.1:5000/events?param=¶m2=value1
The values you are passing are not in the query string. You are using route parts as parameters so the route does not get matched unless you supply something of the form /events/some_name/2019-86-98/2100-9885-24515. The attempts you made are catched by flask as non matching routes and you get 404 not found.
To send those parameters as part of the query string would be to use something like
/events?name=some_name&start_date=2019-86-98&end_date=2100-9885-24515 and to get the values in your route handlers you should use name = request.args.get('name') and so on. Passing null values then means hitting the same url but without the query parameters.
Related
Hi Everyone I'm just searching for the feature of Flask.
What I want to do is to branch controller with query-parameter like Spring #RequestMapping EXAMPLE
I want Flask Controller to work when specific params exist.
Do that features exist In Flask?
I don't want to branch with if statement in method
I dont want to like this.
from flask import request
#app.route('/user')
def user():
actions = request.args.get('actions')
if actions == "migration"
pass
if actions == "something"
pass
....
I want to like this
#app.route('/user', params={"actions=migration"})
def user_migration():
pass
#app.route('/user', params={"actions=something"})
def user_something():
pass
You can just add that logic in your "controller" itself, like so:
from flask import request
#app.route('/home/fetch')
def data():
# here we want to get the value of user (i.e. ?personId=some-value)
personId = request.args.get('personId')
if personId == <your-value-here>
If you know what your params are always going to be then why not just set it to the route itself:
#app.route('/user/migration')
def user_migration():
pass
#app.route('/user/something')
def user_something():
pass
I'm building a webapp where you can add Player-Profiles into a table to compare these. I've posted all changes to same URL, now I found out that the changes are seen by all users.
I considered how to fix this: Instead of url .../stats I tried to individualize url for every Profile added to the table like .../stats?id=237 (for one profile) .../stats?id=237id=335 (for two profiles).
Method for the stats:
#app.route('/stats/', methods=['POST', 'GET'])
def pstats():
...
...
urla= [237, 335]
return redirect(url_for('pstats', data = urla ))
route: .../stats
route: .../stats?id=237
route: .../stats?id=237id=335
How can I write the route of pstats dynamically that it can look like 1. route or 2. route?
Use request.args to get the query parameters that are passed to your route.
#app.route('/stats/', methods=['POST', 'GET'])
def pstats():
id = request.args['id']
Pass id to url_for to generate a URL that contains query parameters.
url_for(url_for('pstats', id=id))
I have a complex DRF ViewSet that supports paging, filtering, sorting, etc. that backends a grid view. To build an "export" capability, I need to be able to take the same querystring that my endpoint uses, such as:
?obj_id=129&ordering=latitude&city__icontains=nap
And be able to, in Django, send that string into DRF somehow and get the fully-modified queryset after all the view's filters, sorts, etc are applied (the same way as the GET did). I could use the fully-rendered json response or some interim filter-applied queryset. Is it possible to use DRF in this way?
You should write a CSV renderer for your viewset and get that content-type to export the CSV.
There's even one already available.
Yes you could, if you already have a request object i.e. If you want to use this DRF viewset into another view which has the request object:
def another_view(request):
# make a copy of the `GET` attribute of request object
request.GET = request.GET.copy()
# now you can set the query params on this GET object
# ?obj_id=129&ordering=latitude&city__icontains=nap
request.GET['obj_id'] = 129
request.GET['ordering'] = 'latitude'
request.GET['city__icontains'] = 'nap'
# you can also set paging options in similar way
# now instantiate the viewset
vs = DRFViewset.as_view()
# call the view for response
# set kwargs as you need
response = vs(request, *args, **kwargs)
# response.data will have what you want here
i'm wondering how to fetch GET parameters in flask-restful like his
/hi/city?=NY
i can do like this /hi/city/NY using /hi/city/<string:ccc> but how to do so with /hi/city?=NY .
i checked the documentation and it seems like using reqparse : http://flask-restful.readthedocs.org/en/latest/reqparse.html but still couldn't figure out how
You can use the RequestParser bundled along with Flask-Restful.
from flask_restful import reqparse
class YourAPI(restful.Resource):
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('city')
args = parser.parse_args()
city_value = args.get('city')
By default, the request parser searches json, form fields and query string (as it is in your case) for the key named city. The variable city_value will have the value passed in the API request.
You can use request.args.get('key')
https://xxxx/category_check_view/?item_id=2
Above is a sample of URL pattern. How should i configured my URL in order to enable it to redirect to the right view?
I seem to get it working for a url like this https://xxxx/category_check_view/2/ only so far.
You can pass parameters to a view either in the url:
/category_check_view/2
Or via GET params:
/category_check_view/?item_id=2
GET params are not processed by the URL handler, but rather passed directly to the GET param dict accessible in a view at request.GET.
The Django (i.e. preferred) way to do handle URLs is the first one. So you would have a URL conf:
(r'^category_check_view/(\d{4})$', 'proj.app.your_view'),
And a matching view:
def your_view(request, id):
obj = Obj.objects.get(id=id)
# ...
However, if you insist on passing the param via GET you would just do:
(r'^category_check_view$', 'proj.app.your_view'),
And:
def your_view(request):
id = request.GET.get('item_id')
obj = Obj.objects.get(id=id)
# ...
You can't use get parameters in URL pattern. Use them in your view:
item_id = request.GET.get('item_id')