Flask __init__.py import error - python

I can not import functions from other files to __init__.py in a flask. Importing something from a file gets an error 500.
__init__.py
from flask import Flask
from fel import fel
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run(debug=True)
fel.py
def fel(a,b):
c = a+b
return (c)
If I delete the following line in the __init__.py file
from fel import fel
Everything is OK.
__init__.py and fel.py are in the same directory
I am working in Python 3.4
Where is the mistake?
edit:
structures
FlaskApp\
__init__.py
fel.py

use relative import
from .fel import fel
fel(something)
Explanation:
The problem of import fel is that you don't know whether its an
absolute import or a relative import. fel could a module in python's
path, or a package in the current module.
Source https://softwareengineering.stackexchange.com/questions/159503/whats-wrong-with-relative-imports-in-python

Your import should be:
from FlaskApp.fel import fel
And the parent directory of FlaskApp needs to be present in your sys.path somehow (for example, set the PYTHONPATH environment variable).

just
from flask import Flask
from .fel import fel
app = Flask(__name__)
#app.route('/')
def hello_world():
number = fel(4,6)
return (number)
if __name__ == '__main__':
app.run(debug=True)

Related

ModuleNotFoundError using Flask

I'm trying to make a Flask api :
app.py
routes
-> __init__.py
-> myobject.py
# app.py
from flask import Flask
from flask_restful import Api
from routes import MyObject
app = Flask(__name__)
api = Api(app)
api.add_resource(MyObject, '/')
if __name__ == '__main__':
app.run()
# __init__.py
from myobject import MyObject
# myobject.py
from flask_restful import Resource
class MyObject(Resource):
def get(self):
return {'hello': 'world'}
When I run my application (python app.py), I get a ModuleNotFoundError: No module named 'myobject'
I don't understand why python can't find my module myobject. Is there something i'm missing in my __init__.py
For __init__.py, it also needs the relative import or absolute import path in order to work correctly.
# __init__.py
# relative import
from .myobject import MyObject
# absolute import
from routes.myobject import MyObject
In another approach, you can write to import MyObject more specifically like this and leave __init__.py an empty file.
# app.py
# ...
from routes.myobject import MyObject
# ...
I believe the problem is due to your app running in the "main" directory and your import residing in a sub directory. Basically your app thinks you are trying to import "/main/myobject.py" instead of "/main/routes/myobject.py"
Change your import in __init__ to from .myobject import MyObject
The . means "this directory" (essentially).

ImportError: cannot import name 'app' from 'FlaskApp' (unknown location)

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!

How to import circular imports

I have a file like this:
app.py:
def app():
........
test.py:
from app import app
def test():
......
but when I try to import " test" function in app.py file I am getting " Module error"
how can I solve this circular imports error?
Try doing a simple import, it worked without any Module error:
import app
def test():
print('b')
app.app()
If the problem persist maybe is because is not finding the module in the directory, try on adding it in the sys.path:
import sys
sys.path.insert(1, '/path/to/module')

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

Why does Flask's app.config.from_object() behave differently with gunicorn?

I'm using Flask with virtualenv, and my demo Flask app is structured as follows:
app/
hello.py
config/
settings.py
venv/
virtualenv files
Contents of hello.py
from flask import Flask
def create_app():
app = Flask(__name__, instance_relative_config=True)
app.config.from_object("config.settings")
#app.route('/')
def index():
return app.config["HELLO"]
return app
if __name__ == "__main__":
app = create_app()
app.run()
settings.py contains just 2 values
DEBUG = True
HELLO = "Hello there from /config !"
I can run this successfully with gunicorn using gunicorn -b 0.0.0.0:9000 --access-logfile - "app.hello:create_app()", it works without any errors.
However, running python app/hello.py from root results in the error ImportError: No module named 'config'. It seems that flask is unable to find the config directory when executed in this manner.
I could move the config directory inside app, but doing so would cause errors with gunicorn instead. Is it not possible to have both ways "just work" ? More importantly, why and what is happening ?
Not the most elegant yet still perfectly working solution:
from os.path import abspath, join
from flask import Flask
def create_app():
app = Flask(__name__, instance_relative_config=True)
config_file_path = abspath(
join(app.instance_path, '../config/settings.py')
)
app.config.from_pyfile(config_file_path)
#app.route('/')
def index():
return app.config["HELLO"]
return app
if __name__ == "__main__":
app = create_app()
app.run()
Addition after considering the comment. In order for Flask to properly import config.settings, the path to app root has to be inside sys.path. It can easily be achieved by adding a single line in the original script:
sys.path.insert(0, os.getcwd())
So the final hello.py looks like:
import os
import sys
from flask import Flask
def create_app():
app = Flask(__name__, instance_relative_config=True)
sys.path.insert(0, os.getcwd())
app.config.from_object("config.settings")
#app.route('/')
def index():
return app.config["HELLO"]
return app
if __name__ == "__main__":
app = create_app()
app.run()
Even more bullet-proof solution would be
app_root_path = os.path.abspath(
os.path.join(app.instance_path, '..')
)
sys.path.insert(0, app_root_path)
This way we do not depend on what os.getcwd() returns: it does not always have to return the app root path.

Categories