[PYTHON] Automatically map controllers from URLs in Flask

Flask requires explicit mapping of URLs and methods, as shown below.

# '/'Call the index method when is accessed
@app.route("/"):
def index():
    return "<h1>Hello, World!</h1>"

For example, how to make this a form that automatically calls the index method of the Hello controller (style like Rails or CakePHP) when "/ Hello / index" is accessed.

Directory structure

script

app.py


from flask import Flask
import importlib

app = Flask(__name__)

@app.route("/<path:path>")
def router(path):
    path = path.split("/")
    module_name = "Controller." + path[0]
    module = importlib.import_module(module_name)
    method = getattr(module, path[1])
    return method()

Controller/Hello.py


def index():
    return "<h1>Hello, Controller!</h1>"

If you specify "\ <path: path>" in the route decorator, the requested path will be stored as a character string in the variable path. The path after it is a variable name, so you can enter any name you like (like \ <path: mypath>).

Since the first element of the array that splits this with "/" is the controller name, use import_module of importlib to specify the path to the controller as a string and get the controller.

Finally, use getattr to get the actual method from the method name string and return it.

Serpentine

Now you can implicitly specify the controller without explicitly specifying it! You did it! !!

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
...

That's against Python's philosophy \ (^ o ^) /

Recommended Posts

Automatically map controllers from URLs in Flask
Try to separate Controllers using Blueprint in Flask
Load images from URLs using Pillow in Python 3
Read logging settings from an external file in Flask
How to change static directory from default in Flask
Change static file storage directories and URLs in Flask
Introducing WebPay from Flask
Image uploader in Flask
Automatically map controllers from URLs in Flask
[Django] Create a form that automatically fills in the address from the zip code
How to reflect ImageField in Django + Docker (pillow)
Models in Django
Forms in Django
How to log in automatically like 1Password from the CLI