【发布时间】:2016-04-27 23:32:11
【问题描述】:
我有一个这样的应用:
myapp/app/init.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/app/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
我尝试构建的项目在 Model 助手类中不需要 with application.app_context()。我看不到我的设置与其设置之间有任何显着差异,但是没有with application.app_context() 与db 相关的任何东西我都会得到通常的application not registered on db 错误。当您在app/models.py 和database.py 中看到的所有内容都在app/__init__.py 中时,它不需要任何with application.app_context() 就可以工作,我可以像from myapp.app import db 一样在shell 中导入db raw 并且它按原样工作。我可以做些什么来消除application not registered on db 的投诉,但能够轻松使用db 而无需app_context,但仍然保持适当的目录结构,其中所有内容都不会卡在init 中?谢谢
【问题讨论】:
标签: python python-3.x flask sqlalchemy flask-sqlalchemy