You can do this as is described in the Flask documentation, basically by calling app.add_url_rule
to set your routes rather than using the decorator.
Making urls.py file for Flask like in Django
-
30-11-2021 - |
题
Maybe someone can help/explain me, how to create urls.py
file for Flask like in Django?
main.py
- main project file. It includes only app runner (app.run()
).urls.py
is situated in the same directory and need to provide views fromviews.py
.
解决方案
其他提示
In addition to the Flask documentation, this can be solved like this:
When creating the Flask app load your 'urls.py' file
app.register_blueprint(apps.someapp.urls.mod)
Then structure urls.py as following:
from flask import Blueprint
from apps.someapp.views import SomeView
# set method as endpoint
view = SomeView.as_view('someview')
# Create the blueprint for this app
mod = Blueprint("payment_methods", __name__, url_prefix="/someapp/", template_folder="templates")
# Add the view as route; methods like GET, POST, PUT will automatically route to class methods with parameters
mod.add_url_rule('<int:id>/', view_func=view)
不隶属于 StackOverflow