使用db而不需要app.app_context() - Flask

时间:2016-04-27 23:32:11

标签: python python-3.x flask sqlalchemy flask-sqlalchemy

我有一个这样的应用程序:

MyApp的/应用/的初始化的.py:

import sqlite3
from contextlib import closing

from flask import Flask, g
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

# from app.models import db
from database import db

application = Flask(__name__)
application.config.from_object('config')
application.debug = True

db.init_app(application)

login_manager = LoginManager()
login_manager.init_app(application)

from app import views

的myapp / database.py:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

MyApp的/应用/ models.py:

from database import db
from app import application


class CRUDMixin(object):

    ...

    def delete(self, commit=True):
        """Remove the record from the database."""
        with application.app_context():
            db.session.delete(self)
            return commit and db.session.commit()


class Model(CRUDMixin, db.Model):
    """Base model class that includes CRUD convenience methods."""
    __abstract__ = True

    def __init__(self, **kwargs):
        db.Model.__init__(self, **kwargs)


class User(Model):
    """
    :param str email: email address of user
    :param str password: encrypted password for the user
    """
    __tablename__ = 'users'

    email = db.Column(db.String, primary_key=True)
    password = db.Column(db.String)
    authenticated = db.Column(db.Boolean, default=False)

    def is_active(self):
        """True, as all users are active."""
        return True

    def get_id(self):
        """Return the email address to satisfy Flask-Login's requirements."""
        return self.email

    def is_authenticated(self):
        """Return True if the user is authenticated."""
        return self.authenticated

    def is_anonymous(self):
        """False, as anonymous users aren't supported."""
        return False

我尝试构建的项目在with application.app_context()助手类中不需要Model。我无法看到我的设置与其设置之间存在任何显着差异,但如果没有with application.app_context()所有与db相关的内容,我会收到通常的application not registered on db错误。当您在app/models.pydatabase.py中看到的所有内容都在app/__init__.py中时,它可以在不需要任何with application.app_context()的情况下工作,我可以在shell中导入db raw from myapp.app import db 1}}它按原样运行。我可以做些什么来安抚application not registered on db投诉但能够轻松使用db而不需要app_context,但仍保留一个正确的目录结构,其中所有内容都不会被卡入init {{1}} 1}?谢谢

1 个答案:

答案 0 :(得分:0)

Flask-Script为您提供shell

如果您想在没有Flask-Script的情况下执行此操作,则必须设置应用程序上下文。普通的Python shell并不知道如何设置上下文。

很容易模仿Flask-Script shell。

创建shell.py文件:

from app import application
ctx = application.app_context()
ctx.push()

使用python -i运行它并使用db并已定义您的应用上下文:

$ python -i shell.py 
>>> from app import db
>>> db.create_all()