python module import conundrum (module from submodule) - python

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.

Related

partially initialized module 'router' has no attribute 'FindCorrectRoute' (most likely due to a circular import)

I try to call from main.py a function in router.py that will call a function in calculator.py that will try to modify a variable in main.py
Something that in C# is achieved for example by creating a public static variable, I don't know how to achieve it in Python.
This is my file main.py:
import router
# create a table
global mytable
mytable = []
router.CallAnotherFunction("testing data")
This is my file router.py:
import calculator
def CallAnotherFunction(sample_data):
calculator.ModifyMainTable(sample_data)
This is my calculator.py:
import main
def ModifyMainTable(sample_data):
main.mytable = sample_data
This is the error I'm getting just when trying to execute router.CallAnotherFunction("testing data"):
AttributeError
partially initialized module 'router' has no attribute 'FindCorrectRoute' (most likely due to a circular import)
File "C:\Users\dimitri\Documents\Upwork\Footyamigo\main.py", line 37, in <module>
router.FindCorrectRoute(odd, next_match, local_data, visitor_data)
File "C:\Users\dimitri\Documents\Upwork\Footyamigo\calculator.py", line 3, in <module>
import main
File "C:\Users\dimitri\Documents\Upwork\Footyamigo\router.py", line 1, in <module>
import calculator
File "C:\Users\dimitri\Documents\Upwork\Footyamigo\main.py", line 5, in <module>
import router
What I really need is that mytable is accesible from all files and if I change it's value from any file I have to see the changes reflected on the others, I don't want to have different instances of the object.
Just solved it import __main__ as main inside calculator.py

Python import error when importing from __init__.py

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.

Error in Tumblelog Application development using Flask and MongoEngine

I am trying to follow below tutorial but I am facing few issue, when i run manage.py. Any help could be great help.
http://docs.mongodb.org/ecosystem/tutorial/write-a-tumblelog-application-with-flask-mongoengine/#id1
manage.py run output:
(Tumbler)afiz Tumbler $ python manage.py
Traceback (most recent call last):
File "manage.py", line 6, in <module>
from tumblelog import app
File "/home/afiz/.virtualenvs/tumblelog/__init__.py", line 18, in <module>
register_blueprints(app)
File "/home/afiz/.virtualenvs/tumblelog/__init__.py", line 13, in register_blueprints
from tumblelog.views import posts
File "/home/afiz/.virtualenvs/tumblelog/views.py", line 5, in <module>
from tumblelog.models import Post, Comment
File "/home/afiz/.virtualenvs/tumblelog/models.py", line 6, in <module>
class Post(db.DynamicDocument):
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/base/metaclasses.py", line 361, in __new__
meta['index_specs'] = new_class._build_index_specs(meta['indexes'])
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 722, in _build_index_specs
unique_indices = cls._unique_with_indexes()
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 861, in _unique_with_indexes
field.document_type != cls):
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/fields.py", line 563, in document_type
self.document_type_obj = get_document(self.document_type_obj)
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/base/common.py", line 25, in get_document
""".strip() % name)
mongoengine.errors.NotRegistered: `Comment` has not been registered in the document registry.
Importing the document class automatically registers it, has it
been imported?
manage.py file:
#set the path
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from flask.ext.script import Manager, Server
from tumblelog import app
manager = Manager(app)
# Turn on debugger by default and reloader
manager.add_command("runserver", Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0')
)
if __name__ == "__main__":
manager.run()
I had the same problem as you are facing now. In models.py file I just wrote
class Comment(db.EmbeddedDocument):
and it's content first then added
class Post(db.Document):
and then it's content. In other words, I first wrote Comment class then Post class and problem got solved ;) :) Cheers!!
Inside Post, when EmbeddedDocumentField is assigned to a variable, it needs to be pre-registered. Therefore, always register such field i.e. Comments before they are used.

Python ImportError: cannot import modules/classes

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?

Importing from main app in a flask blueprint

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.

Categories

Resources