python - Flask 与 项目内其他 SQLalchemy 如何共用 Models 文件?
伊谢尔伦
伊谢尔伦 2017-04-17 13:33:30
0
3
366

有一需求:Web 框架用 Flask 在同一个项目内(例:Project)目录结构如下

myProject
|- app1
|- app2
|- Flask-app

app1 是一个简单爬虫, app2 是一个数据分析,都不是 Flask 应用,能不能定义一组 Model 使这三个 app 都共用这一组 model,并且使项目结构如下:

myProject
|- app1
|- app2
|- Flask-app
|- models

P.S. 已用 Flask-SQLalchemy

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(3)
洪涛

Yes, the simplest way is, sys.path.append('the directory where models are located'), and then you can import

Peter_Zhu

If multiple frameworks are mixed, use pure sqlalchemy instead of flask-sqlalchemy.

Ty80

1. Create a initdb.py in the project root directory, which is your myProject directory, and the user initializes SQLAlchemy, for example:

from flask.ext.sqlalchemy import SQLAlchemy

__all__ = ['db']

db = SQLAlchemy()

2. Similarly, create a shared application.py file in the root directory, which is used to create apps, for example:

from initdb import db

def create_app(app):
    db.init_app(app)

    return app

3. Create a __init__.py file in each individual app to initialize the app, for example:

from flask import Flask

app = Flask(__name__)

4. Create a app.py file in each separate app to start the separate app, for example:

import sys
sys.path.append('你的项目根目录,也就是你的myProject')

from application import create_app
from app1 import app as _app

application = create_app(_app)
if __name__ == "__main__":
    application.run(port=9000, host='0.0.0.0', debug=True)

5. You can create a models directory in the root directory to store all database models.
6. When using it in the view, you only need to enter the required import.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!