ModuleNotFoundError using Flask - python

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).

Related

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!

Flask ImportError: cannot import name (for app in __init__.py)

I'm new to flask, and REST-APIs / server side scripting in general. I get the error "ImportError: cannot import name 'flask_app'" when I try executing run_app.py
This is my dir structure.
my_project
- webapp
- __init__.py
- helpers.py
- c_data.py
- run_app.py
Contents of each file:
__init__.py
"""This is init module."""
from flask import Flask
from webapp import c_data
# Place where webapp is defined
flask_app = Flask(__name__)
c_data.py
"""This module will serve the api request."""
from app_config import client
from webapp import flask_app
from webapp import helpers
from flask import request, jsonify
# Select the database
db = client.newDB
# Select the collection
collection = db.collection
#flask_app.route("/")
def get_initial_response():
"""Welcome message for the API."""
# Message to the user
message = {
'apiVersion': 'v1.0',
'status': '200',
'message': 'Welcome to the Flask API'
}
# Making the message looks good
resp = jsonify(message)
# Returning the object
return resp
run_app.py
# -*- coding: utf-8 -*-
from webapp import flask_app
if __name__ == '__main__':
# Running webapp in debug mode
flask_app.run(debug=True)
What am I doing wrong?
It is because you import c_data in init.py, this makes recursive import
To be clearer, you import c_data and define flask_app inside __init__, but later than c_data you import flask_app which is not defined yet.
from webapp import c_data # Remove it, it makes recursive import
# Place where webapp is defined
flask_app = Flask(__name__)
Try to remove it. Or change the way to import c_data.
Possible solution, change your run_app.py
Remember to remove from webapp import c_data in __init__.py
from webapp import flask_app
from webapp import c_data # New import
if __name__ == '__main__':
# Running webapp in debug mode
flask_app.run(debug=True)

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 __init__.py import error

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)

Set a variable before importing module __init.py__

My Python application structure is thus:
run.py
app/__init.py__
app/config.py
app/<other modules in app>
In my app/__init.py, I'd like to check a variable DEBUG_MODE and depending on its value, start a python Logger if DEBUG_MODE == False, and simply print to console if it is True. My currently attempted (and not working) solution is to have three files:
app/config.py
DEBUG_MODE = False
app/__init__.py
app = MyApp()
from config import DEBUG_MODE
app.debug = DEBUG_MODE
if not app.debug:
import logging
...
run.py
from app import config
config.DEBUG_MODE = True
from app import app
The problem, of course, is that by the time my code reaches config.DEBUG_MODE=True, the app module's init code has already been called because my config file is part of the app module.
How can I tell the module that I want to enable debugging at run time from my run.py script?
The cause of this problem is config.py being part of the app module and namespace - any reference to it and its variables requires the app/__init__.py to be evaluated first.
One way around it is to hijack the Python __builtin__ "module", which is available to all Python modules, and add our own variable:
run.py
import __builtin__
__builtin__.myapp_debug = True
from app import app
And then in the module __init__.py:
# app is instantiated as an Object
import __builtin__
if hasattr(__builtin__, "myapp_debug"):
app.debug = __builtin__.myapp_debug
else:
app.debug = False
# If debugging is off, use file-based logging:
if not app.debug:
print "Setting up logging..."
import logging
...

Categories