如何在Flask-RESTPlus中获取请求的资源路径?
如何判断Flask-RESTPlus中GET请求使用的路径
嘿,刚接触Flask和Flask-RESTPlus的话,遇到多个路由绑定同一个资源类的情况确实容易困惑,我来教你两种简单的方法判断当前GET请求走的是哪条路径:
方法一:直接读取request.path获取当前请求路径
Flask会把当前请求的所有上下文信息封装在request对象里,其中request.path就能返回请求的路径字符串。你只需要在Resource类的get方法里调用这个属性,就能明确知道是哪条路由匹配上了。
举个修改后的代码示例:
from flask import request from flask_restplus import Resource, Namespace, Api api = Api() ns = api.namespace('sample', description='get stuff') @ns.route( '/resource-settings/<string:address>', '/unit-settings/<string:address>', '/resource-proposals/<string:address>', '/unit-proposals/<string:address>' ) @ns.param('address', 'The address to decode') class Decode(Resource): @ns.doc(id='Get the decoded resource') def get(self, address): # 获取当前请求的完整路径 current_request_path = request.path # 根据路径判断对应的业务逻辑 if '/resource-settings/' in current_request_path: return { 'status': 'success', 'handler': 'resource-settings', 'address': address, 'requested_path': current_request_path } elif '/unit-settings/' in current_request_path: return { 'status': 'success', 'handler': 'unit-settings', 'address': address, 'requested_path': current_request_path } elif '/resource-proposals/' in current_request_path: return { 'status': 'success', 'handler': 'resource-proposals', 'address': address, 'requested_path': current_request_path } elif '/unit-proposals/' in current_request_path: return { 'status': 'success', 'handler': 'unit-proposals', 'address': address, 'requested_path': current_request_path } else: return {'status': 'error', 'message': 'Unknown path matched'}
方法二:给每个路由指定独立端点(Endpoint)
如果你想通过端点标识来判断,可以在定义路由时给每个路径手动指定不同的endpoint参数,之后通过request.endpoint来区分:
修改后的路由定义示例:
@ns.route( '/resource-settings/<string:address>', endpoint='resource-settings', '/unit-settings/<string:address>', endpoint='unit-settings', '/resource-proposals/<string:address>', endpoint='resource-proposals', '/unit-proposals/<string:address>', endpoint='unit-proposals' )
然后在get方法里判断:
def get(self, address): current_endpoint = request.endpoint # 根据端点处理逻辑(端点格式是「命名空间名.你指定的endpoint」) if current_endpoint == 'sample.resource-settings': return {'handler': 'resource-settings', 'address': address} elif current_endpoint == 'sample.unit-settings': return {'handler': 'unit-settings', 'address': address} # 其他端点同理
不过第一种方法(读取request.path)更直观,不需要额外修改路由定义,适合你当前的场景。
内容的提问来源于stack exchange,提问作者Frank C.
相关产品推荐
相关产品推荐

