允许在Flask中使用所有方法类型

2024-03-29 06:59:31 发布

您现在位置:Python中文网/ 问答频道 /正文

如何允许路由接受所有类型的方法?在

我不想只路由标准方法,比如HEADGETPOSTOPTIONSDELETE&;PUT。在

我希望它也接受以下方法:FOOBARWHYISTHISMETHODNAMESOLONG&;每隔一个可能的方法名。在


Tags: 方法路由类型标准getputdeletepost
3条回答

您可以直接为此更改url映射,方法是添加一个^{},而不使用任何方法:

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

A sequence of http methods this rule applies to. If not specified, all methods are allowed.

下面是一些代码(我已经删减了)from the Flask app object。这段代码处理添加一个url规则(这也是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的,而生产线。。。在

^{pr2}$

…通常使用Werkzeug's Rule类。这个类有关于“methods”参数的以下文档。。。在

A sequence of http methods this rule applies to. If not specified, all methods are allowed.

所以,这告诉我你也许可以做如下的事情。。。在

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

要快速启用a route的所有HTTP Request Methods,而无需手动向烧瓶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

相关问题 更多 >