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.
Related
I'm trying to build my application, after installing flask_login0.4.1 and configuring it
i come across this error
Traceback (most recent call last):
File "C:\Users\Catalyst\Desktop\Python\chatAp\application.py", line 2, in <module>
from wtform_fields import *
File "C:\Users\Catalyst\Desktop\Python\chatAp\wtform_fields.py", line 6, in <module>
from models import User
File "C:\Users\Catalyst\Desktop\Python\chatAp\models.py", line 2, in <module>
from flask_login import UserMixin
File "C:\Users\Catalyst\Desktop\Python\chatAp\venv\lib\site-packages\flask_login\__init__.py", line 16, in <module>
from .login_manager import LoginManager
File "C:\Users\Catalyst\Desktop\Python\chatAp\venv\lib\site-packages\flask_login\login_manager.py", line 24, in <module>
from .utils import (_get_user, login_url as make_login_url, _create_identifier,
File "C:\Users\Catalyst\Desktop\Python\chatAp\venv\lib\site-packages\flask_login\utils.py", line 13, in <module>
from werkzeug.security import safe_str_cmp
ImportError: cannot import name 'safe_str_cmp' from 'werkzeug.security' (C:\Users\Catalyst\Desktop\Python\chatAp\venv\lib\site-packages\werkzeug\security.py)
based on answers on stackoverflow I have downgraded werkzeug to 2.0.0 but i got other error
Traceback (most recent call last):
File "C:\Users\Catalyst\Desktop\Python\chatAp\application.py", line 1, in <module>
from flask import Flask, render_template,redirect,url_for
File "C:\Users\Catalyst\Desktop\Python\chatAp\venv\lib\site-packages\flask\__init__.py", line 4, in <module>
from . import json as json
File "C:\Users\Catalyst\Desktop\Python\chatAp\venv\lib\site-packages\flask\json\__init__.py", line 8, in <module>
from ..globals import current_app
File "C:\Users\Catalyst\Desktop\Python\chatAp\venv\lib\site-packages\flask\globals.py", line 56, in <module>
app_ctx: "AppContext" = LocalProxy( # type: ignore[assignment]
TypeError: LocalProxy.__init__() got an unexpected keyword argument 'unbound_message'
what other alternatives solutions I can use
I'm using flask 2.2.2
Try
Werkzeug <= 2.1.2
flask == 2.1.2
Both of these have to be compatible. Let me know if you can work it out. the above version worked for me.
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.
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.
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 have directory structure as follow:
gnukhata/tests/functional.
In functional folder I have web tests files. Following is the sample test.
from gnukhata.tests import *
class TestVendorController(TestController):
def test_index(self):
response = self.app.get(url(controller='vendor', action='index'))
After running this test file, gives following error:
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/twisted/trial/runner.py", line 651, in loadByNames
things.append(self.findByName(name))
File "/usr/lib/python2.6/dist-packages/twisted/trial/runner.py", line 460, in findByName
return filenameToModule(name)
File "/usr/lib/python2.6/dist-packages/twisted/trial/runner.py", line 98, in filenameToModule
return _importFromFile(fn)
File "/usr/lib/python2.6/dist-packages/twisted/trial/runner.py", line 117, in _importFromFile
module = imp.load_source(moduleName, fn, fd)
File "test_vendor.py", line 1, in <module>
from gnukhata.tests import *
exceptions.ImportError: No module named tests
Instead of gnukhata.tests if I write gnukhata then it shows the following error:
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/twisted/trial/runner.py", line 651, in loadByNames
things.append(self.findByName(name))
File "/usr/lib/python2.6/dist-packages/twisted/trial/runner.py", line 460, in findByName
return filenameToModule(name)
File "/usr/lib/python2.6/dist-packages/twisted/trial/runner.py", line 98, in filenameToModule
return _importFromFile(fn)
File "/usr/lib/python2.6/dist-packages/twisted/trial/runner.py", line 117, in _importFromFile
module = imp.load_source(moduleName, fn, fd)
File "test_vendor.py", line 3, in <module>
class TestVendorController(TestController):
exceptions.NameError: name 'TestController' is not defined
Try my most simple configuration and let me know if it work:
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from gnukhata.lib.base import BaseController, render
from gnukhata import model
import gnukhata.model.meta as meta
In the init.py:
from unittest import TestCase
from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import url
from routes.util import URLGenerator
from webtest import TestApp
from pylons import config
import pylons.test
__all__ = ['environ', 'url', 'TestController']
# Invoke websetup with the current config file
SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']])
environ = {}
class TestController(TestCase):
def __init__(self, *args, **kwargs):
wsgiapp = pylons.test.pylonsapp
config = wsgiapp.config
self.app = TestApp(wsgiapp)
url._push_object(URLGenerator(config['routes.map'], environ))
TestCase.__init__(self, *args, **kwargs)
Is there an __init__.py in gnukhata/tests directory? If not, then gnukhata.tests is not recognized as a module and you can't import from it.
If such file does exist, could you post here the import statements in gnukhata/tests/__init__.py if any?