[英]How do I access a resource with multiple endpoints with Flask-Restful?
Here's a simple Flask-Restful resource: 这是一个简单的Flask-Restful资源:
class ListStuff(Resource):
def get(self):
stuff = SomeFunctionToFetchStuff()
if re.match('/api/', request.path):
return {'stuff': stuff}
return make_response("{}".format(stuff), 200, {'Content-Type': 'text/html'})
api.add_resource(ListStuff, '/list', '/api/list', endpoint='list')
My idea is to allow users to call both /list
and /api/list
. 我的想法是允许用户同时调用
/list
和/api/list
。 If they use the first URL, they will get back an HTML representation of the data. 如果他们使用第一个URL,他们将返回数据的HTML表示。 If they use the second URL, they will get a JSON representation.
如果他们使用第二个URL,他们将获得JSON表示。
My trouble is when I want to access the URL of this endpoint elsewhere in the program. 我的麻烦是我想在程序的其他地方访问此端点的URL。 I can't just use
url_for('list')
, because that will always return /list
, no matter whether the user accessed http://host.example.com/list
or http://host.example.com/api/list
我不能只使用
url_for('list')
,因为无论用户是访问过http://host.example.com/list
还是http://host.example.com/api/list
,都会返回/list
http://host.example.com/api/list
So how can I build the URL for /api/list
? 那么如何构建
/api/list
的URL呢?
Looks like Hassan was on the right track - I can add a new resource for the same class but give it a different endpoint. 看起来Hassan在正确的轨道上 - 我可以为同一个类添加一个新资源,但给它一个不同的端点。
api.add_resource(ListStuff, '/list', endpoint='list')
api.add_resource(ListStuff, '/api/list', endpoint='api-list')
>>> print('URL for "list" is "{}"'.format(url_for('list'))
>>> print('URL for "api-list" is "{}"'.format(url_for('api-list'))
URL for "list" is "/list"
URL for "api-list" is "/api/list"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.