Flask: cannot import name 'app' - python

Trying to run my python file updater.py to SSH to a server and run some commands every few set intervals or so. I'm using APScheduler to run the function update_printer() from __init__.py. Initially I got a working outside of application context error but someone suggested that I just import app from __init__.py. However it isn't working out so well. I keep getting a cannot import name 'app' error.
app.py
from queue_app import app
if __name__ == '__main__':
app.run(debug=True)
__init__.py
from flask import Flask, render_template
from apscheduler.schedulers.background import BackgroundScheduler
from queue_app.updater import update_printer
app = Flask(__name__)
app.config.from_object('config')
#app.before_first_request
def init():
sched = BackgroundScheduler()
sched.start()
sched.add_job(update_printer, 'interval', seconds=10)
#app.route('/')
def index():
return render_template('index.html')
updater.py
import paramiko
import json
from queue_app import app
def update_printer():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(app.config['SSH_SERVER'], username = app.config['SSH_USERNAME'], password = app.config['SSH_PASSWORD'])
...
File Structure
queue/
app.py
config.py
queue_app/
__init__.py
updater.py
Error
Traceback (most recent call last):
File "app.py", line 1, in <module>
from queue_app import app
File "/Users/name/queue/queue_app/__init__.py", line 3, in <module>
from queue_app.updater import update_printer
File "/Users/name/queue/queue_app/updater.py", line 3, in <module>
from queue_app import app
ImportError: cannot import name 'app'
What do I need to do be able to get to the app.config from updater.py and avoid a "working outside of application context error" if ran from APScheduler?

It's a circular dependency, as you import updater in your __init__.py file. In my Flask setup, app is created in app.py.

Related

Importing modules from parent folder does not work when running flask app

I am trying to import module from file in my parent directory but is not working
Here is how my directory looks like :
Here is how my main.py file looks like :
import sys
path_modules="./Utils"
sys.path.append(path_modules)
from functools import lru_cache
from flask import Flask, render_template, request
import Utils.HardSoftClassifier as cl
import Utils.prediction_utils as ut
import Utils.DataPrepper_reg as prep
app = Flask(__name__)
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/viz')
def viz():
return render_template('viz.html')
if __name__=="__main__":
# import os
# os.system("start microsoft-edge:http:\\localhost:5000/")
app.run(debug=True)
Here is my flaks output :
In order to make a package importable, it must have an (optionally empty) __init__.py file in its root. So first create an empty __init__.py file in the Utils directory.
Furthermore, you don't have to alter the import path, since you start the Flask app from the Clean_code, the simple relative importing will work. So the first three line can be removed from main.py.

python unittest ModuleNotFoundError: No module named <...>

I tried to crate simple Python project with flask and unittest. Structure is quite simple:
classes
|-sysinfo
|static
|templates
|- index.html
|- layout.html
|__init__.py
|sysinfo.py
|printinfo.py
tests
|test_sysinfo.py
README.md
requirments.txt
Very simple class in printinfo.py:
#!/usr/bin/python
import psutil
import json
class SysInfo:
.......
def displayInfo(self):
.......
return json.dumps(self.__data)
And simple flask server run with sysinfo.py:
from flask import Flask, flash, redirect, render_template, request, session, abort
from printinfo import SysInfo
import json
obj1 = SysInfo("gb")
app = Flask(__name__)
#app.route('/')
def index():
var = json.loads(obj1.displayInfo())
return render_template('index.html',**locals())
#app.route('/healthcheck')
def healthcheck():
return "Ok"
#app.route("/api/all")
def all():
return obj1.displayInfo()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
del obj1
I run it with python sysinfo.py staying in classes/sysinfo folder and everything works ok.
So I decided to run unittest for my application. Put in classes/tests ( also tried classes/sysinfo/tests) file test_sysinfo.py with code:
import unittest
import printinfo
from sysinfo import sysinfo
import json
import sys
class TestFlaskApi(unittest.TestCase):
def setUp(self):
self.app = sysinfo.app.test_client()
def simple_test(self):
response = self.app.get('/health')
self.assertEqual(
json.loads(response.get_data().decode(sys.getdefaultencoding())),
{'healthcheck': 'ok'}
)
if __name__ == "__main__":
unittest.main()
And when I started it I can see error:
Error Traceback (most recent call last):
File "\Python\Python37-32\lib\unittest\case.py", line 59, in testPartExecutor
yield File "\Python\Python37-32\lib\unittest\case.py", line 615, in run
testMethod() File "\Python\Python37-32\lib\unittest\loader.py", line 34, in testFailure
raise self._exception ImportError: Failed to import test module: test_sysinfo Traceback (most recent call last): File
"\Python\Python37-32\lib\unittest\loader.py", line 154, in
loadTestsFromName
module = __import__(module_name) File "\classes\sysinfo\tests\test_sysinfo.py", line 2, in <module>
import printinfo ModuleNotFoundError: No module named 'printinfo'
I read several articles, some topics here on StackOverflow for my understanding it's related to project structure. I tried to create setup.py and setup.cfg. I managed to start it with this setup, but test still didn't work.
Could you please help me with minimum setup applicable for my case? All the material I found had written for specific case or too general. I cannot apply it for my case.
Follow flask tutorial I edit __init__.py file to start app from here:
from flask import Flask, flash, redirect, render_template, request, session, abort
from . import printinfo
import json
import os
obj1 = printinfo.SysInfo("gb")
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev'
)
obj1 = printinfo.SysInfo("gb")
#app.route('/')
def index():
var = json.loads(obj1.displayInfo())
return render_template('index.html', **locals())
#app.route('/healthcheck')
def healthcheck():
return "Ok"
#app.route("/api/all")
def all():
return obj1.displayInfo()
#del obj1
return app
Also environment variables should be set for Flask:
For Linux and Mac:
export FLASK_APP=sysinfo
export FLASK_ENV=development
For Windows cmd, use set instead of export:
set FLASK_APP=sysinfo
set FLASK_ENV=development
And run application:
flask run
It run application on localhost on port 5000 since development env set. Anyway I needed to add from . import printinfo into __init__.py.
Didn't try test, but think it should work. If interesting will update soon.
Just followed Flask tutorial. Created conftest.py and test_factory.py. Run Ok with pytest:
import pytest
from sysinfo import create_app
from sysinfo import printinfo
#pytest.fixture
def app():
app = create_app({
'TESTING': True
})
with app.app_context():
printinfo.SysInfo("gb")
yield app
Probably the same setup could be used with unittest. Didn't try.

