python error when importing from __init__ file - python-2.7

I have a package installed in my site-packages dir. Folder structure looks like this
MyPkg\
__init__.py
LogUtils\
__init__.py
logwrapper.py
Shortcuts\
__init__.py <-----this references LogUtils
somefile.py
When I do help ('modules') I see MyPkg listed. But I get the following error in IDLE:
>>> import MyPkg
>>> from MyPkg import LogUtils
>>> from MyPkg import Shortcuts
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
from MyPkg import Shortcuts
File "C:\Python27\lib\site-packages\MyPkg\Shortcuts\__init__.py", line 1, in <module>
from GoToUrl import go_to_url
File "C:\Python27\lib\site-packages\MyPkg\Shortcuts\GoToUrl.py", line 1, in <module>
from LogUtils import logger, log
ImportError: No module named LogUtils
Why would LogUtils import fine standing alone, but throw an error when being imported via an init file??

Seems to me you are lacking some backslashes
MyPkg\
__init__.py
LogUtils\
__init__.py, \
logwrapper.py
Shortcuts\
__init__.py, \
somefile.py

As you see yourself, you are not importing the same module:
>>> from MyPkg import LogUtils
vs.
from LogUtils import logger, log
The first imports a package called MyPkg.LogUtils, the second imports a package called LogUtils. Whether they exist or not depends on your python paths, but in general, if the first one works, change the second one to
from MyPkg.LogUtils import logger, log

Related

What does it mean attempted relative import beyond top-level package?

Traceback
File "", line 5, in <module>
from ..books.models import Commen
ImportError: attempted relative import beyond top-level package
forms.py
from ..books.models import Comment
Maybe problem in urls.py?
There is the structure of my project
enter image description here

ImportErrors cannot import app and bcrypt from flask_app and can't import db from models.py

stucture of the app
flask_app
__init__.py
models.py
routes.py
run.py
__init__.py
from flask import Flask
from flask_bcrypt import Bcrypt
import os
from flask_app.models import db
app = Flask(__name__)
db.init_app(app)
bcrypt = Bcrypt(app)
from flask_app import routes
models.py
from flask_sqlalchemy import SQLAlchemy
from flask_app import app, bcrypt
db = SQLAlchemy()
run.py
from flask_app import app
if __name__ == '__main__':
app.run(debug=True)
This happens first
Traceback (most recent call last):
File
"c:\users\cristovao\documents\mqs_development\flaskexperiment\env\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\run.py", line 4, in <module>
from flask_app import app # importing from __init__.py within flask_app package
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\__init__.py", line 6, in <module>
from flask_app.models import db
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\models.py", line 2, in <module>
from flask_app import app, bcrypt
ImportError: cannot import name 'app' from 'flask_app' (C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\__init__.py)
and then in models.py after this error I write from flask__app.__init__ import app bcrypt and I got another error
Traceback (most recent call last):
File "c:\users\cristovao\documents\mqs_development\flaskexperiment\env\lib\site-packages\flask\cli.py", line 240, in locate_app
__import__(module_name)
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\run.py", line 4, in <module>
from flask_app import app # importing from __init__.py within flask_app package
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\__init__.py", line 6, in <module>
from flask_app.models import db
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\models.py", line 2, in <module>
from flask_app.__init__ import app, bcrypt
File "C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\__init__.py", line 6, in <module>
from flask_app.models import db
ImportError: cannot import name 'db' from 'flask_app.models' (C:\Users\cristovao\Documents\MQS_Development\FlaskExperiment\flask_app\models.py)
when I run my app using flask run it gives me those import errors cannot import app and bcrypt from flask_app to models.py and can't import db from models.py to __init__py. I dont understand why since run.py is being separated from my package (flask__app).
When I use your code, I get an error because of a circular import.
ImportError: cannot import name 'app' from partially initialized module 'flask_app' (most likely due to a circular import) (/home/jugmac00/Tests/stackoverflow/flask_app/__init__.py)
I can get rid of that when I remove this line from models.py
from flask_app import app, bcrypt
The easiest way to get rid of circular imports is to use the app factory pattern.
https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/
This application factory pattern took me a while to understand, but it is really worthwile to try to understand and use it.
There is a mindblowing good video on that, from this year's Flask-Conference:
https://www.youtube.com/watch?v=xNo-eOfZH5Q
If this sounds to hard, then my advice would be... just put everything in one file - that is not too bad, unless the app grows really big.

Getting an error in django-admin.py

I have installed django 1.6 using pip on Windows 7. When I try to run django-admin.py, I get this error
C:\django-admin.py startproject test007
Traceback (most recent call last):
File "C:\Python27\Scripts\django-admin.py", line 2 in ?
from django.core import management
File "C:\Python27\Lib\site-packages\django\core\management\__init__.py", line 55
except ImportError as e:
^
SyntaxError: invalid syntax
in the \management__init__.py, the imports are
import collections
import os
import sys
from optparse import OptionParser, NO_DEFAULT
import imp
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError, handle_default_options
from django.core.management.color import color_style
from django.utils.importlib import import_module
from django.utils import six
# For backwards compatibility: get_version() used to be in this module.
from django import get_version
Here's the relevant block from the same file
parts = app_name.split('.')
parts.append('management')
parts.reverse()
part = parts.pop()
path = None
# When using manage.py, the project module is added to the path,
# loaded, then removed from the path. This means that
# testproject.testapp.models can be loaded in future, even if
# testproject isn't in the path. When looking for the management
# module, we need look for the case where the project name is part
# of the app_name but the project directory itself isn't on the path.
try:
f, path, descr = imp.find_module(part, path)
except ImportError as e:
if os.path.basename(os.getcwd()) != part:
raise e
else:
if f:
f.close()
while parts:
part = parts.pop()
f, path, descr = imp.find_module(part, [path] if path else None)
if f:
f.close()
return path
in which the same line 55 from the traceback is in the try/except block towards the bottom. I've uninstalled and reinstalled but, to no avail.
It works when I give the/full/path/to/django-admin.py but it shouldn't be required.

Django 1.4 not recognizing my app

I am using django 1.4, and the app.module name does not seem to be working as expected for me. My settings.py has the app included as "survey.surveys".
Here is the django shell dump for an import I attempted through a preexisting file. The error says No module named ....
from survey.surveys.views.db import mobile_survey1
Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/pjain/dev/survey/survey/surveys/views/db.py", line 6, in <module>
from survey.surveys.models import Survey, Section, Question, Option
File "/home/pjain/dev/survey/survey/surveys/views/survey.py", line 7, in <module>
from survey.surveys.models import Survey, Section, Question, Option
ImportError: No module named surveys.models
However, when I copied and pasted the exact import which breaks, it imports fine in the shell.
from survey.surveys.models import Survey, Section, Question, Option
How can I fix this import in my project?

Pydev and Django: Shell not finding certain modules?

I am developing a Django project with PyDev in Eclipse. For a while, PyDev's Django Shell worked great. Now, it doesn't:
>>> import sys; print('%s %s' % (sys.executable or sys.platform, sys.version))
C:\Python26\python.exe 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
>>>
>>> from django.core import management;import mysite.settings as settings;management.setup_environ(settings)
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named mysite.settings
>>>
The dev server runs just fine. What could I be doing wrong?
The models module is also conspicuously absent:
>>> import mysite.myapp.models
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named mysite.myapp.models
On the normal command line, outside of PyDev, the shell works fine.
Why could this be happening?
Seems like a simple path issue. What's the output of this:
import sys; print sys.path
I don't know anything about PyDev, but there's probably a setting somewhere to add paths to the PYTHONPATH setting. If not, you can do it directly in the shell:
sys.path.insert(0, '/path/to/directory/containing/mysite/')
I had a similar problem to this a while ago while moving my project from Django 1.3 and having the settings.py file at the root of my source and then moving it down into the application.
For example what happened was that I had the following:
rootOfSource/
- settings.py
- myapp
and I changed it to be:
rootOfSource/
- myapp
- myapp/settings.py
and I also changed my settings file to be the following:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
However when I debugged into the os.eviron I found that the DJANGO_SETTINGS_MODULE was not as expected, I then changed my manage.py to be the following:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
os.environ.__setitem__("DJANGO_SETTINGS_MODULE", "myapp.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Which then allowed me to run from PyDev.
Hope this helps.
I fixed this problem by going to the project properties -> PyDev Django and setting the Django settings module.