Flask ImportError: cannot import name routes - python

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

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!

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

Tumblelog Application with Flask and MongoEngine example does not work - Complete Novice

The Tumblelog app on the MongoDB site does not work .
I've followed the example absolutely and I get a 404 error when I run it in my local host. I'm using Eclipse Indigo (3.7.2) with pyDev on Ubuntu 12.0.4.
I'm not sure if it's because of the register_blueprints, which I included in the __init__.py
I did it like this as in the tutorial:
from flask import Flask
from flask.ext.mongoengine import MongoEngine
app = Flask(__name__)
app.config["MONGODB_DB"] = "my_tumble_log"
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
db = MongoEngine(app)
if __name__ == '__main__':
app.run()
def register_blueprints(app):
# Prevents circular imports
from tumblelog.views import posts
app.register_blueprint(posts)
register_blueprints(app)
Otherwise I have followed the tutorial exactly.
register_blueprints is never called - app.run blocks until you kill the script (at which point there is no point to adding routes).
Change the order and everything will run:
def register_blueprints(app):
# Prevents circular imports
from tumblelog.views import posts
app.register_blueprint(posts)
register_blueprints(app)
if __name__ == '__main__':
app.run()
regist_blueprints is not actually preventing circular imports - the pattern to avoid circular imports is to create the app in a different file and import both app and blueprint into a third file to run everything:
# application.py
from flask import Flask # etc.
app = Flask("your_package_name")
# tumblelog/views.py
from flask import Blueprint, current_app # etc.
posts = Blueprint("tumblelog")
#posts.route("/")
def index():
# use current_app rather than app here
# run_server.py (use the same pattern for .wsgi files)
from application import app
from tumblelog.views import posts
app.register_blueprint(posts)
if __name__ == "__main__":
app.run()

Categories