Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow ALL method types in flask route

Tags:

python

flask

How can I allow a route to accept all types of methods?

I don't just want to route the standard methods like HEAD, GET, POST, OPTIONS, DELETE & PUT.

I would like it to also accept the following methods: FOOBAR, WHYISTHISMETHODNAMESOLONG & every other possible method names.

like image 815
Tyilo Avatar asked May 17 '13 14:05

Tyilo


People also ask

How are routes defined in Flask?

Routing in FlaskThe route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result. Here, URL '/hello' rule is bound to the hello_world() function.

How do I change my route in Flask?

The decorator is taking your function as an input and performing some actions to correlate the path with your given input. This can obviously be used for many other purposes. For example, flask also allows an additional decorator to define the type of request allowed for the function, such as GET, POST, etc.


1 Answers

You can change the url_map directly for this, by adding a Rule with no methods:

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.

like image 107
DazWorrall Avatar answered Sep 28 '22 12:09

DazWorrall