Noob level here. It seems my models.py file can't import the db object created in init.py, but a db file (blog.db) is still being created. Since I can't use my model class (Entry(db.Model)) to add to the database from within the console (the db object itself works in the console), I think I'm importing incorrectly from within the models.py. On Python3 (venv), Linux.
Dir structure (relevant folders only, ex. no cache):
/folder/
/folder/app/
/folder/app/__init__.py
/folder/app/models.py
/folder/config.py (only includes the sqlite uri naming variable)
/folder/fakepy/etc (venv, with flask and flask_sqlalchemy)
/folder/run.py (starts server fine, but does show that 'common' sql track modifications warning twice after a restart. normal?)
__init__.py:
#!fakepy/bin/python3 (error happens with or without shebang(s))
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import models
models.py:
#!fakepy/bin/python3
from app import db
import re
import datetime
class Entry(db.Model):
__tablename__ = "post"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
slug = db.Column(db.String, unique=True)
content = db.Column(db.Text)
timestamp = db.Column(db.DateTime)
def __init__(self, title, content, slug=None, timestamp=None):
self.title = title
self.content = content
if slug is None:
self.slug = re.sub('[^\w]+', '-', self.title.lower())
if timestamp is None:
timestamp = datetime.utcnow()
self.timestamp = timestamp
config.py:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'blog.db')
Database is created... (console opened at /folder/, blog.db created at /folder/):
>>> from app import db
>>> db.create_all()
>>>
ERROR: name 'Entry' is not defined when app is imported from console
(fakepy) cha0#skyrim:~/folder$ python3
Python 3.4.3+ (etc removed for brevity)
>>> from app import app
(common sql track modifications warning, removed it for brevity)
>>> Entry()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Entry' is not defined
>>>
>>> from app import models
>>> Entry()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Entry' is not defined
>>>
>>> from app import Entry
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'Entry'
>>>
ERROR: No module named 'app' when models.py is ran directly.
(fakepy) cha0#skyrim:~/folder/app$ python3 models.py
Traceback (most recent call last):
File "models.py", line 2, in <module>
from app import db
ImportError: No module named 'app'
(fakepy)
ERROR: No module named 'config' when init.py is ran directly.
I think this may be a separate issue though.
python3 __init__.py
Traceback (most recent call last):
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 418, in import_string
__import__(import_name)
ImportError: No module named 'config'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "__init__.py", line 6, in <module>
app.config.from_object('config')
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/flask/config.py", line 162, in from_object
obj = import_string(obj)
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 443, in import_string
sys.exc_info()[2])
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/_compat.py", line 137, in reraise
raise value.with_traceback(tb)
File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 418, in import_string
__import__(import_name)
werkzeug.utils.ImportStringError: import_string() failed for 'config'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Debugged import:
- 'config' not found.
Original exception:
ImportError: No module named 'config'
What I want:
From flask website.
>>>from yourapplication import User
>>> admin = User('admin', 'admin#example.com')
In my case-
>>>from app import Entry
>>>entry = Entry("title", "this is a post.")
from app.models import Entry
You must import Entry from the models module of the app.
You may also need to add relative imports in your __init__ for any custom modules.
add to your __init__
from .models import *
edit: Another useful debugging tip - is to use the dir() function to see what is included in a package. In your case, the imports are working so you can run something like
dir(app)
With an argument, attempt to return a list of valid attributes for that object.
for instance here is a returned list for a flask app I wrote.if You cant see your moudle here, add the import.
Related
https://github.com/CodeHostedHere/channel_response_bot
I want to create a db instance and share it between my two modules "messages" and "slash_commands". Extensions.py contains the code to create this and is imported in both modules. I would like to import the Flask(app) from app.py but it results in an error.
Traceback (most recent call last):
File "app.py", line 1, in <module>
from slash_commands import slash_cmds_bp
File "/opt/channel_response_bot/slash_commands/__init__.py", line 5, in <module>
from . import views
File "/opt/channel_response_bot/slash_commands/views.py", line 10, in <module>
from extensions import db, bolt_app, client, handler
File "/opt/channel_response_bot/extensions.py", line 12, in <module>
from app import flask_app
File "/opt/channel_response_bot/app.py", line 2, in <module>
from messages import messages_bp
File "/opt/channel_response_bot/messages/__init__.py", line 5, in <module>
from . import views
File "/opt/channel_response_bot/messages/views.py", line 10, in <module>
from extensions import db, bolt_app, client, handler
ImportError: cannot import name 'db' from 'extensions' (/opt/channel_response_bot/extensions.py)
I also can't do an import from __init__.py in the same level using from . import app as this results in ImportError: attempted relative import with no known parent package
I've been battling blueprints and database issues a lot so my my head is completely fried on this one, I'll need some serious ELI5 to get me across the line
Try using:
from ..extensions import db, bold_app, client, handler
I'm running a script from inside a django application at the very root of the app_name folder; as in app_name>app_name.
At the top of the script I have this:
import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE','versal.settings')
import django
django.setup()
I'm trying to handle an integrity error - my slugs need to be unique, so when one isn't unique, I want to handle the integrity error by adding a '1' to the slug.
try:
podcast_instance.slug = slugify(parsed_podcast.title)
podcast_instance.save()
podcast_saves += 1
except IntegrityError:
podcast_instance.slug = slugify(parsed_podcast.title + '1')
podcast_instance.save()
podcast_saves += 1
When I run this code, I get this:
Traceback (most recent call last):
File "podcasts.py", line 166, in <module>
podcasty()
File "podcasts.py", line 159, in podcasty
submit(podcast_objects,podcast_rss)
File "podcasts.py", line 73, in submit
except IntegrityError as e:
NameError: name 'IntegrityError' is not defined
You need to import it before using it.
from django.db import IntegrityError
Here is what I did:
I wrapped my 12 Django apps in an apps folder in my Django project.
I added sys.path.append(os.path.join(BASE_DIR, 'apps')) in settings.py (before INSTALLED_APPS declaration) sothat I don't need to specify the apps folder when importing my apps.
I changed every 12 apps.py files to set name = apps.myappname
INSTALLED_APPS are still defined with myappname (not apps.myappname)
Here is what I have so far:
Code works normally
Unit tests, when run app by app, 100% works for the 12 apps.
Unit tests, when run as a whole, at some point of execution, fail with errors like this one:
ImportError: Failed to import test module: apps.badges.tests
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/loader.py", line 428, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name
__import__(name)
File "/vagrant/fugo/fugoproj/apps/badges/tests.py", line 10, in <module>
from .factories import BadgeFactory
File "/vagrant/fugo/fugoproj/apps/badges/factories.py", line 6, in <module>
from .models import Badge
File "/vagrant/fugo/fugoproj/apps/badges/models.py", line 51, in <module>
models.Model):
File "/home/ubuntu/fenv/lib/python3.6/site-packages/django/db/models/base.py", line 118, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class apps.badges.models.Badge doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
Here is the badges/factories.py file in error:
from datetime import timedelta
import factory
from django.utils import timezone
from .models import Badge
# some code
On every test which fails, it seems related to the relative import for the model (from .models import SomeModel). If I replace this with from myappname.models import SomeModel, this solve the error.
Any idea on something wrong in my code? I'd like to keep my relative imports.
How to explain it does not fail when running tests app by app?
Thanks.
For some reason I receive an ImportError every time I try to import a class from another file. Here's the github page for my project: https://github.com/wheelebin/mcnextbot
Here's the error that I'm receiving:
Traceback (most recent call last):
File "ircbot.py", line 36, in <module>
from test import mcnextlvl
ImportError: cannot import name mcnextlvl
Here your from test import something refers to the module test in <PYTHONPATH>/lib, not yourselves test.py, and there is no submodule/class mcnextlvl there. You should use from lib.test import mcnextlvl as #sgmart commented.
The __init__.py python file allow you can import your individual modules named 'test' from the lib package.
I want to run my first Django cassandra code in pyCharm.
My code is running smoothly in Django console but it's not working in a .py file. these are the errors:
C:\Python27\python.exe "D:/Developer Center/PyCharm/DJangoCassandra/MyApp/testFile.py"
Traceback (most recent call last):
File "D:/Developer Center/PyCharm/DJangoCassandra/MyApp/testFile.py", line 3, in <module>
from MyApp.models import Person
File "D:\Developer Center\PyCharm\DJangoCassandra\MyApp\models.py", line 1, in <module>
from django.db import models
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Process finished with exit code 1
this is my .py file:
__author__ = 'ehsan'
from cqlengine import connection
from MyApp.models import Person
from cqlengine.management import sync_table,drop_table
def main():
connection.setup(['127.0.0.1:9160'])
sync_table(Person)
Person.create(id='2',name='Ali',family='Rezayee')
p = Person.objects.all()
for item in p:
print item.id
Person.filter(id='1')
this is my model:
from django.db import models
from cqlengine import Model, columns
# Create your models here.
class Person(Model):
id = columns.Text(primary_key=True)
name = columns.Text()
family = columns.Text()
If you'll write the following lines when starting the managy.py shell command, it should work:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zoo.settings")