简体   繁体   中英

Flask- How to import db=SQLAlchemy in separate file

I want to add a new table or add data by calling db , but i got some problem when i try to import db

db return like this <SQLAlchemy engine=None>

which mean i didnt already doing this db.init_app(app)

this is my file struckture

Root
run.py
------>server/__init__.py

Config.py

import os


class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY')
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@localhost/flask_py'
    MAIL_SERVER = 'smtp.googlemail.com'
    MAIL_PORT = 587
    MAIL_USE_TLS = True
    MAIL_USERNAME = os.environ.get('EMAIL_USER')
    MAIL_PASSWORD = os.environ.get('EMAIL_PASS')

Run.py

from server import server_app, db
app = server_app()
if __name__ == '__main__':
    app.run(debug=True)

__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from server.config import Config

db = SQLAlchemy()


    def server_app(config_class=Config):
        app = Flask(__name__)
        app.config.from_object(Config)
        db.init_app(app)
        from server.users.routes import users
        app.register_blueprint(users)
        return app

in my command line using windows i want to import db, i try like this :

D:\PYTHON\root>python
from run import db
db.create_all() 

but when i check is :

<SQLAlchemy engine=None>

I have a full working solution here very similar to what you're doing. Check my layout and then look at the create_db.py.

https://github.com/researcher2/stackoverflow_56885380

It appears in your case the "server_app" is not being executed in your interactive shell. Assuming you are running interactive shell in root directory, you would want to do the following:

from server import db, create_app

app = server_app()    
with app.app_context():
    db.create_all()

The annoying thing about flask-sqlalchemy as opposed to plain sqlalchemy is the db is coupled to a flask app. The db config comes from the flask config and the initiation is done during db_init or just SqlAlchemy(db) if you want the simpler version for single app setup.

Your models would also need to be setup properly. In my example above I just had them in the create_db script.

This post may help you as well regarding factories and blueprints. I created the above github to answer it.

Reflecting different databases in Flask factory setup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM