ModuleNotFoundError when running imported Flask app - python-3.x

I have a python module with the following layout:
foo
| __init__.py
| __main__.py
| bar.py
__init__.py is empty.
Content of foo/bar.py:
from flask import Flask
app = Flask(__name__)
def baz(): pass
When running python3 -m foo i get confusing results.
Contents of foo/__main__.py
# Results in a ModuleNotFoundError: No module named 'foo'
from foo.bar import app
app.run()
# Raises no error and correctly prints the type
from foo.bar import app
print(type(app))
# Also runs without an error
from foo.bar import baz
baz()
Why is it possible to import and execute a function from this module, but when trying to do the same with a flask app it results in a ModuleNotFoundError?
I just can't see any way this makes any sense.
Edit:
The error is persistent even with this code:
from foo.bar import app
print(type(app))
app.run()
Output:
<class 'flask.app.Flask'>
* Serving Flask app "foo.bar" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "/home/user/projects/ftest/foo/__main__.py", line 1, in <module>
from foo.bar import app
ModuleNotFoundError: No module named 'foo'
So, obviously the module can be imported, because type(app) works just fine and flask does start. It seems like flask does a reload and is messing around with imports somehow.
Edit 2:
I turned debug mode off and it works just fine.
This error only occurs if you set export FLASK_DEBUG=True or explicitly enable debug via app.config["DEBUG"] = True

