[英]How do I use flask.url_for() with flask-restful?
I have setup Flask restful like this: 我已经像这样设置了Flask:
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
. 我想在内部重定向到端点
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? 我错过了什么?
You'll need to specify a value for the ios_sync_timestamp
part of your URL: 您需要为URL的
ios_sync_timestamp
部分指定一个值:
flask.url_for('api.ftrecord', ios_sync_timestamp='some value')
or you could use Api.url_for()
, which takes a resource: 或者你可以使用
Api.url_for()
,它需要一个资源:
api.url_for(FTRecordsAPI, ios_sync_timestamp='some value')
I had this problem today. 我今天遇到了这个问题。 Here's the pull request that added the functionality (11 months ago):
这是添加功能的拉取请求(11个月前):
https://github.com/twilio/flask-restful/pull/110 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. 希望有所帮助。
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.
通过使用'with app.test_request_context():',它可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.