簡體   English   中英

如何使用Flask-Restful訪問具有多個端點的資源?

[英]How do I access a resource with multiple endpoints with Flask-Restful?

這是一個簡單的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')

我的想法是允許用戶同時調用/list/api/list 如果他們使用第一個URL,他們將返回數據的HTML表示。 如果他們使用第二個URL,他們將獲得JSON表示。

我的麻煩是我想在程序的其他地方訪問此端點的URL。 我不能只使用url_for('list') ,因為無論用戶是訪問過http://host.example.com/list還是http://host.example.com/api/list ,都會返回/list http://host.example.com/api/list

那么如何構建/api/list的URL呢?

看起來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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM