Search code examples
pythonflaskpeewee

Does using functionality needed to interface with current app means creating view in flask?


in my flask app app/__init__.py I have included the below function

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

now I also have /app/datastore/core.py in which I have

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

when I create my run my app start.py it creates the app object but when I try access the URL in browser I get error saying

 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.

what am I doing wrong here?


Solution

  • what am I doing wrong here?

    Just about everything.

    Peewee already exposes database connections as a threadlocal so what you're doing is senseless. Especially given from reading your comments you are only trying to add connection hooks.

    The peewee docs are QUITE CLEAR: http://docs.peewee-orm.com/en/latest/peewee/database.html#flask

    As an aside, read the damn docs. How many questions have you posted already that could have been easily answered just by reading the documentation?