NameError: name 'app' is not defined in Flask - python

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.

Related

IndexError from eureka-flask

So I try to register simple Flask service with Eureka by installing a client. I did everything by the instruction from there: https://github.com/elviejokike/flask-eureka
The code I try to run:
from flask import jsonify
from flask_eureka import Eureka
from flask_eureka.eureka import eureka_bp
app = Flask(__name__)
eureka = Eureka(app)
eureka.register_service(name="my-flask-service")
app.register_blueprint(eureka_bp)
#app.route('/model')
def hello_world():
a = {"text": "I am model service!"}
return jsonify(a)
if __name__ == '__main__':
app.run()
Instead of initializing the service I get this pile of errors:
FLASK_ENV = development
FLASK_DEBUG = 0
In folder C:/Users/HP/PycharmProjects/models-service
C:\Users\HP\PycharmProjects\models-service\venv\Scripts\python.exe -m flask run
* Serving Flask app "app.py"
* Environment: development
* Debug mode: off
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\__main__.py", line 15, in <module>
main(as_module=True)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\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 "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 782, in main
rv = self.invoke(ctx)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 848, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 305, in __init__
self._load_unlocked()
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\HP\PycharmProjects\models-service\app.py", line 9, in <module>
eureka.register_service(name="my-flask-service")
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask_eureka\eureka.py", line 51, in register_service
eureka_client = EurekaClient(name=name, host_name=host_name,
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask_eureka\eurekaclient.py", line 95, in __init__
host_info = HostInfo().get()
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask_eureka\hostinfo.py", line 34, in get
'IPv4': self.ipv4(),
File "C:\Users\HP\PycharmProjects\models-service\venv\lib\site-packages\flask_eureka\hostinfo.py", line 53, in ipv4
ipv4 = ipv4.split(':')[1]
IndexError: list index out of range
Process finished with exit code 1
Every library is installed through pip, code without eureka runs correctly. I think it might be related to OS forbidding an access to network, but I'm not quite sure and need a hand.

Flask migrate fails with extension not loaded

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.

Getting ModuleNotFoundError only if debug mode is enabled

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.

How can this SSL error using PROTOCOL_TLSv1_2 be solved?

I am creating an API using Python and the flask library. I have some problems with SSL. I am running the API on a Ubuntu 16.04.6 LTS server.
from flask import Flask
from flask import request
from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.load_cert_chain('PATH_TO_PUBLIC_KEY','PATH_TO_PRIVATE_KEY')
#app.route('/example', methods=['POST'])
def sayHallo():
return "Hallo!"
if __name__ == '__main__':
serving.run_simple("0.0.0.0", 5000, app, ssl_context=context)
The API and its connection works using http, but adding SSL to the code gives me the error:
Traceback (most recent call last):
File "/usr/local/bin/flask", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 966, in main
cli.main(prog_name="python -m flask" if as_module else None)
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 1137, in inv oke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 956, in invo ke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 555, in invo ke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 555, in invo ke
return callback(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 848, in run_c ommand
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 305, in __ini t__
self._load_unlocked()
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 330, in _load _unlocked
self._app = rv = self.loader()
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 388, in load_ app
app = locate_app(self, import_name, name)
File "/usr/local/lib/python2.7/dist-packages/flask/cli.py", line 240, in locat e_app
__import__(module_name)
File "/var/www/api/app.py", line 7, in <module>
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
AttributeError: 'module' object has no attribute 'PROTOCOL_TLSv1_2'
According to [PyOpenSSL]: class OpenSSL.SSL.Context(method):
Parameters: method - One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or TLSv1_METHOD.
So, you should use:
context = SSL.Context(SSL.TLSv1_2_METHOD)

Error running OpenTok Server Code (Python)

I have problem running flask run for OpenTok server code. How can I eradicate the error? Thanks in advance.
This is the error:
(opentokenv) ➜ opentok-server python -m flask run
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/Library/Python/2.7/site-packages/flask/__main__.py", line 15, in <module>
main(as_module=True)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 513, in main
cli.main(args=args, prog_name=name)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 380, in main
return AppGroup.main(self, *args, **kwargs)
File "/Library/Python/2.7/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/Library/Python/2.7/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Library/Python/2.7/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Library/Python/2.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/Library/Python/2.7/site-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs)
File "/Library/Python/2.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 423, in run_command
app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 152, in __init__
self._load_unlocked()
File "/Library/Python/2.7/site-packages/flask/cli.py", line 176, in _load_unlocked
self._app = rv = self.loader()
File "/Library/Python/2.7/site-packages/flask/cli.py", line 237, in load_app
rv = locate_app(self.app_import_path)
File "/Library/Python/2.7/site-packages/flask/cli.py", line 90, in locate_app
__import__(module)
File "/Users/azambaderi/Documents/Web_Projects/opentok-server/opentok.py", line 2, in <module>
from opentok import OpenTok
ImportError: cannot import name OpenTok
This is the Python code:
from flask import Flask, render_template
from opentok import OpenTok
import os
try:
api_key = os.environ['API_KEY']
api_secret = os.environ['API_SECRET']
except Exception:
raise Exception('You must define API_KEY and API_SECRET environment variables')
app = Flask(__name__)
opentok = OpenTok(api_key, api_secret)
session = opentok.create_session()
#app.route("/")
def hello():
key = api_key
session_id = session.session_id
token = opentok.generate_token(session_id)
return render_template('index.html', api_key=key, session_id=session_id, token=token)
if __name__ == "__main__":
app.debug = True
app.run()
I tried your code and it worked for me, until I changed the filename to opentok.py (from the stack trace it appears that is the name you are using).
I think the quickest solution here is to change your filename from opentok.py to something else as it conflicting with the library name. (Don't forget to remove the opentok.pyc file too).
If you wish to keep the name you should see this answer about Absolute and Relative imports

Categories

Resources