I have a Flask server which loads Tensorflow models on startup in an external service module.
The problem is if debug mode is enabled, so FLASK_DEBUG = 1, the app crashes because it is not able to load a certain module from Tensorflow. tensorflow_core.keras to be precise.
However, running the application without debugging works.
The project structure looks like this:
controllers/
__init__.py # Exposes controllers_blueprint
controller.py
services/
service.py
__init__.py # Exposes app, socketio
model_util.py # Used to load models, imports Tensorflow
server.py
So, in a services/service.py, on module load, I call a function which does the job:
import model_util
def _load_models():
# Loading models here using model_util.load(..)
return models
_models = _load_models()
This module gets imported from a controllers/controller.py
from services import service
from flask import current_app, request
from application import socketio
NAMESPACE = '/test'
#socketio.on('connect', namespace=NAMESPACE)
def handle_connect():
service.create_session(request.sid)
Where the controllers/__init__.py exposes a controller_blueprint:
from flask import Blueprint
from controllers import controller
controllers_blueprint = Blueprint('controllers', __name__)
Which then gets registered in my server.py
from flask import current_app
from controllers import controllers_blueprint
from application import app, socketio
def main():
app.register_blueprint(controllers_blueprint)
socketio.run(app)
if __name__ == '__main__':
main()
For completeness, this is __init__.py
from flask import Flask
from flask_caching import Cache
from flask_socketio import SocketIO
HTTP_SERVER_PORT = 5000
app = Flask(__name__, static_folder='../static', static_url_path='')
cache = Cache(config={'CACHE_TYPE': 'simple'})
cache.init_app(app)
socketio = SocketIO(app)
socketio.init_app(app)
Also model_util.py is where the Tensorflow modules are being imported:
import tensorflow as tf
from tensor2tensor.data_generators.text_encoder import SubwordTextEncoder
# ...
def load(...):
# ..
pass
The error I am getting is
Traceback (most recent call last):
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/flask/__main__.py", line 15, in <module>
main(as_module=True)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/flask/cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/click/decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/flask/cli.py", line 860, in run_command
extra_files=extra_files,
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/werkzeug/serving.py", line 1050, in run_simple
run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/werkzeug/_reloader.py", line 337, in run_with_reloader
reloader.run()
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/werkzeug/_reloader.py", line 202, in run
for filename in chain(_iter_module_files(), self.extra_files):
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/werkzeug/_reloader.py", line 24, in _iter_module_files
filename = getattr(module, "__file__", None)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/tensorflow/__init__.py", line 50, in __getattr__
module = self._load()
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/site-packages/tensorflow/__init__.py", line 44, in _load
module = _importlib.import_module(self.__name__)
File "/Users/sfalk/miniconda3/envs/web-service/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'
What is the reason for this and how can I resolve this issue?
Additional Information
I am running the application with PyCharm. This is the output on startup:
FLASK_APP = application/server.py
FLASK_ENV = development
FLASK_DEBUG = 1
In folder /Users/sfalk/workspaces/git/web-service
/Users/sfalk/miniconda3/envs/web-service/bin/python -m flask run
* Serving Flask app "application/server.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 298-908-268
Apparently there is a bug in werkzeug which is used by flask to serve flask apps, when running flask apps in debug mode with python -m.
To prevent this from happening, you can start the app without the -m option, e.g with flask run.
Related
Updating Based on Comment Requests (Full Error and Port Reference)
I'm trying to deploy my Flask app to Google Cloud but keep running into a 500 Server Error (although sometimes it's 502 Bad Gateway). The Flask app runs fine locally, and the gcloud logs show the following error:
Traceback (most recent call last):
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
worker.init_process()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 92, in init_process
super().init_process()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process
self.load_wsgi()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi
self.wsgi = self.app.wsgi()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load
return self.load_wsgiapp()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp
return util.import_app(self.app_uri)
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app
mod = importlib.import_module(module)
File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/srv/main.py", line 10, in <module>
from spotiparty import server
File "/srv/spotiparty.py", line 1395, in <module>
app.run_server(debug=False, port=8085)
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/jupyter_dash/jupyter_app.py", line 180, in run_server
super_run_server(**kwargs)
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/dash/dash.py", line 1750, in run_server
self.server.run(host=host, port=port, debug=debug, **flask_run_options)
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/flask/app.py", line 990, in run
run_simple(host, port, self, **options)
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/werkzeug/serving.py", line 1008, in run_simple
inner()
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/werkzeug/serving.py", line 957, in inner
fd=fd,
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/werkzeug/serving.py", line 781, in make_server
host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
File "/layers/google.python.pip/pip/lib/python3.7/site-packages/werkzeug/serving.py", line 686, in __init__
super().__init__(server_address, handler) # type: ignore
File "/opt/python3.7/lib/python3.7/socketserver.py", line 452, in __init__
self.server_bind()
File "/opt/python3.7/lib/python3.7/http/server.py", line 137, in server_bind
socketserver.TCPServer.server_bind(self)
File "/opt/python3.7/lib/python3.7/socketserver.py", line 466, in server_bind
self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use
I've tried troubleshooting with all the solutions here, but still keep running into the same error. For some background, the app is using the Spotify API and is initially supposed to prompt the user for their Spotify login. Here is the full code I'm using in main.py:
from flask import Flask, request, redirect, g, render_template, session
from spotify_requests import spotify
from spotiparty import server
app = Flask(__name__)
app.secret_key = 'some key for session'
# ----------------------- AUTH API PROCEDURE -------------------------
#app.route("/auth")
def auth():
return redirect(spotify.AUTH_URL)
#app.route("/callback/")
def callback():
auth_token = request.args['code']
auth_header = spotify.authorize(auth_token)
session['auth_header'] = auth_header
return profile()
def valid_token(resp):
return resp is not None and not 'error' in resp
# -------------------------- API REQUESTS ----------------------------
#app.route("/")
def index():
src = server
return render_template('index.html', src=src)
if __name__ == "__main__":
app.run(debug=False, port=spotify.PORT)
spotify.py contains the API credentials and spotiparty.py contains the bulk of my application being deployed, including a separate Dash/Flask framework that is being linked to the server in main. The spotify.PORT reference within the app run at the bottom of my code simply points to a variable in spotify.py which stores the value 8080 (have also tried with various other port values to make sure it's not running on the same server as gcloud).
Based on the suggestions in the linked post above, I've tried commenting out the if name == "main" block, switching the app run to a different port, and setting the Flask port directly from the command line, but I still receive the same error and logs in gcloud on every run.
I feel like I've hit a bit of a wall on this one, but given that the app runs fine locally I think I must be close to getting it up and running (maybe wishful thinking). Any help here would be greatly appreciated, and please let me know if there's any other info I can provide on the other scripts involved in the app or the gcloud logs resulting from the server errors.
FlaskWebDir
helloapp
__init__.py
templates
hello.py
main.py
__ init __.py:
from flask import Flask
from helloapp import routes
app = Flask(__name__)
if __name__=='__main__':
app.run()
routes.py:
from flask import render_template
#app.route("/")
def hello():
### code
#app.route("/user/<username>/")
def hello_user(username):
### code
#app.route("/users/")
def display_users():
###code
main.py:
from helloapp import app
$ flask run
* Serving Flask app "main.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Traceback (most recent call last):
File "/home/as/FlaskWebDir/projenv/bin/flask", line 8, in <module>
sys.exit(main())
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 848, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 305, in __init__
self._load_unlocked()
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "/home/as/FlaskWebDir/projenv/lib/python3.8/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/home/as/FlaskWebDir/main.py", line 1, in <module>
from helloapp import app
File "/home/as/FlaskWebDir/helloapp/__init__.py", line 2, in <module>
from helloapp import routes
File "/home/as/FlaskWebDir/helloapp/routes.py", line 5, in <module>
#app.route("/")
NameError: name 'app' is not defined
In your routes, add:
# Previous import
from helloapp import app
#app.route('/')
def hello():
# ...
# ...
The app you are importing here is used in your decorators.
I'm trying to run a socketio flask server and ran into the issue above. I can't figure out where the overflow happens, despite the error message tells me. Help?!
app.py:
from flask import Flask, render_template, url_for
from flask_login import LoginManager, login_required, logout_user
from flask_socketio import SocketIO, send
import socketio
from auth import authentication
from manager import manager
from remote import remote
from models import db, User
def create_socketserver():
app = Flask(__name__)
app.debug = True
#app.config['SECRET_KEY'] = 'nF4fN^xe=X*tBM/X+\A4A/'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///user.db'
db.init_app(app)
app.register_blueprint(authentication)
app.register_blueprint(manager)
app.register_blueprint(remote)
socketio = SocketIO(app, cors_allowed_origins='*')
return app, socketio
if __name__ == "__main__":
app, socketio = create_socketserver()
#app.route('/')
def index():
return render_template('base.html')
login_manager = LoginManager(app)
#login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
logout_user
socketio.run(app, host='0.0.0.0')
Error in command line:
pi#raspberrypi:~/Desktop/server $ python __init__.py
Traceback (most recent call last):
File "__init__.py", line 40, in <module>
socketio.run(app, host='0.0.0.0')
File "/home/pi/.local/lib/python3.8/site-packages/flask_socketio/__init__.py", line 647, in run
monkey.patch_thread()
File "/home/pi/.local/lib/python3.8/site-packages/gevent/monkey.py", line 195, in ignores
return func(*args, **kwargs)
File "/home/pi/.local/lib/python3.8/site-packages/gevent/monkey.py", line 754, in patch_thread
gevent_threading_mod, _ = _patch_module('threading',
File "/home/pi/.local/lib/python3.8/site-packages/gevent/monkey.py", line 443, in _patch_module
gevent_module, target_module, target_module_name = _check_availability(name)
File "/home/pi/.local/lib/python3.8/site-packages/gevent/monkey.py", line 429, in _check_availability
gevent_module = getattr(__import__('gevent.' + name), name)
File "<frozen importlib._bootstrap>", line 988, in _find_and_load
File "<frozen importlib._bootstrap>", line 149, in __enter__
File "<frozen importlib._bootstrap>", line 88, in acquire
File "src/gevent/_semaphore.py", line 273, in gevent._gevent_c_semaphore.Semaphore.__enter__
File "src/gevent/_semaphore.py", line 274, in gevent._gevent_c_semaphore.Semaphore.__enter__
File "src/gevent/_semaphore.py", line 175, in gevent._gevent_c_semaphore.Semaphore.acquire
File "/home/pi/.local/lib/python3.8/site-packages/gevent/thread.py", line 121, in acquire
acquired = BoundedSemaphore.acquire(self, blocking, timeout)
File "src/gevent/_semaphore.py", line 175, in gevent._gevent_c_semaphore.Semaphore.acquire
File "src/gevent/_semaphore.py", line 200, in gevent._gevent_c_semaphore.Semaphore.acquire
OverflowError: Python int too large to convert to C long
as .png
edit
Hopefully this better now...
I changed the log to text now
edit out
Initialization code
extensions.py
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from authentek.logger import log
db = SQLAlchemy()
migrate = Migrate()
bcrypt = Bcrypt()
cors = CORS(resources={r"/v1/*": {"origins": "*"}})
log.debug("in debug mode")
from authentek.extensions import db, migrate, bcrypt, cors
def configure_extensions(flask_app, cli):
"""configure flask extensions
"""
db.init_app(flask_app)
blueprint = Blueprint('api', __name__, url_prefix='/v1')
api.init_app(blueprint)
api.add_namespace(users_namespace)
api.add_namespace(auth_namespace)
if blueprint.name not in flask_app.blueprints.keys():
flask_app.register_blueprint(blueprint)
else:
flask_app.blueprints[blueprint.name] = blueprint
cors.init_app(flask_app)
db.app = flask_app
db.create_all()
bcrypt.init_app(flask_app)
if cli is True:
migrate.init_app(flask_app, db) # here it's registered
flask db migrate
2020-06-27 09:09:04,827 - authentek.logger - DEBUG - in debug mode
Traceback (most recent call last):
File "/usr/local/bin/flask", line 8, in <module>
sys.exit(main())
File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 967, in main
cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 426, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/flask_migrate/cli.py", line 88, in migrate
rev_id)
File "/usr/local/lib/python3.7/site-packages/flask_migrate/__init__.py", line 175, in migrate
config = current_app.extensions['migrate'].migrate.get_config(
KeyError: 'migrate'
repository: https://github.com/eshta/authentek
You haven't initialized the migrate instance.
def configure_extensions(flask_app, cli):
"""configure flask extensions
"""
db.init_app(flask_app)
migrate.init_app(flask_app, db)
# ...
Also, remove db.create_all(), since you want Flask-Migrate to manage your database schema.
I have read many different blogs explaining how to combine Flask and Celery. I've also read tons of stack questions on the subject. However, it has been days and I still don't manage to solve this "RuntimeError: Working outside of application context" and I don't know what I can do to solve the issue at this point.
The project is done as such :
/application
__ init__
models
routes
tfidf_matching
celery_worker
config
wsgi
I implemented my project to have a Factory architecture as done on this article. Then, the celery implementation has been done to fit this Factory architecture as explained on this article.
The HTTP request is handled in routes.py and will call a celery task to be done in the background. Meanwhile the app can continue to run and do other things. It will send a POST HTTP with another function and when the celery task is done then it will send a POST HTTP of the celery result.
routes.py contains the following, I have reduced it to the important parts:
from flask import request, make_response, jsonify, copy_current_request_context
from flask import current_app as app
from application import tfidf_matching
import time
from application.models import db, Status
from app import cel
def snooze(maxTime):
...
#app.before_first_request
def default_values():
...
#cel.task
def tfidf(question):
with app.app_context:
answer = tfidf_matching.getMatchingSentence(question)
...
return answer
#app.route('/webhook', methods=['GET', 'POST'])
def webhook():
req = request.get_json(force=True)
...
if ... :
user_input = req.get('queryResult').get('queryText')
answer = tfidf.apply_async(args=[user_input], expires=60)
...
snooze(4)
response = {'followupEventInput': {'name': 'snooze'}}
if ...:
response = {'fulfillmentText': answer}
return make_response(jsonify(response))
I have tried using #copy_current_request_context and with app.app_context to solve the error as suggested in other stack overflow questions but no success.
Celery is launched with the following command :
celery worker -A celery_worker.cel --loglevel=info
The celery_worker.py contains the following:
import os
from app.routes import tfidf
from application import cel, create_app
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
app.app_context().push()
I am not sure if it is necessary but in case I am also adding the init and wsgi content. Models is an SQLAlchemy database and this doesn't seem relevant so I will not add this part.
__ init__.py contains the following:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from celery import Celery
from config import config, Config
db = SQLAlchemy()
cel = Celery(__name__, broker=Config.broker_url, backend=Config.result_backend)
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
db.init_app(app)
app.config.update(
broker_url='redis://localhost:6379',
result_backend='redis://localhost:6379',
SQLALCHEMY_DATABASE_URI='postgresql://postgres:APG#localhost:5432/Dialogflow',
SQLALCHEMY_TRACK_MODIFICATIONS='None'
)
cel.conf.update(
result_expires=3600,
)
cel.conf.update(app.config)
with app.app_context():
from . import routes
db.create_all()
return app
And wsgi.py contains the following:
import os
from application import create_app
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
if __name__ == "__main__":
app.run(host='0.0.0.0')
Finally, this is the stack trace :
Traceback (most recent call last):
File "c:\users\emma\appdata\local\programs\python\python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\users\emma\appdata\local\programs\python\python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\Emma\AppData\Local\Programs\Python\Python37\Scripts\celery.exe\__main__.py", line 7, in <module>
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\__main__.py", line 16, in main
_main()
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\bin\celery.py", line 322, in main
cmd.execute_from_commandline(argv)
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\bin\celery.py", line 495, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\bin\base.py", line 289, in execute_from_commandline
argv = self.setup_app_from_commandline(argv)
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\bin\base.py", line 509, in setup_app_from_commandline
self.app = self.find_app(app)
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\bin\base.py", line 531, in find_app
return find_app(app, symbol_by_name=self.symbol_by_name)
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\app\utils.py", line 373, in find_app
sym = symbol_by_name(app, imp=imp)
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\bin\base.py", line 534, in symbol_by_name
return imports.symbol_by_name(name, imp=imp)
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\kombu\utils\imports.py", line 57, in symbol_by_name
module = imp(module_name, package=package, **kwargs)
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\celery\utils\imports.py", line 111, in import_from_cwd
return imp(module, package=package)
File "c:\users\emma\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Emma\PycharmProjects\APG_Dialogflow\celery_worker.py", line 2, in <module>
from application.routes import tfidf
File "C:\Users\Emma\PycharmProjects\APG_Dialogflow\application\routes.py", line 21, in <module>
#app.before_first_request
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\werkzeug\local.py", line 348, in __getattr__
return getattr(self._get_current_object(), name)
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\werkzeug\local.py", line 307, in _get_current_object
return self.__local()
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\flask\globals.py", line 52, in _find_app
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.
Edit
By changing from flask import current_app as app as suggested by Miguel the Error disappears.
I changed the import to from wsgi import app in routes.py but this doesn't work. My app instance should be imported in another way but I don't know how
When running flask with : flask run
I get the following Traceback
Traceback (most recent call last):
File "c:\users\emma\appdata\local\programs\python\python37\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\Emma\PycharmProjects\APG_Dialogflow\wsgi.py", line 4, in <module>
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
File "C:\Users\Emma\PycharmProjects\APG_Dialogflow\application\__init__.py", line 28, in create_app
from . import routes
File "C:\Users\Emma\PycharmProjects\APG_Dialogflow\application\routes.py", line 6, in <module>
from wsgi import app
ImportError: cannot import name 'app' from 'wsgi' (C:\Users\Emma\PycharmProjects\APG_Dialogflow\wsgi.py)
The problem is that you have this in your code:
from flask import current_app as app
And then you use app in #app.route and #app.before_first_request.
This is incorrect, Flask has no way to figure out what is your application instance. What you need to do is use the real application instance instead of current_app.
You can use current_app inside a view function because Flask sets the app context for you, but you cannot use it in the global scope of your application.
Update to the answer after your update:
You now how a circular dependency problem. Note how the last stacktrace shows wsgi.py, going into application/__init__.py, then on to application/routes.py and finally back into wsgi.py.
A fairly common solution for this problem in Flask apps is to move the from . import routes in your application/__init__.py file all the way to the . bottom of the file. I believe that will remove the circular dependency.