2016-04-27 18 views
0

我有這樣一個應用程序:使用分貝,而無需app.app_context() - 瓶

MyApp的/應用/ 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的/應用/ 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.pydatabase.py中看到的所有內容都在app/__init__.py中時,它的工作原理不需要任何with application.app_context(),我可以在外殼中導入db原始外殼,如from myapp.app import db,並且按原樣工作。我能做些什麼安靜的application not registered on db投訴,但能夠輕鬆地使用db無需app_context,但仍保持在那裏一切都沒有擠進init一個正確的目錄結構?謝謝

回答

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()