How do I split Flask models out of app.py without passing db object all over?

前端 未结 2 1314
闹比i
闹比i 2021-01-02 06:14

I\'d like to use Flask-Migrate and am looking at their example:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script imp         


        
2条回答
  •  温柔的废话
    2021-01-02 07:07

    Here is an idea. You can create a package model in which you define classes as individual .py files. For example, user.py contains the User class.

    In the __init__.py file you can define the db variable. You may also include from user import User statement so that it would be possible to access User object directly outside the package. For example you can import the model package somewhere else in the program using import model and then use model.User to directly use the User class.

    To use db variable directly in the user.py use from ..model import db which imports db variable defined in the __init__.py file.

提交回复
热议问题