Flask CLI command not in __init__.py file

I'm trying to add commands to my Flask app.
This is my __init__.py file:
import os
from flask import Flask
from flask_cors import CORS
from flask_mongoengine import MongoEngine
app = Flask(__name__)
CORS(app)
app.config.from_object(os.environ['APP_SETTINGS'])
db = MongoEngine(app)
import slots_tracker_server.views # noqa
If I add to it:
#app.cli.command()
def test_run():
print('here')
I can run flask test_run with no problems, but if I try to move the code to another file, for example: commands.py, I get the error Error: No such command "test_run". when trying to run the command.
What I'm missing?
Use click (the library behind Flask commands) to register your commands:
# commands.py
import click
#click.command()
def test_run():
print('here')
In your __init__.py import and register the commands:
# __init__.py
from yourapp import commands
from flask import Flask
app = Flask(__name__)
app.cli.add_command(commands.test_run)
Take a look at the official docs
In you commands.py you can add register function like that:
def register(app):
#app.cli.command(name='test_run', help="test_run command")
def register_test_run():
test_run()
# other commands to register
And then in your __init__.py import this register function
from flask import Flask
app = Flask(__name__)
from commands import register
register(app)
Notice, that you should import register after you've initialized your app.

Issue with unit test for tiny Flask app

I have a very primitive Flask application which works as I'm expecting, but I'm failing to write a unit test for it. The code of the app is following (i omit insignificant part):
app.py
from flask import *
import random
import string
app = Flask(__name__)
keys = []
app.testing = True
#app.route('/keygen/api/keys', methods=['POST'])
def create():
symbol = string.ascii_letters + string.digits
key = ''.join(random.choice(symbol) for _ in range(4))
key_instance = {'key': key, 'is_used': False}
keys.append(key_instance)
return jsonify({'keys': keys}), 201
The test is:
tests.py
import unittest
from flask import *
import app
class TestCase(unittest.TestCase):
def test_number_one(self):
test_app = Flask(app)
with test_app.test_client() as client:
rv = client.post('/keygen/api/keys')
...something...
if __name__ == '__main__':
unittest.main()
The traceback:
ERROR: test_number_one (__main__.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 12, in test_number_one
test_app = Flask(app)
File "/Users/bulrathi/Yandex.Disk.localized/Virtualenvs/ailove/lib/python3.5/site-packages/flask/app.py", line 346, in __init__
root_path=root_path)
File "/Users/bulrathi/Yandex.Disk.localized/Virtualenvs/ailove/lib/python3.5/site-packages/flask/helpers.py", line 807, in __init__
root_path = get_root_path(self.import_name)
File "/Users/bulrathi/Yandex.Disk.localized/Virtualenvs/ailove/lib/python3.5/site-packages/flask/helpers.py", line 668, in get_root_path
filepath = loader.get_filename(import_name)
File "<frozen importlib._bootstrap_external>", line 384, in _check_name_wrapper
ImportError: loader for app cannot handle <module 'app' from '/Users/bulrathi/Yandex.Disk.localized/Обучение/Code/Django practice/ailove/keygen/app.py'>
----------------------------------------------------------------------
Ran 1 test in 0.003s
FAILED (errors=1)
Thanks for your time.
You have a few issues with the posted code (indentation aside):
First, in tests.py you import app and use it, but app is the module rather than the app object from app.py. You should import the actual app object using
from app import app
and secondly, you are using that app object (assuming we fix the import) as a parameter to another Flask() constructor—essentially saying:
app = Flask(Flask(app))
Since we've imported app from app.py, we can just use it directly, so we remove the app = Flask(app) line (and the associated import statement as we don't need it anymore) and your test file becomes:
import unittest
from app import app
class TestCase(unittest.TestCase):
def test_number_one(self):
with app.test_client() as client:
rv = client.post('/keygen/api/keys')
...something...
if __name__ == '__main__':
unittest.main()
You should note also that the from flask import * form is discouraged in favour of importing specific parts of the module, so
from flask import Flask, jsonify
would be better in your app.py.

python imp.load_source with dependencies

My app has the following layout:
/wsgi/myapp/__init__.py
/wsgi/application
/app.py
File _init_.py:
from flask import Flask #python flask framework!
def create_app(app_name=None):
app_name = app_name or __name__
app = Flask(app_name)
return app
File application (without .py extension!):
from myapp import create_app
application = create_app('myapp')
#application.route('/', methods=['GET', 'POST'])
def index():
return 'My OpenShift Flask app'
File app.py has the following line which causes error:
import imp
app = imp.load_source('application', 'wsgi/application')
The error is "No module named myapp". What else I need to solve the issue?
add the import path
import sys
sys.path.append('wsgi')
import imp
app = imp.load_source('application', 'wsgi/application')
Does it work?
import imp
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'application.py')
application = wsgi.application
this should work in python 3

Categories

Resources