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.
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.
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