如何允许路由接受所有类型的方法?
我不只是想路由标准方法,如HEAD
, GET
, POST
, OPTIONS
, DELETE
& PUT
。
我希望它也接受以下方法:FOOBAR
, WHYISTHISMETHODNAMESOLONG
&所有其他可能的方法名称。
您可以为此直接更改 url_map,方法是添加一个Rule
不带方法的:
from flask import Flask, request
import unittest
from werkzeug.routing import Rule
app = Flask(__name__)
app.url_map.add(Rule('/', endpoint='index'))
@app.endpoint('index')
def index():
return request.method
class TestMethod(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
def test_custom_method(self):
resp = self.client.open('/', method='BACON')
self.assertEqual('BACON', resp.data)
if __name__ == '__main__':
unittest.main()
methods
此规则适用的一系列 http 方法。如果未指定,则允许所有方法。
要在不手动向 Flask 中添加规则的情况下快速启用所有HTTP 请求方法,请修改定义如下:route
url_map
route
from flask import request
HTTP_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH']
@app.route('/', methods=HTTP_METHODS)
def index():
return request.method
见下文,这是来自 Flask app object的一些代码(我已删减)。此代码处理添加 url 规则(当您在视图上执行 app.route() 时,flask 也会调用该规则)......
@setupmethod
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
""" I remove a ton the documentation here.... """
if endpoint is None:
endpoint = _endpoint_from_view_func(view_func)
options['endpoint'] = endpoint
methods = options.pop('methods', None)
# if the methods are not given and the view_func object knows its
# methods we can use that instead. If neither exists, we go with
# a tuple of only `GET` as default.
if methods is None:
methods = getattr(view_func, 'methods', None) or ('GET',)
methods = set(methods)
# ... SNIP a bunch more code...
rule = self.url_rule_class(rule, methods=methods, **options)
rule.provide_automatic_options = provide_automatic_options
self.url_map.add(rule)
如您所见,Flask 将尽最大努力确保明确定义方法。现在,Flask 是基于 Werkzeug 的,并且生产线...
rule = self.url_rule_class(rule, methods=methods, **options)
...通常使用Werkzeug 的 Rule类。此类具有以下有关“方法”参数的文档...
此规则适用的一系列 http 方法。如果未指定,则允许所有方法。
所以,这告诉我你可能能够做如下的事情......
from werkzeug.routing import Rule
app = Flask(__name__)
def my_rule_wrapper(rule, **kwargs):
kwargs['methods'] = None
return Rule(rule, **kwargs)
app.url_rule_class = my_rule_wrapper
我还没有对此进行测试,但希望这可以让你走上正轨。
编辑:
或者您可以只使用 DazWorrall 的答案,这似乎更好:P