Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use flask.url_for() with flask-restful?

I have setup Flask restful like this:

api = Api(app, decorators=[csrf_protect.exempt])
api.add_resource(FTRecordsAPI,
                 '/api/v1.0/ftrecords/<string:ios_sync_timestamp>',
                 endpoint="api.ftrecord")

I would like to redirect internally to the endpoint api.ftrecord.

But the moment I try to do this:

base_url = flask.url_for('api.ftrecord')

I get an exception.

  File "/Users/hooman/workspace/F11A/src/lib/werkzeug/routing.py", line 1620, in build
    raise BuildError(endpoint, values, method)
BuildError: ('api.ftrecord', {}, None)

What am I missing please?

like image 751
Houman Avatar asked Jun 14 '14 19:06

Houman


People also ask

What does Flask's url_for () do?

Flask url_for is defined as a function that enables developers to build and generate URLs on a Flask application. As a best practice, it is the url_for function that is required to be used, as hard coding the URL in templates and view function of the Flask application tends to utilize more time during modification.

What is the difference between Flask and flask RESTful?

Flask is a highly flexible Python web framework built with a small core and easy-to-extend philosophy. Flask-Restful is an extension of Flask that offers extension to enable writing a clean object-oriented code for fast API development.


3 Answers

You'll need to specify a value for the ios_sync_timestamp part of your URL:

flask.url_for('api.ftrecord', ios_sync_timestamp='some value')

or you could use Api.url_for(), which takes a resource:

api.url_for(FTRecordsAPI, ios_sync_timestamp='some value')
like image 103
Martijn Pieters Avatar answered Sep 28 '22 08:09

Martijn Pieters


I had this problem today. Here's the pull request that added the functionality (11 months ago):

https://github.com/twilio/flask-restful/pull/110

You can see his example usage there.

In my resources file, I do not have access to the app context. So I had to do this:

from flask.ext import restful
from flask import current_app

api = restful.Api
print api.url_for(api(current_app), UserResource, user_id=user.id, _external=True)

Hope that helps.

like image 26
Miles Richardson Avatar answered Sep 28 '22 08:09

Miles Richardson


api = Api(app, decorators=[csrf_protect.exempt])
api.add_resource(FTRecordsAPI,
                 '/api/v1.0/ftrecords/<string:ios_sync_timestamp>',
                 endpoint="api.ftrecord")
with app.test_request_context():
    base_url = flask.url_for('api.ftrecord')

I met the same error. By using 'with app.test_request_context():', it works.

like image 30
user3131182 Avatar answered Sep 28 '22 08:09

user3131182