How to organize a relatively large Flask application?

前端 未结 6 1958
渐次进展
渐次进展 2020-12-12 09:57

I\'m building my first Flask app and I can\'t figure out a good, clean Pythonic way of organizing my application. I don\'t want to have everything in a single .py file as in

6条回答
  •  攒了一身酷
    2020-12-12 10:39

    I'm working on a (by my standards) big Flask project (5000 lines of Python code and it's only half-finished). The customer wants the project to be modular, so I took this apporach:

    My folder structure looks like this:

    ├── __init__.py
    ├── modules.yml
    ├── config
    ├── controllers
    │   └── ...
    ├── lib: Common functions I use often
    │   └── ...
    ├── models
    │   └── ...
    ├── static: All static files
    │   ├── css
    │   ├── img
    │   └── js
    └── templates: Jinja2 templates
        └── ...
    

    In modules.yml I define my modules including name and URL. This way the customer is able to enable/disable modules without touching a single Python file. In addition, I generate the menus based on the modules list. By convention every module has it its own Python-module in controllers/ that will load its model from models/. Every controller defines a Blueprint stored as the controller's name. E.g. for a user module, I have in controllers/user.py:

    # Module name is 'user', thus save Blueprint as 'user' variable
    user = Blueprint('user', __name__)
    
    @user.route('/user/')
    def index():
        pass
    

    This way, I can read the modules.yml in my __init__.py and load and register all enabled modules dynamically:

    # Import modules
    for module in modules:
    
        # Get module name from 'url' setting, exculde leading slash
        modname = module['url'][1:]
    
        try:
            # from project.controllers. import 
            mod = __import__(
                'project.controllers.' + modname, None, None, modname
            )
        except Exception as e:
            # Log exceptions here
            # [...]
    
        mod = getattr(mod, modname)  # Get blueprint from module
        app.register_blueprint(mod, url_prefix=module['url'])
    

    I hope, this can be some inspiration for you :)

提交回复
热议问题