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
I am trying to use pytest to test a flask app and failing at instantiating the app. I am getting the following error when running pytest tests/. The flask --app main run works fine.
ImportError while importing test module '****/tests/test_eventlist.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/homebrew/Cellar/python#3.10/3.10.6_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests/test_eventlist.py:2: in <module>
from app import create_app
app/__init__.py:1: in <module>
from flask import Flask
E ModuleNotFoundError: No module named 'flask'
Here is my project structure.
Here is the code for test_eventlist.py file and my main.py
import pytest
from app import create_app
#pytest.fixture()
def app():
app = create_app()
app.config.update({
"TESTING": True,
})
yield app
#pytest.fixture()
def client(app):
return app.test_client()
def test_eventlist_post(client):
response = client.post("/", data={"filename": "sample1.txt",
"from": "2000-01-01T17:25:49Z", "to": "2000-01-10T16:55:01Z"})
assert len(response) == 5
from flask import Flask
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
I have been following this tutorial from digital ocean.
I got all the way to the last step when I get a 500 Internal Server Error.
My app is structured like the following:
|--------FlaskApp
|----------------FlaskApp
|-----------------------static
|-----------------------templates
|-----------------------venv
|-----------------------__init__.py
|----------------flaskapp.wsgi
My __init__.py contains the following:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello, I love Digital Ocean!"
if __name__ == "__main__":
app.run()
My flaskapp.wsgi contains the following:
import sys
import logging
import site
site.addsitedir('/var/www/FlaskApp/venv/lib/python3.7/site-packages')
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
from FlaskApp import app as application
application.secret_key = 'key'
I had added the bit about importing site after reading this SO
When I look into /var/www/FlaskApp/venv/lib/python3.7/site-packages I can in fact see that packages I need and when I run python3, and import flask, it does load.
Thanks for your help in advance!
I struggle with the implementation of the Flask-MQTT lib to my app. SQLAlchemy etc works fine, but
flask-mqtt throws the error AttributeError: module 'app.mqtt' has no attribute 'init_app'.
In the offical documentatio of Flask-MQTT they build up the create_app() Method the same way
( https://flask-mqtt.readthedocs.io/en/latest/usage.html )
Would be greate if someone can help me! Thank you very much
__init__.py
from flask import Flask
from flask_restful import Api
from flask_mqtt import Mqtt
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_jwt_extended import JWTManager
mqtt = Mqtt()
api = Api()
db = SQLAlchemy()
ma = Marshmallow()
jwt = JWTManager()
def create_app(config):
app = Flask(__name__)
app.config.from_object(config.DevelopmentConfig)
mqtt.init_app(app)
db.init_app(app)
api.init_app(app)
ma.init_app(app)
jwt.init_app(app)
return app
from app.mqtt import mqttclient
run.py
from app import create_app
import config
from flask_migrate import Migrate
app = create_app(config)
migrate = Migrate(app, db)
app.config['MQTT_BROKER_URL'] = 'hivemq'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5003, threaded=True)
ERROR:
mqttservice | Traceback (most recent call last):
mqttservice | File "run.py", line 5, in <module>
mqttservice | app = create_app(config)
mqttservice | File "/code/app/__init__.py", line 18, in create_app
mqttservice | mqtt.init_app(app)
mqttservice | AttributeError: module 'app.mqtt' has no attribute 'init_app'
In that code fragment, mqtt has two meanings. The first is the variable assigned in
mqtt = Mqtt()
The second is a namespace (module)
from app.mqtt import mqttclient
The tell is in the error
AttributeError: module 'app.mqtt' has no attribute 'init_app'
which is happening because the import is overwriting the initial value, so by the time of that .init_app(), mqtt isn't what you expected.
You're going to have to change one of those names.
I am writing a simple Flask app that uses Celery to run a background task, but when i try to run the app on terminal i get the following error message:
Traceback (most recent call last):
File "server.py", line 2, in <module>
from flask_celery import make_celery
File "/usr/local/lib/python2.7/site-packages/flask_celery.py", line 16, in <module>
from celery.app import App, AppPickler, current_app as current_celery
ImportError: cannot import name App
Here is the code that i am using:
from flask import Flask
from flask_celery import make_celery
app = Flask(__name__)
app.config["CELERY_BROKER_URL"] = "amqp://guest:guest#localhost:5672//"
celery = make_celery(app)
#celery.task(name='server.reverse')
def reverse(string):
return string[::-1]
#app.route("/process/<name>")
def process(name):
reverse.delay(name)
return "I sent an async request!"
if __name__ == "__main__":
app.run(debug=True)
Anyone know what i am doing wrong?
Thanks
You receive the error because App is not published by the celery.app module, see the code. Also, it seems that you are using flask_celery, which is not the recommended way how to use Flask with Celery now:
From Celery 3.0 the Flask-Celery integration package is no longer recommended and you should use the standard Celery API instead.
Here's the part of the Flask documentation that covers integration with Celery:
http://flask.pocoo.org/docs/1.0/patterns/celery/
I'm converting a cli application to use a REST api and I've read up on flask and I thought I understood things but apparently not :-D. based on this: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I have a directory structure:
--myApp
myApp.py
--APIService
__init__.py
WebService.py
myApp.py:
from APIService import app
app.run(debug = True )
init:
from flask import Flask
app = Flask(__name__)
from app import routes
WebService.py:
from APIService import app
class WebService(object):
'''
classdocs
'''
def __init__(self,):
'''
Constructor
'''
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
I've tried this a few different ways like renaming app to APIService but I keep circling back to the same error: APIService\__init__.py", line 5, in <module> from app import routes ImportError: No module named app
I just don't get what I'm doing wrong here. I did pip install flask so the module is there. I skipped the environment part but that's because I wasn't bothered with running globally for now. anyone have a clue as to what I messed up?
In the following line insideAPIService\__init__.py:
from app import routes
the keyword routes is referencing a separate Python Module inside the APIService folder that is named "routes.py" in the Flask Mega Tutorial. It seems like you have renamed the "routes.py" file to "WebService.py" so you can solve the import issue by changing the import line insideAPIService\__init__.pyto:
from app import WebService