I have the following files inside a package called users:
file __init__.py:
from flask_sqlalchemy import SQLAlchemy
from .views import UserDetails, UserList
db = SQLAlchemy()
file models.py:
from users import db
class User(db.Model):
pass
and file views.py:
from .models import User
from users import db
#code
But the following Import exception had occurred:
Error: While importing "users", an ImportError was raised:
Traceback (most recent call last):
File "/var/www/microservices/venv/lib/python3.6/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/var/www/microservices/Flask_Microservices/users/__init__.py", line 9, in <module>
from .views import UserDetails, UserList
File "/var/www/microservices/Flask_Microservices/users/views.py", line 5, in <module>
from .models import User
File "/var/www/microservices/Flask_Microservices/users/models.py", line 2, in <module>
from users import db
ImportError: cannot import name 'db'
Any idea about what is wrong in my imports?
Wild guess. Try to move
from .views import UserDetails, UserList
under db = SQLAlchemy() so it looks like
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from .views import UserDetails, UserList
when you execute import from views it tries to import db from init.py in views.py file. It is not present yet so error occurs. At least I think so.
Related
I'm creating an app directory for web scraping which is scrape inside my django_project. I'm having an an error in importing a class from my models.py module into my views.py module.
this is my project structure:
Here's my code inside models.py in scrape app
from django.db import models
# Create your models here.
# model -- headline (title, url, date)
class Headline(models.Model):
title = models.CharField(max_length=120)
url = models.TextField()
event_date = models.TextField()
def __str__(self):
return self.title
and this code inside views.py in scrape app
from django.shortcuts import render, redirect
import requests
requests.packages.urllib3.disable_warnings()
from bs4 import BeautifulSoup
from .models import Headline
# Create your views here.
def scrape():
# Use the session to get the URL
session = requests.Session()
url = 'https://allevents.in/malacca/all?ref=cityhome-popular'
# Content is basically grabs all the HTML that comes from the session
content = session.get(url, verify=False).content
soup = BeautifulSoup(content, "html.parser")
# Return a list
#item = soup.find_all('div', class_="event-item")
for item in soup.find_all('div', class_="event-item"):
title = item.find("h3").text.strip()
linkhref = item.find("h3").find("a").get('href')
date_posted = item.find("div", {"class":"right"})
new_headline = Headline()
new_headline.title = title
new_headline.url = linkhref
new_headline.event_date = date_posted
new_headline.save()
return redirect('/event/')
after try run python views.py from cmd this error is appeared
Traceback (most recent call last):
File "views.py", line 5, in <module>
from .models import Headline
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
I also try this in my views.py
from scrape.models import Headline
but I get the following error
Traceback (most recent call last):
File "views.py", line 5, in <module>
from scrape.models import Headline
File "C:\Users\USER\django_project\scrape\scrape.py", line 2, in <module>
from .models import Headline
ImportError: attempted relative import with no known parent package
also if i change from models import Headline
Traceback (most recent call last):
File "views.py", line 6, in <module>
from models import Headline
File "C:\Users\USER\django_project\scrape\models.py", line 7, in <module>
class Headline(models.Model):
File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 103, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__
self._setup(name)
File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf\__init__.py", line 64, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
When you want to import your model you should use the path to, in this case, models.py to specificy where Python should look. Then you can import one or multiple models by specifying their class names like this:
from <path_to_models.py> import <your_model_name>
To solve your problem, change:
from .models import Headline
to
from models import Headline
In all your files where you are importing your Headline model
EDIT
When you are using an IDE that has autofill, Pycharm for example. You can import the model in an easy way:
Make sure the imported model is used in your file
Remove the import line
Put your cursor at the end of the model you want to import in the file
Press alt + enter
Click on import model
testapp
models.py
serializers.py
serializers.py :
from .models import Product
This worked for me.
Copying the import lines from tap.py...
tap.py:
import site
import user
from site import security, agent
from site.security import models
When I run this i am getting:
File "/home/vikasadmin/user/tap.py", line 31, in init
from site import security, agent
File "/usr/lib/python2.6/site-packages/site/security.py", line 9, in <module>
from site import models
File "/usr/lib/python2.6/site-packages/site/models.py", line 12, in <module>
from site import config
ImportError: cannot import name config
Since I already imported models from site.security this config should have been included. Please explain? How can I solve this?
I have the following project structure:
./app/__init__.py
./app/main/__init__.py
./app/main/views.py
./app/models.py
./app/resources/__init__.py
./app/resources/changesAPI.py
./config.py
./manage.py
The app/models.py file has the following line:
from app import db
db is defined in app/__init__.py
db = SQLAlchemy()
I'm importing classes from models.py from app/resources/__init__.py:
from app.models import User, Task, TaskChange, Revision
However, it fails when model tries to import db:
Traceback (most recent call last):
File "manage.py", line 5, in <module>
from app import create_app, db, api
File "/Users/nahuel/proj/ptcp/app/__init__.py", line 16, in <module>
from app.resources.changesAPI import ChangesAPI
File "/Users/nahuel/proj/ptcp/app/resources/__init__.py", line 5, in <module>
from app.models import User, Task, TaskChange, Revision
File "/Users/nahuel/proj/ptcp/app/models.py", line 1, in <module>
from app import db
ImportError: cannot import name db
What am I doing wrong?
You have a circular import.
You are importing create_app, db and api from manage.py, which triggers an import of the app.resources.changesAPI module, which in turn then triggers import of the __init__.py package in app/resources which then tries to import your models, which fails because db was not yet defined in app/__init__.py.
You need to move importing ChangesAPI to after the line that defines db in your app/__init__.py file. Any name defined in app/__init__.py before the from app.resources.changesAPI import ChangesAPI is available to your sub-packages, names after are not.
I'm writing an application with one blueprint. My application uses Flask-SQLAlchemy, so my blueprint needs access to the main app's db object (created by Flask-SQLAlchemy) in order to create its own models.
However, when I try to get the db object with current_app.db, flask gives me the following error:
RuntimeError: working outside of application context
Here is my main __init__.py:
from flask import Flask
from app.uploader import uploader
app = Flask(__name__)
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
app.register_blueprint(uploader)
Here's the __init__.py from my uploader blueprint:
from flask import Blueprint
uploader = Blueprint('uploader', __name__,
template_folder='templates')
from . import views
from .models import *
Here's views.py of the blueprint, where the exception takes place:
from flask import (redirect, render_template, request, send_from_directory,
session, current_app)
from flask.views import View
from werkzeug import secure_filename
print current_app.db # Exception happens here
And here's the stacktrace:
Traceback (most recent call last):
File "runtests.py", line 11, in <module>
import tests
File "/home/plasmasheep/project/tests.py", line 14, in <module>
from app import app, db, user_datastore
File "/home/plasmasheep/project/app/__init__.py", line 6, in <module>
from app.uploader import uploader
File "/home/plasmasheep/project/app/uploader/__init__.py", line 6, in <module>
from . import views
File "/home/plasmasheep/project/app/uploader/views.py", line 18, in <module>
print current_app.db
File "/home/plasmasheep/project/venv/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/home/plasmasheep/project/venv/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/home/plasmasheep/project/venv/lib/python2.7/site-packages/flask/globals.py", line 34, in _find_app
raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context
Simply trying to use from .. import db does not work:
Traceback (most recent call last):
File "runtests.py", line 11, in <module>
import tests
File "/home/plasmasheep/project/tests.py", line 14, in <module>
from app import app, db, user_datastore
File "/home/plasmasheep/project/app/__init__.py", line 7, in <module>
from app.uploader import uploader
File "/home/plasmasheep/project/app/uploader/__init__.py", line 6, in <module>
from . import views
File "/home/plasmasheep/project/app/uploader/views.py", line 17, in <module>
from .. import db
ImportError: cannot import name db
Nor does from app import db:
Traceback (most recent call last):
File "runtests.py", line 11, in <module>
import tests
File "/home/plasmasheep/project/tests.py", line 14, in <module>
from app import app, db, user_datastore
File "/home/plasmasheep/project/app/__init__.py", line 7, in <module>
from app.uploader import uploader
File "/home/plasmasheep/project/app/uploader/__init__.py", line 6, in <module>
from . import views
File "/home/plasmasheep/project/app/uploader/views.py", line 17, in <module>
from app import db
ImportError: cannot import name db
current_app is only set during (essentially) a request/response cycle. Normally, you use this only inside views, or stuff that is guaranteed to be called inside views. You typically use current_app when you don't have access to the app directly, such as if you are using an application factory. Since you're not using a factory, just import db directly and it should work in your case.
The import error is due to a circular import. Move the line from app.uploader import uploader to after the definition of db. See a couple paragraphs into this section of the docs, which mentions importing views after defining any of their dependencies.
I have a model project_phase:
from django.db import models
from django.utils import simplejson
from core.models import pmo_review_task
it references pmo_review_task (because it creates a pmo_review_task in its save ovewrite)
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
from core.models import sc_review_task
which references sc_review_task that references project_phase (because it creates a project_phase in its save ovewrite)
from django.db import models
from core.models import project_phase
so it ends up project_phase imports pmo_review_task imports sc_review_task imports project_phase and I guess it loops up somehow generating this error:
Unhandled exception in thread started by <bound method Command.inner_run of <django.core.management.commands.runserver.Command object at 0x010ACFB0>>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 88, in inner_run
self.validate(display_num_errors=True)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python27\lib\site-packages\django\core\management\validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 146, in get_app_errors
self._populate()
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 64, in _populate
self.load_app(app_name)
File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in import_module
__import__(name)
File "C:\work\Portman\core\models\__init__.py", line 4, in <module>
from pmo_review_task import pmo_review_task
File "C:\work\Portman\core\models\pmo_review_task.py", line 5, in <module>
from core.models import sc_review_task
File "C:\work\Portman\core\models\sc_review_task.py", line 3, in <module>
from core.models import project_phase
File "C:\work\Portman\core\models\project_phase.py", line 4, in <module>
from core.models import pmo_review_task
ImportError: cannot import name pmo_review_task
how do I overcome this?
Two ways:
To import a model inside a method (as #YujiTomita suggested).
To use get_model function from django.db.models which is designed for lazy model imports.:
project_phase = get_model('core', 'project_phase')
I prefer the second one, but both methods are ok.
import project_phase inside the save method.
The import is called whenever the code is executed.
If it's in the global module namespace (at the top) then it's called right away and you'll have circular import problems as you describe because one file imports another file which imports the original file.
If you put the problem import statement inside a function, it is /not/ called upon importing the file.
import foo # executed upon importing this file.
def import_foo_when_called():
import foo # only executed when function is called, thus no problems when
# another module imports this file.
Django 1.9 and above
As get_model() in django.db.models has been removed in 1.9.
Use django.apps.get_model()
Similar Question:
What is the equivalent of django.db.models.loading.get_model() in Django 1.9?
or use application label in quotes if you are just using it to create foreignkey.
Instead of from core.models import project_phase
do
models.ForeignKey("core.project_phase")