Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-styled Flask URL pattern for large application

I started off using Django building web apps, and now I'm depending on Flask for most of my projects. I think the decorator @app.route in Flask is straightforward, but once the file grows bigger and bigger, the "django style" url mapping seems to be more favorable.

To accomplish this, I used a work around to mimic Django's url mapping, but I'm not sure if this is a good practice and worried that there might be some performance issue.

Here is a minimal example:

# project/views.py
def index():
    print "hello index!"

def get_users():
    print "hello users!"

# project/urls.py
from project import views

# store url mapping arguments in a list of tuples following this pattern:
# (endpoint, methods, viewfunc)

urls = [
  ('/', ['GET'], views.index),
  ('/users', ['GET'], views.get_users)
]

Then finally:

# project/__init__.py
from flask import Flask
from project.urls import urls

app = Flask(__name__)
# Loop through the urls list to add all url rules to app
for url in urls:
    app.add_url_rule(url[0], methods=url[1], view_func=url[2])

This structure works with no problems and I see a cleaner organization of my code base, but somehow I feel unconfident having a loop inside my __init__.py.

Does anyone have a better solution?

like image 571
benjaminz Avatar asked Oct 19 '22 06:10

benjaminz


1 Answers

You can set up an application factory:

def create_app(name):
    app = Flask(name)
    for url in urls:
        app.add_url_rule(url[0], methods=url[1], view_func=url[2])
    return app

app = create_app(__name__)
like image 175
Daniel Hepper Avatar answered Oct 21 '22 23:10

Daniel Hepper