It turns out it's a bug in werkzeug.
The code works as expected if werkzeug's reloader is disabled.
How to reproduce the behaviour
Directory structure:
foo
| __init__.py
| __main__.py
Content of __init__.py:
from flask import Flask
app = Flask(__name__)
app.config["DEBUG"] = True
Content of __main__.py:
from foo import app
app.run()
If we run it:
$python3 -m foo
* Serving Flask app "foo" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "/home/user/projects/ftest/foo/__main__.py", line 1, in <module>
from foo import app
ModuleNotFoundError: No module named 'foo'
If we change __main__.py:
from foo import app
app.run(use_reloader=False)
Everything works just fine.
What's going on
The problem is in werkzeug._reloader.ReloaderLoop.restart_with_reloader. It calls a subprocess with the arguments provided by werkzeug._reloader._get_args_for_reloading but this function does not behave as expected when executing a package via the -m switch.
def _get_args_for_reloading():
"""Returns the executable. This contains a workaround for windows
if the executable is incorrectly reported to not have the .exe
extension which can cause bugs on reloading.
"""
rv = [sys.executable]
py_script = sys.argv[0]
if os.name == 'nt' and not os.path.exists(py_script) and \
os.path.exists(py_script + '.exe'):
py_script += '.exe'
if os.path.splitext(rv[0])[1] == '.exe' and os.path.splitext(py_script)[1] == '.exe':
rv.pop(0)
rv.append(py_script)
rv.extend(sys.argv[1:])
return rv
In our case it returns ['/usr/local/bin/python3.7', '/home/user/projects/ftest/foo/__main__.py']. This is because sys.argv[0] is set to the full path of the module file but it should return ['/usr/local/bin/python3.7', '-m', 'foo']` (At least from my understanding it should and it works this way).
I have no good idea on how to fix this behaviour, or if it is something that need to be fixed. It just seems weird to me that I'm the only one that has encountered this problem, since it doesn't seem too much of a corner case to me.

Adding the following line before app.run() works around the werkzeug reloader bug:
os.environ['PYTHONPATH'] = os.getcwd()
Thanks to #bootc for the tip! https://github.com/pallets/flask/issues/1246

Have you tried from foo import app in your main.py file?

Related

How to get the correct path for a django script

Here is my arborescence
V1 :
project/
---AppUser/
------models.py, view.Py etc ...
---project/
------settings.py, manage.py etc ...
myscript.py
here my script works perfectly :
import sys
import os
import django
sys.path.append("../../../project")
os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
django.setup()
from AppUser.models import Subscription
maps = Subscription.objects.get(uuid="1234565")
print(maps)
It works fine, i launch it from the root of the project ...
But when i want to put my script in a script folder :
V2 :
project/
---AppUser/
------models.py, view.py etc ...
---project/
------settings.py, manage.py etc ...
---script/
------myscript.py
Here is my script :
import sys
import os
import django
sys.path.append("../../../../project")
os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
django.setup()
from AppUser.models import Subscription
maps = Subscription.objects.get(uuid="123")
print(maps)
and when i am in script/
and i do a python3 script.Py
I have a :
Traceback (most recent call last):
File "myscript.py", line 12, in <module>
from AppUser.models import Subscription
ModuleNotFoundError: No module named 'AppUser'
error
How to be in script and not having this error ?
The django.setup() seems to works fine, but after it seems to have a problem.
To run the script, you don't have to be in the script folder as you already updated the path in the script.
sys.path.append("../../../../project")
If you want to run from the script folder you can update the path in the script
sys.path.append("../../../project")

Python import from parent directory for dockerize structure

I have a project with two applications. They both use a mongo-engine database model file. Also they have to start in different Docker containers, but use the same Mongo database in the fird container. Now my app structure looks like this:
app_root/
app1/
database/
models.py
main.py
app2/
database/
models.py
main.py
And it works fine, BUT I have to support two same files database/models.py. I dont want to do this and I make the next structure:
app_root/
shared/
database/
models.py
app1/
main.py
app2/
main.py
Unfortunately it doesnt work for me, because when I try this in my main.py:
from ..shared.database.models import *
I get
Exception has occurred: ImportError
attempted relative import with no known parent package
And when I try
from app_root.shared.database.models import *
I get
Exception has occurred: ModuleNotFoundError No module named 'app_root'
Please, what do I do wrong?
In the file you perform the import, try adding this:
import os
import sys
sys.path.append(os.path.abspath('../../..'))
from app_root.shared.database.models import *

How does one import python files from the same sub-directory?

I am trying to create a project with the Panda3D game engine. I have the files stored in C:/%users%/Documents/Python/Starbound. Here is the directory of the project:
Starbound
|--.git
| |--all the git system stuff
|--__pycache__
| |--__init__.cpython-37.pyc
| |--main.cpython-37.pyc
| |--run.cpython-37.pyc
|--__init_.py
|--main.py
|--run.py
I would like to use run.py as an easy command-line quick-run for the project. It is a script designed to call the main application as a library. This allows me to change the order of the setup without accidentally messing up the main program. When I call run.py from Windows CMD(in the Starbound directory), I get a traceback to line 9 of run.py:
'loadWorld' missing 1 required positional argument: 'self'
When I import run.py from the Python interpreter, I get a different traceback to line 5 of run.py:
ModuleNotFoundError: No module named 'main'
run.py:
#run.py
#File to call "main.py"
#from Starbound import main
import main
print("Import of main file successful.")
App = main.Application
print("Declaration of application class successful.")
App.loadWorld()
print("Loading of world successful.")
main.py:
#main.py
#File which contains the application control. Designed to be called from "run.py".
from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from direct.actor.Actor import Actor
from direct.interval.IntervalGlobal import Sequence
from panda3d.core import Point3
class Application(ShowBase):
#variables
def __init__(self):
ShowBase.__init__(self)
def loadMainMenu(self):
print("Main menu is not currently available.")
def loadWorld(self):
self.scene = self.loader.loadModel('models/environment')
self.scene.reparentTo(self.render)
__init__.py
import sys
sys.path.insert(1, '/Starbound')
How do I call the main.py from __init__.py and other files?
Visual Studio 2019 installation of Python 3.7.5, Windows 10 Home.
If you want to be able to call a python package, create a __main__.py file inside of it. It can be called with python -m mymodule (calls mymodule.main).

Unable to run celery task directly but still possible via Python console

I'd like to run a simple test (run a task) first via RabbitMQ and once this is setup correctly, then encapsulate in Docker and run from there.
My structure looks like so:
-rabbitmq_docker
- test_celery
- __init__.py
- celeryapp.py
- celeryconfig.py
- runtasks.py
- tasks.py
- docker-compose.yml
- dockerfile
- requirements.txt
celeryconfig.py
## List of modules to import when celery starts
CELERY_IMPORTS = ['test_celery.tasks',] # Required to import module containing tasks
## Message Broker (RabbitMQ) settings
CELERY_BROKER_URL = "amqp://guest#localhost//"
CELERY_BROKER_PORT = 5672
CELERY_RESULT_BACKEND = 'rpc://'
celeryapp.py
from celery import Celery
app = Celery('test_celery')
app.config_from_object('test_celery.celeryconfig', namespace='CELERY')
__init__.py
from .celeryapp import app as celery_app
run_tasks.py
from tasks import reverse
from celery.utils.log import get_task_logger
LOGGER = get_task_logger(__name__)
if __name__ == '__main__':
async_result = reverse.delay("rabbitmq")
LOGGER.info(async_result.get())
tasks.py
from test_celery.celeryapp import app
#app.task(name='tasks.reverse')
def reverse(string):
return string[::-1]
I run celery -A test_celery worker --loglevel=info from the rabbitmq_docker directory. Then in a separate window I trigger reverse.delay("rabbitmq") in the Python console, after importing the required module. This works. Now when I try to trigger the reverse function via the run_tasks.py i.e. python test_celery/run_tasks.py I get:
Traceback (most recent call last):
File "test_celery/run_tasks.py", line 1, in <module>
from tasks import reverse
File "/Users/my_mbp/Software/rabbitmq_docker/test_celery/tasks.py", line 1, in <module>
from test_celery.celeryapp import app
ModuleNotFoundError: No module named 'test_celery'
What I don't get is why this Traceback doesn't get thrown when called directly from the Python console. Could anyone help me out here? I'd eventually like to startup docker, and just run the tests automatically (without going into the Python console).
The problem is simply because your module is not in the Python path.
These should help:
Specify the PYTHONPATH to point to the directory where your test_celery package.
Always run your Python code in the directory where your test_celery package is located.
Or alternatively reorganise your imports...

Deploying Python Flask app on web using pythonanywhere

I want to deploy my flask app publicly using pythonanywhere. I have followed all steps exactly. Tried implementing it with virtualenv and without virtualenv but none works.
I can get the simple flask page 'Hello to flask app" working but my code is not working.
Path is /home/anwaraliafshan/bella and file is afshan.py
This is my WSGI.py and I tried replacing flask with bella and afshan but nothing worked.
Also getting import imutil error in error.log though install imutil successfully on python3
Please help me finding the cause. Thanks in advance
# This file contains the WSGI configuration required to serve up your
# web application at http://<your-username>.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# The below has been auto-generated for your Flask project
import sys
# add your project directory to the sys.path
project_home = '/home/anwaraliafshan/bella/'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
# import flask app but need to call it "application" for WSGI to work
from flask import app as application # noqa
As quoted from their website:
import sys
path = '/home/yourusername/mysite'
if path not in sys.path:
sys.path.insert(0, path)
from flask_app import app as application

Resources