I'm basing myself on the structure of a web app I found up on github, here.
My project's structure looks like this:
~/Learning/flask-celery $ tree
.
├── config
│ ├── __init__.py
│ └── settings.py
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
└── web
├── app.py
├── __init__.py
├── static
└── templates
└── index.html
I want my Flask app in web/app.py to load the settings in the config module, as I saw in the githug project linked above.
Here's how I'm instantiating the Flask app in web/app.py:
from flask import Flask, request, render_template, session, flash, redirect, url_for, jsonify
[...]
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config.settings')
app.config.from_pyfile('settings.py')
[...]
The issue I'm getting is:
root#0e221733b3d1:/usr/src/app# python3 web/app.py
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/werkzeug/utils.py", line 427, in import_string
module = __import__(module_name, None, None, [obj_name])
ImportError: No module named 'config'
[...]
Obviously, Flask can't find the config module in the parent directory, which makes sens to me, but I don't understand how the linked project I'm basing myself on is successfully loading the module with the same tree structure and Flask config code.
In these circumstances, how can I get Flask to load the config module?
Without adding the config directory to your path your Python package will not be able to see it.
Your code can only access what is in web by the looks of it.
You can add the config directory to the package like so:
import os
import sys
import inspect
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
Then you should be able to import config.
In case anyone finds themselves looking at this question from years ago, it is possible to load the config file in the project structure above like this:
app.config.from_pyfile('../config/settings.py')
This will work when starting the app using flask run
Related
I have flask based python project that I run with flask run.
Full picture of errors:
File "D:\ias\project_name\wsgi.py", line 4, in <module>
from app import app as application
File "D:\ias\project_name\entity\__init__.py", line 4, in <module>
from api import *
ModuleNotFoundError: No module named 'api'
Below is my project's files structure and content of troubled files:
project_folder/
entity/
__init__.py
api.py
wsgi.py
app.py
__init__.py contains this piece of code:
from api import *
wsgi.py contains:
from app import app as application
if __name__ == '__main__':
application.run()
app.py contains:
app = Flask(__name__)
app.config.from_object(__name__)
You can do some of the modifications to make it work better I suppose.
From:
project_folder/
entity/
__init__.py
api.py
wsgi.py
app.py
To:
project_folder/
entity/
app/
__init__.py # Import from app.api the blueprint, initialize the create_app() from here.
api/
__init__.py
api.py
wsgi.py
app.py # Call the create_app() from app to initialize and then do app.run().
I am trying to make a flask application, and I am following the well known tutorials out there. I am using docker containers, so I don't need virtual environments, as the containers are already isolated environments.
that's my project folder for the flask app:
flask
├── Dockerfile
├── app
│ ├── __init__.py
│ ├── routes.py
│ ├── static
│ └── templates
│ ├── index.html
│ └── test.html
├── requirements.txt
├── run.py
└── uwsgi.ini
When starting up the container with docker-compose, I get the following error.
Traceback (most recent call last):
File "run.py", line 1, in <module>
from app import app #as application
File "./app/__init__.py", line 1, in <module>
from flask import Flask
ModuleNotFoundError: No module named 'flask'
unable to load app 0 (mountpoint='') (callable not found or import error)
I have read many other questions with such an error, but none of those solutions helped or had to do with venv (which I am not using). So I hope someone can pinpoint, where the problem might be.
I have installed flask in Dockerfile with
RUN python3 -m pip install --disable-pip-version-check --no-cache-dir -r /tmp/requirements.txt
(I also just used pip3 install... but it does not make a difference, flask is installed either way). from the build log:
Successfully installed Jinja2-3.0.3 MarkupSafe-2.0.1 Werkzeug-2.0.2 click-8.0.3 flask-2.0.2 itsdangerous-2.0.1
## run.py
from app import app
This is the import that seems to fail:
## __init__.py
from flask import Flask
app = Flask(__name__)
from app import routes
extract from uwisg.ini:
[uwsgi]
plugin = python3
wsgi-file = run.py
callable = app
After starting the container with docker-compose, I exec into the container, start a Python3 interactive shell and have no problems at all doing from flask import Flask.
I have tried running the container as root but that did not change anything.
Any ideas? thanks!
Ok, after more rinse and repeat trying, I figured it out.
In my Dockerfile I also set the PYTHONPATH to my workspace:
ENV PYTHONPATH "${PYTHONPATH}:/workspace/flask"
ENV PYTHONPATH "${PYTHONPATH}:/workspace/flask/app"
and site-packages apperently could not be accessed by Python anymore.
I also had to add this:
ENV PYTHONPATH "${PYTHONPATH}:/usr/local/lib/python3.11/site-packages"
I have no idea, why this path was not accessible for Python? Did I overwrite sys.path when using ENV PYTHONPATH? Should this not be additive to sys.path?
Here's my current folder structure
.
├── api
│ ├── api_routes.py
│ └── sql
│ └── models.py # import db into this file
├── application
│ └── __init__.py # db here
└── wsgi.py
In __init__.py there's a variable db (Flask-SQLAlchemy instance) and a function create_app, all of which are successfully imported into wsgi.py using this line:
from application import create_app
I used the same line to import db into models.py, to no avail. What can I do now? I have no idea where to start. One SO post suggests that maybe there's a circular import involved, however, I can't find it in my code. I also tried to import with these lines without success:
from . import create_app
from .application import create_app
from ..application import create_app
Edit: after 1 week turning a way from the problem, I found the line that causes it all. The problem was indeed circular dependency. Thanks for all your help!
There are few tricks to handle such imports,
1) Mark the "application" folder as the "Sources Root", and then I think it should work (marking folder as sources root is relatively easy when using pycharm so I suggest you to use pycharm for this and for many more tricks with python)
2) trick number to is to add the path to the directory you want to import from to sys.path, do something like
import sys
sys.path = ['/path/to/your/folder'] + sys.path
...
other code
and then importing should work.
I hope this will help (:
my flask app is a package named app located at /Users/gexinjie/Codes/MyProject/xinnjie_blog
the file tree is like this
xinnjie_blog
├── app
| ├── __init__.py
│ ├── config.py
│ ├── exceptions.py
│ ├── model.py
│ ├── model_sqlalchemy.py
│ ├── static
│ ├── templates
│ ├── util.py
│ └── views
├── manage.py
I export it as PATHONPATH, so manage.py can import app
echo $PATHONPATH
/Users/gexinjie/Codes/MyProject/xinnjie_blog
and export FLASK_APP
echo $FLASK_APP
manage.py
current dir is /Users/gexinjie/Codes/MyProject/xinnjie_blog
pwd
/Users/gexinjie/Codes/MyProject/xinnjie_blog
here is the manage.py
import click
from app import create_app
app = create_app('development')
#app.cli.command()
def initdb():
click.echo('Init the db...')
here is app.__init__.py
from flask import Flask
from .model_sqlalchemy import db
def create_app(config_name='default'):
app = Flask(__name__)
... # init
return app
but then if I execute flask initdb, I get this error:
Usage: flask [OPTIONS] COMMAND [ARGS]...
Error: No such command "initdb".
and if I execute flask run, I get
Usage: flask run [OPTIONS]
Error: The file/path provided (manage) does not appear to exist. Please verify the path is correct. If app is not on PYTHONPATH, ensure the extension is .py
why manage.py is not found? And how can I fix it.
(actually it worked well when manage.py have flask app in itself )
# manage.py
# this work well
app = Flask(__name__) # not app = create_app('development')
Thank you
Thank to #Adam, This problem was solved after I uninstall Anaconda.
Because all the time I tested manage.py on Pycharm command tool, and that flask was installed by Anaconda(python version 3.6), it may lack some extensions(usually I use python3.5 on terminal).So I think the problem occur during importing.
The flask command tool complain about 'can't locate the app', but the real problem is import error.So that is so confusing.
"universal" solution:
So when if you come to this kind of problem like I do, I suggest you first check the location of your app(try both relative path and absolute path), relative path may cause the locate problem when you are not at the right working directory.So absolute path is recommend.
If every thing about path went well, then make sure that all the packages required by your app is installed and can be imported. if you are using some type of virtual environment or something like that (In my case, I use the other version of python lacking some flask extensions), it may be the import error makes flask complain.
Hope this can help you.
Under my Django project I have created a directory for an aiohttp service.
1) How is the best way to structure it?
This is my current structure:
myproject/
myservice/
__init__.py
service.py
utils.py
myproject/
__init__.py
settings.py
urls.py
uwsgi.py
manage.py
2) If my service needs to import some settings from myproject.settings, how can I do it? Should I move service.py under the root?
I get:
ImportError: No module named 'myproject'
Your server.py script, which uses aiohttp should be next to your manage.py file.
You should probraly also add:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
from django import setup
setup()