使用与当前应用程序交互所需的功能是否意味着在flask中创建视图?

时间:2019-01-03 10:30:09

标签: python flask peewee

在我的烧瓶应用程序app/__init__.py中,我包含了以下功能

def create_app(config_filename=None):
    _app = Flask(__name__, instance_relative_config=True)
    with _app.app_context():
        print "Creating web app",current_app.name
        cors = CORS(_app, resources={r'/*': {"origins": "*"}})
        sys.path.append(_app.instance_path)
        _app.config.from_pyfile(config_filename)
        from config import app_config
        config = app_config[_os.environ.get('APP_SETTINGS', app_config.development)]
        _app.config.from_object(config)
        register_blueprints(_app)
        # _app.app_context().push()
        return _app

现在我也有/app/datastore/core.py,其中

import peewee
import os

from flask import g, current_app
cfg = current_app.config    
dbName = 'clinic_backend'


def connect_db():
    """Connects to the specific database."""
    return peewee.MySQLDatabase(dbName, 
    user=cfg['DB_USER'], 
    host=cfg['DB_HOST'], 
    port=3306, 
    password=cfg['DB_PWD']
    )

def get_db():
    """ Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'db'):
        g.db = connect_db()
    return g.db

当我创建运行我的应用start.py时,它会创建应用对象,但是当我尝试在浏览器中访问URL时,出现错误提示

 File "/Users/ciasto/Development/python/backend/app/datastore/core.py",
 line 31, in get_db
     g.db = connect_db()   File "/Users/ciasto/Development/python/backend/venv/lib/python2.7/site-packages/werkzeug/local.py",
 line 364, in <lambda>
     __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)   File
 "/Users/ciasto/Development/python/backend/venv/lib/python2.7/site-packages/werkzeug/local.py",
 line 306, in _get_current_object
     return self.__local()   File "/Users/ciasto/Development/python/backend/venv/lib/python2.7/site-packages/flask/globals.py",
line 44, in _lookup_app_object
    raise RuntimeError(_app_ctx_err_msg) RuntimeError: Working outside of application context.

 This typically means that you attempted to use functionality that
 needed to interface with the current application object in some way.
 To solve this, set up an application context with app.app_context(). 
 See the documentation for more information.

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

  

我在做什么错了?

关于一切。

Peewee已经将数据库连接公开为局部线程,因此您所做的事情毫无意义。特别是阅读您的评论后,您只会尝试添加连接挂钩。

peewee文档非常清晰:http://docs.peewee-orm.com/en/latest/peewee/database.html#flask

顺便说一句,请阅读该死的文档。您已经发布了多少个问题,仅阅读文档便可以轻松回答?