I got stuck on import error when running python manage.py db migrate for my Flask app. I tried a lot of combinations with import statements in traceback files (general, local).
Traceback (most recent call last):
File "src/manage.py", line 7, in <module>
from api import app, db
File "/api/src/api.py", line 6, in <module>
import auth.views
File "/api/src/auth/views.py", line 3, in <module>
import models
File "/api/src/models.py", line 2, in <module>
from api import app
ImportError: cannot import name 'app'
Any idea?
Can you try
import os
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
app_settings = os.getenv(
'APP_SETTINGS',
'config.DevelopmentConfig'
)
app.config.from_object(app_settings)
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Try by keeping the import here?
import auth.views
app.register_blueprint(auth.views.auth_blueprint)
Most probable reason for this issue would be that you are referring app Flask object in your auth.views and models even before you create the app object....
ImportError: cannot import name 'app'
so if you import the auth.views after your app creation, then the reference would work....
Related
I am new to flask and I am trying to learn flask-sqlalchemy. For that, I referred to their documentation: https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/#a-minimal-application
Here is my `__init__.py` file:
from flask import Flask
from flask_sqlalchemy import SQLALchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
from app import routes
So, when I import the db variable with from app import db command, I get this error:
Traceback (most recent call last):
File "c:\users\dell\desktop\flask\tutorial\venv\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\Dell\Desktop\Flask\tutorial\app\__init__.py", line 2, in <module>
from flask_sqlalchemy import SQLALchemy
ImportError: cannot import name 'SQLALchemy' from 'flask_sqlalchemy' (c:\users\dell\desktop\flask\tutorial\venv\lib\site-packages\flask_sqlalchemy\__init__.py)
Why am I getting this error? I read through a few stack overflow questions, but none of them helped me.
it's SQLAlchemy not SQLALchemy - note the second L should be lowercase
I have setup all the requirements in Face recognition project master . Everything gone good in last I run the command python app.py
this showing error
Traceback (most recent call last):
File "app.py", line 21, in <module>
DATABASE_USER = os.environ['root']
File "C:\Users\Satya Jeet\AppData\Local\Programs\Python\Python36\lib\os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'root'
my app.py file some codes upto line 25
# * ---------- IMPORTS --------- *
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import os
import psycopg2
import cv2
import numpy as np
import re
# Get the relativ path to this file (we will use it later)
FILE_PATH = os.path.dirname(os.path.realpath(__file__))
# * ---------- Create App --------- *
app = Flask(__name__)
CORS(app, support_credentials=True)
# * ---------- DATABASE CONFIG --------- *
DATABASE_USER = os.environ['root']
DATABASE_PASSWORD = os.environ['root']
DATABASE_HOST = os.environ['localhost']
DATABASE_PORT = os.environ['']
DATABASE_NAME = os.environ['detect']
Using flask-restful, i can not import the object mongo = PyMongo() from the file app/__init__.py into app/common/db.py.
My folder structure looks like this:
myproject/
run.py
app/
__init__.py
config.py
common/
__init__.py
db.py
auth/
__init__.py
resources.py
app/__init__.py contains:
from flask import Flask, Blueprint
from flask_pymongo import PyMongo
from flask_restful import Api
from app.config import Config
from app.auth.resources import Foo
mongo = PyMongo()
bp_auth = Blueprint('auth', __name__)
api_auth = Api(bp_auth)
api_auth.add_resource(Foo, '/foo/<string:name>')
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
mongo.init_app(app)
app.register_blueprint(bp_auth)
return app
app/common/db.py contains:
from app import mongo
the application itself is run from the root via run.py which contains:
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
Problem:
Running the application i get an ImportError:
from app import mongo
ImportError: cannot import name 'mongo'
Why this is not working?
Thanks for your help!
EDIT:
Full Traceback:
Traceback (most recent call last):
File "run.py", line 1, in <module>
from app import create_app
File "/home/bt/Dropbox/dev/flask/test_api/app/__init__.py", line 13, in <module>
from app.auth.resources import SignIn, Users, User, Foo
File "/home/bt/Dropbox/dev/flask/test_api/app/auth/resources.py", line 8, in <module>
from app.common.resources import AuthResource
File "/home/bt/Dropbox/dev/flask/test_api/app/common/resources.py", line 3, in <module>
from app.auth.decorators import token_required
File "/home/bt/Dropbox/dev/flask/test_api/app/auth/decorators.py", line 6, in <module>
from app.common.database import users
File "/home/bt/Dropbox/dev/flask/test_api/app/common/database.py", line 1, in <module>
from app import mongo
ImportError: cannot import name 'mongo'
As I suspected, this is a circular import problem.
You can track the closed loop of dependencies looking at the traceback:
app -> resources -> database -> app
This is a common mistake and not properly documented in Flask tutorials. As explained here by Lepture, you should avoid declaring db in the __init__.py
I always keep this one certain rule when writing modules and packages:
Don't backward import from root __init__.py.
How should you do it, then?
declare db in the proper module (db.py)
import it inside the application factory
I found myself reluctant towards this pattern, I thought those import statements didn't belong inside a function. But this is the way to go.
So, your files should look something alike:
app/common/db.py
from flask_pymongo import PyMongo
mongo = PyMongo
app/__init__.py
from flask import Flask
...
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
from app.common.db import mongo
mongo.init_app(app)
...
and when you need your database connection, i.e. in resources module, you should import it like
from app.common.db import mongo
Note: to avoid future problems, your blueprints should also be declared elsewhere and import on creation time. I really encourage you to read the post by Lepture to better understand this approach.
I'm having the following error when I try to run a Flask app:
File "/home/patterson/Documentos/CPFL/cpfl/computer.py", line 12, in <module>
from cpfl.cpfl import sendmail
ImportError: cannot import name 'sendmail'
sendmail is a function I'm trying to import from the cpfl.py module which is a flask app.
cpfl.py:
...
app = Flask(__name__)
...
The structure of my project is as follows:
I have no idea why import does not work.
Could someone help-me?
Have you tried import cpfl and then when you call the method you use cpfl.sendmail?
I have built is a simple web app with Flask and Python, which I intend to upload to Heroku.
When starting my app locally, with the following script:
#!venv/bin/python
from app import app
app.run(debug = True)
I get this error message:
Traceback (most recent call last):
File "./run.py", line 2, in <module>
from app import app, mail
File "/home/ricardo/personalSite/app/__init__.py", line 3, in <module>
from app import index
File "/home/ricardo/personalSite/app/index.py", line 6, in <module>
from emails import send_email
File "/home/ricardo/personalSite/app/emails.py", line 2, in <module>
from app import app, mail
ImportError: cannot import name mail
So, it cannot import mail.
Inside the app directory I have this __init__.py, here is were I create the Mail object that is ginving me trouble to import:
from flask import Flask
app = Flask(__name__)
from app import index
from flask.ext.mail import Mail
mail = Mail(app)
And this is the file emails.py where I call the send_mail function:
from flask.ext.mail import Message
from app import app, mail
from flask import render_template
from config import ADMINS
from decorators import async
So, according to the error message, the error is in this file, in the from app import app, mail.
What is the problem? Why can't it import mail?
Update:
This is my directory listing:
persSite\
venv\
<virtual environment files>
app\
static\
templates\
__init__.py
index.py
emails.py
decorators.oy
tmp\
run.py
You have a circular dependency. You have to realize what Python is doing when it imports a file.
Whenever Python imports a file, Python looks to see if the file has already started being imported before. Thus, if module A imports module B which imports module A, then Python will do the following:
Start running module A.
When module A tries to import module B, temporarily stop running module A, and start running module B.
When module B then tries to import module A, then Python will NOT continue running module A to completion; instead, module B will only be able to import from module A the attributes that were already defined there before module B started running.
Here is app/__init__.py, which is the first file to be imported.
from flask import Flask
app = Flask(__name__)
from app import index # <-- See note below.
from flask.ext.mail import Mail
mail = Mail(app)
When this file is imported, it is just Python running the script. Any global attribute created becomes part of the attributes of the module. So, by the time you hit the third line, the attributes 'Flask' and 'app' have been defined. However, when you hit the third line, Python begins trying to import index from app. So, it starts running the app/index.py file.
This, of course, looks like the following:
from flask.ext.mail import Message
from app import app, mail # <-- Error here
from flask import render_template
from config import ADMINS
from decorators import async
Remember, when this Python file is being imported, you have thus far only defined Flask and app in the app module. Therefore, trying to import mail will not work.
So, you need to rearrange your code so that if app.index relies on an attribute in app, that app defines that attribute before attempting to import app.index.
This is probably the problem:
from app import app, mail
In the file 'app/emails.py' the import is from the current module, not a nested app module. Try:
from . import app, mail
If it doesn't work, you should update your question with a more detailed directory listing.