[Python] Flask - working outside of application context

Discussão em 'Python' iniciado por Stack, Maio 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am testing a Flask application and am receiving a "working outside of application context" error. My file directory is as follows:

    api
    app.py
    __init__.py
    models
    __init__.py
    user.py
    resources
    __init__.py
    deals.py
    stores.py
    common
    __init__.py
    calculations.py
    decorators.py


    My app.py file looks like the following:

    import os
    from flask import Flask, jsonify, url_for, redirect, request, g, current_app
    from flask_pymongo import PyMongo
    from flask_restful import Api, Resource
    from flask_httpauth import HTTPTokenAuth
    from flask.ext.sqlalchemy import SQLAlchemy
    from flask.ext.httpauth import HTTPBasicAuth

    from resources.deals import Deals
    from resources.stores import Stores

    from models.user import User

    USERDBFILE=os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)),'database'),'db.sqlite')

    #Deals database
    app = Flask(__name__)
    app.config["MONGO_DBNAME"] = "database"
    mongo = PyMongo(app,config_prefix='MONGO')
    app.db = mongo

    #User database
    app.config['SECRET_KEY'] = 'SECRET KEY'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.dbuser = SQLAlchemy(app)

    #App url
    app.APP_URL = "http://127.0.0.1:5000"

    #Setup authorization
    auth = HTTPTokenAuth(scheme='Token')

    #Setup the app
    api = Api(app)
    api.add_resource(Deals, '/deals', '/Deals/<string:type>/<string:id>',endpoint="dealType")
    api.add_resource(Stores, '/stores', '/Stores/<string:type>/<string:id>',endpoint="type")

    if __name__ == "__main__":
    if not os.path.exists(USERDBFILE):
    app.dbuser.create_all()
    app.run(debug=True)


    My users.py file is as follows:

    from flask import current_app
    import os
    from flask import Flask, abort, request, jsonify, g, url_for
    from flask.ext.sqlalchemy import SQLAlchemy
    from flask.ext.httpauth import HTTPBasicAuth
    from passlib.apps import custom_app_context as pwd_context
    from itsdangerous import (TimedJSONWebSignatureSerializer
    as Serializer, BadSignature, SignatureExpired)

    class User(current_app.dbuser.Model):
    __tablename__ = 'user_api'
    id = current_app.dbuser.Column(current_app.dbuser.Integer,primary_key=True)
    date_created = current_app.dbuser.Column(current_app.dbuser.DateTime,default=current_app.dbuser.func.current_timestamp())
    date_modified = current_app.dbuser.Column(current_app.dbuser.DateTime,default=current_app.dbuser.func.current_timestamp(),
    onupdate=current_app.dbuser.func.current_timestamp())
    # User Name
    name = current_app.dbuser.Column(current_app.dbuser.String(128),nullable=False)
    # Identification Data: email & password
    email = current_app.dbuser.Column(current_app.dbuser.String(128),nullable=False,unique=True)
    password = current_app.dbuser.Column(current_app.dbuser.String(192),nullable=False)
    company = current_app.dbuser.Column(current_app.dbuser.String(128),nullable=False,unique=True)
    # Authorization Data: role & status
    role = current_app.dbuser.Column(current_app.dbuser.String(32),nullable=False,default='user')
    status = current_app.dbuser.Column(current_app.dbuser.Boolean,nullable=False,default=True)
    hourly_limit = current_app.dbuser.Column(current_app.dbuser.Integer,nullable=False,default=100)
    daily_limit = current_app.dbuser.Column(current_app.dbuser.Integer,nullable=False,default=2400)
    monthly_limit = current_app.dbuser.Column(current_app.dbuser.Integer,nullable=False,default=2400)
    admin = current_app.dbuser.Column(current_app.dbuser.Boolean,nullable=False,default=True)

    def hash_password(self, password):
    self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
    return pwd_context.verify(password, self.password_hash)

    def generate_auth_token(self, expiration=600):
    s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
    return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
    data = s.loads(token)
    except SignatureExpired:
    return None # valid token, but expired
    except BadSignature:
    return None # invalid token
    user = User.query.get(data['id'])
    return user


    I run the file in the same directory as app.py using

    python app.py


    But it returns the following error:

    File "app.py", line 13, in <module>
    from models.user import User
    File "/Users/toby/api/api/models/user.py", line 10, in <module>
    class User(current_app.dbuser.Model):
    File "/Users/toby/api/venv/lib/python3.4/site-packages/werkzeug/local.py", line 343, in __getattr__
    return getattr(self._get_current_object(), name)
    File "/Users/toby/api/venv/lib/python3.4/site-packages/werkzeug/local.py", line 302, in _get_current_object
    return self.__local()
    File "/Users/toby/api/venv/lib/python3.4/site-packages/flask/globals.py", line 34, in _find_app
    raise RuntimeError('working outside of application context')
    RuntimeError: working outside of application context


    If I move the contents of the user.py file into the app.py file and change the inheritance from current_app.dbuser.Model to app.dbuser.Model it seems to work fine. Does anyone know what I am doing wrong?

    Continue reading...

Compartilhe esta Página