No Module error when running pytest for flask - python

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)

Related

AttributeError: 'function' object has no attribute 'test_client'

main.py
import os
import psycopg2
import gunicorn
from flask import Flask
from app.routes.universities_routes import app_universities_routes
from app.routes.degrees_routes import app_degrees_routes
from app.routes.curriculum_ratings_routes import app_curriculum_ratings_routes
from app.routes.departments_route import app_departments_routes
from app.routes.user_route import app_users_routes
from app.routes.history_route import app_history_routes
from app.routes.curriculums_route import app_curriculum_routes
from app.routes.courses_route import app_course_routes
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
app.register_blueprint(app_universities_routes)
app.register_blueprint(app_degrees_routes)
app.register_blueprint(app_curriculum_ratings_routes)
app.register_blueprint(app_departments_routes)
app.register_blueprint(app_users_routes)
app.register_blueprint(app_history_routes)
app.register_blueprint(app_curriculum_routes)
app.register_blueprint(app_course_routes)
#app.route('/')
def hello():
return 'Hello, Class Track!'
...
test_routes.py
import pytest
from flask import current_app as app
#pytest.fixture
def app():
app.testing = True
yield app
#pytest.fixture
def client(app):
return app.test_client()
#pytest.fixture
def runner(app):
return app.test_cli_runner()
def test_hello(client):
response = client.get('/')
assert response.status_code == 200
File Structure
backend
app
routes
models
tests
test_routes.py
main.py
I'm trying to run the most simple test for routes, but for some reason this doesn't work and throws this error:
app = <function app at 0x000001FD18A0EF80>
#pytest.fixture
def client(app):
> return app.test_client()
E AttributeError: 'function' object has no attribute 'test_client'
backend\app\tests\test_routes.py:24: AttributeError
I run this through VSCode and through the terminal with the 'pytest' command
Is there a way to make this work without changing the code in main.py

In Apache2 Error.log: ModuleNotFoundError: No module named

Context:
Ubuntu 20
apache2
python 3.8
flask 2.0
venv
PyCharm
This works fine
init.py
from flask import Flask
app = Flask(__name__)
def func1():
return "test1"
#app.route("/")
def index():
f1 = func1()
return f1
if __name__ == "__main__":
app.run(debug=True)
works
This doesn't work
init.py
from flask import Flask
import mod
app = Flask(__name__)
#app.route("/")
def index():
f1 = mod.func1()
return f1
if __name__ == "__main__":
app.run(debug=True)
works not 1
mod.py
def func1():
return "test1"
works not 2
In apache2 error.log
apache2 error.log
In Browser
browser
Why?
The reason for the error is due to the file system in Linux.This code would work perfectly in windows, But in Linux you should write.
import .mod
or
from ubc3 import mod
or
import ubc3.mod

Python circular import error with flask and celery

How can I make #celery.task available on user resources package?
I'm new to python and confused about the "circular imports error" can somebody explain how it works? and how to handle this kind of errors in flask application. This is the part where I always get stuck.
This is my project current folder structure
code
|_resources
| |_user.py
|
|_utils
| |_flask_celery.py
|
|_flask_app.py
--- SOURCE CODE ---
flask_app.py
from flask import Flask
from flask_cors import CORS
from flask_restful import Api
from util.flask_celery import make_celery
from routes.endpoint import urls
from resources.user import Users
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql:///username:StrongPassword#localhost:3306/db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['CELERY_BROKER_URL'] = 'amqp//admin:StrongPassword#localhost:5672'
app.config['CELERY_RESULT_BACKEND'] = 'db+mysql:///username:StrongPassword#localhost:3306/db'
app.config['PROPAGATE_EXCEPTIONS'] = True
api = Api(app)
celery = make_celery(app)
url = urls()
api.add_resource(Users, url.get('users'))
if __name__ == "__main__":
# sqlalchemy
from db import db
db.__init__(app)
app.run(host='0.0.0.0', debug=True, port=5000)
flask_celery.py
from celery import Celery
def make_celery(celery_app):
celery = Celery(
celery_app.import_name,
backend=celery_app.config['CELERY_RESULT_BACKEND'],
broker=celery_app.config['CELERY_BROKER_URL']
)
celery.conf.update(celery_app.config)
class ContextTask(celery.Task):
def __call__(self, *args, **kwargs):
with celery_app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
user.py
from flask_restful import Resource, reqparse
from app import celery # <-- this cause the error
from util.zk_connector import zk_connect
from util.zk_error import error
class Users(Resource):
def post(self, ip, comkey):
zk = zk_connect(ip=ip, password=int(comkey))
try:
session = zk.connect()
session.disable_device()
users = session.get_users()
print(users)
session.enable_device()
session.disconnect()
return {'message': 'success'}, 200
except Exception as e:
return error(e)
#celery.task(name='user.reverse')
def reverse(string):
return string[::-1]
Error:
Traceback (most recent call last):
File ".\flask_app.py", line 6, in <module>
from resources.user import User
File "C:\Users\Gelo\Documents\Brand new clean arch pyzk\code\resources\user.py", line 2, in <module>
from flask_app import celery
File "C:\Users\Gelo\Documents\Brand new clean arch pyzk\code\flask_app.py", line 6, in <module>
from resources.user import User
ImportError: cannot import name 'User' from partially initialized module 'resources.user' (most likely due to a circular import) (C:\Users\Gelo\Documents\Brand new clean arch pyzk\code\resources\user.py)

Flask ImportError: cannot import name routes

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

Flask ImportError: cannot import name 'app' [duplicate]

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.

Categories