I want know how open correctly new connection to database. A problem rise when i want create single QUERY to database, from many places in my code. For example, one request is sent to database from login.html , second from register page, third to gallery in index.html . I guess , should i use some project patterns? Do you have some suggestion ?
I have written this class which are responsible for connection to mysql database. I suppose that it is very wrong (i don't focus yet on validation - but i know about that):
import mysql.connector
import configparser
class DataBaseConnectionHandler(object):
__DATABASE = ""
user = ""
passwd = ""
host = ""
fileName = ""
dataBaseConnection = ""
def __init__(self, fileName=None, host='localhost'):
if fileName is not None:
config_file = configparser.ConfigParser()
config_file.read('shop/config/dbConfig.ini')
database: str = config_file.get('DEFAULT', 'database')
user: str = config_file.get('DEFAULT', 'user')
password: str = config_file.get('DEFAULT', 'password')
self.__DATABASE = database
self.user = user
self.passwd = password
self.host = host
def connectToDatabase(self):
""" EXECUTE CONNECTION AND RETURN AN HOOK TO DATABASE"""
dataBaseConnector = mysql.connector.connect(
host=self.host,
user=self.user,
passwd=self.passwd,
database=self.__DATABASE
)
if dataBaseConnector != "":
self.dataBaseConnection = dataBaseConnector
return self.dataBaseConnection
else:
self.dataBaseConnection = None
return self.dataBaseConnection
class RegisterUser
from .databses import DataBaseConnection
class RegisterUser(object):
__formName = ""
__formLogin = ""
__formSurrname = ""
__formPasswd = ""
__fromEmail = ""
def __init__(self, userName, userSurrname, userLogin, userPassword, userEmail):
self.__formName = userName
self.__formSurrname = userSurrname
self.__formLogin = userLogin
self.__formPasswd = userPassword
self.__fromEmail = userEmail
def createUser(self):
print("[!] Create user")
# ------------- CONNECTION TO DATABASE ----------------
hook = DataBaseConnection.DataBaseConnectionHandler('shop/config/dbConfig.ini').connectToDatabase()
myCursor = hook.cursor()
# ------------- EXECUTING MYSQL QUERY ----------------
# [!] nie szyfruje hasła
sqlStatment = "INSERT INTO user(Login, Password, Email, Name, Surname) " \
"VALUES ('{}', '{}', '{}', '{}', '{}');".format(self.__formLogin,
self.__formPasswd,
self.__fromEmail,
self.__formName,
self.__formSurrname)
myCursor.execute(sqlStatment)
hook.commit()
print(myCursor.rowcount, "Record inserted")
print("[*] Executing an query")
# ------------- CLOSE CONNECTION ----------------
hook.close()
I know that Django has own way to connect to database, but it is wired for me. i had some wired error, that why i decide use PyMysql. In near time I'll change that, but it's good moment to learn how to write code correctly .
edit:
PycharmProjects/lovLevelMusic/lovLevelMusic/settings.py changed, reloading.
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 77, in raise_last_exception
raise _exception[1]
File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 337, in execute
autoreload.check_errors(django.setup)()
File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.7/dist-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/usr/local/lib/python3.7/dist-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "/usr/local/lib/python3.7/dist-packages/django/db/models/base.py", line 117, in __new__
new_class.add_to_class('_meta', Options(meta, app_label))
File "/usr/local/lib/python3.7/dist-packages/django/db/models/base.py", line 321, in add_to_class
value.contribute_to_class(cls, name)
File "/usr/local/lib/python3.7/dist-packages/django/db/models/options.py", line 204, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/usr/local/lib/python3.7/dist-packages/django/db/__init__.py", line 28, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/usr/local/lib/python3.7/dist-packages/django/db/utils.py", line 201, in __getitem__
backend = load_backend(db['ENGINE'])
File "/usr/local/lib/python3.7/dist-packages/django/db/utils.py", line 110, in load_backend
return import_module('%s.base' % backend_name)
File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/usr/local/lib/python3.7/dist-packages/django/db/backends/mysql/base.py", line 22, in <module>
from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip
ImportError: cannot import name 'CLIENT' from 'MySQLdb.constants' (unknown location)
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbDjango',
'USER': 'root',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
Related
I'm relatively new to Django and working on a project. I was about to makemigrations and got the following trace:
demoproject lamidotijjo$ python3 manage.py makemigrations
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module>
from . import _mysql
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib
Referenced from: <D6AC4B91-4AA0-31A5-AA10-DE3277524713> /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so
Reason: tried: '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/usr/lib/libmysqlclient.21.dylib' (no such file, not in dyld cache)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/lamidotijjo/Python/Django/demoproject/manage.py", line 22, in <module>
main()
File "/Users/lamidotijjo/Python/Django/demoproject/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute
django.setup()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate
app_config.import_models()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models
self.models_module = import_module(models_module_name)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
class AbstractBaseUser(models.Model):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 141, in __new__
new_class.add_to_class("_meta", Options(meta, app_label))
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 369, in add_to_class
value.contribute_to_class(cls, name)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/options.py", line 231, in contribute_to_class
self.db_table, connection.ops.max_name_length()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/connection.py", line 15, in __getattr__
return getattr(self._connections[self._alias], item)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/connection.py", line 62, in __getitem__
conn = self.create_connection(alias)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/utils.py", line 193, in create_connection
backend = load_backend(db["ENGINE"])
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/utils.py", line 113, in load_backend
return import_module("%s.base" % backend_name)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
import MySQLdb as Database
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/__init__.py", line 24, in <module>
version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined
From what I could gather, from the "NameError: name '_mysql' is not defined error. I had also installed "pip3 install mysqlclient" prior to making migrations. That did not solve the issue.
My settings.py for my db connection is as follows:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}
}
}
I believe that my parameters are correct.
Installed mysqlclient via pip3
Verfied mysql configuration in settings.py file for django app
Googled Stacktrace posted for missing elements.
I noticed the following, error might be related to the following:
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: #rpath/libmysqlclient.21.dylib
Referenced from: <1F087C56-18D4-3EC9-8718-BEA0A3ECBAE8> /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so
Reason: tried: '/System/Volumes/Preboot/Cryptexes/OS#rpath/libmysqlclient.21.dylib' (no such file), '/usr/lib/libmysqlclient.21.dylib' (no such file, not in dyld cache)
Therefore, tried to create a symlink as root:
ln -s /usr/local/mysql-8.0.31-macos12-arm64/lib/libmysqlclient.21.dylib /usr/lib/libmysqlclient.21.dylib
I was able to fix the issue. The issue stemmed from the fact that Django was looking for the following file: "libmysqlclient.21.dylib" in the wrong location. The relative path found in "_mysql.cpython-310-darwin.so" has been set to the correct absolute path which on my system is found at "/usr/local/mysql-8.0.31-macos12-arm64/lib/libmysqlclient.21.dylib"
Command used was:
install_name_tool -change #rpath/libmysqlclient.21.dylib /usr/local/mysql-8.0.31-macos12-arm64/lib/libmysqlclient.21.dylib _mysql.cpython-310-darwin.so
I cannot access my app, when I enter the URL, it gives me the error
OperationalError: no such table: django_session
This usually means I need to migrate, or delete my sqlite database and redo migrations, so I did that multiple times. I deleted everything in the migrations folder and sqlite3.db and ran:
python manage.py makemigrations app_name
python manage.py migrate app_name
No errors yet. Then after creating a superuser I run:
python manage.py runserver
It tells me 18 migrations have not been made, which I was able to fix with:
python manage.py migrate --fake
I try the site and again I get the no such table: django_session error.
I read this thread
Django: no such table: django_session
and tried everything in it, including the approved solution, same error.
Also, when I try to run the migrate command again, I get this error
OperationalError: no such table: django_content_type
so I went to this thread
sqlite3.OperationalError: no such table: django_content_type
once again, the solutions that worked for them did not work for me.
This problem started after we migrated to MySQL, I tried to switch databases using a .env file, but ran into these problems, so I tried to switch back to sqlite so I can at least work on the project. The team is in the middle of moving to MySQL, and we have people working successfully with both databases, so it shouldn't be a database issue.
Here is my settings.py file:
import os
from pathlib import Path
from django.contrib.messages import constants as message_constants
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
SECRET_KEY = os.environ.get("DJ_SECRET_KEY", default="Testing")
DEBUG = os.environ.get("DJ_DEBUG", default=True)
ALLOWED_HOSTS = ["redonkulator.apps.dev.mach9.usmc.mil", "localhost", "127.0.0.1"]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"redonkulator_app.apps.RedonkulatorAppConfig",
"jquery",
"debug_toolbar",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.middleware.common.CommonMiddleware",
"debug_toolbar.middleware.DebugToolbarMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
ROOT_URLCONF = "iiimef_project.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
AUTH_USER_MODEL = "redonkulator_app.MlptUsers"
WSGI_APPLICATION = "iiimef_project.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
"NAME": os.environ.get(
"SQL_DATABASE",
os.path.join(BASE_DIR, "db.sqlite3"),
),
"USER": os.environ.get("SQL_USER", "user"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
"HOST": os.environ.get("SQL_HOST", "localhost"),
"PORT": os.environ.get("SQL_PORT", "5432"),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
LOGIN_REDIRECT_URL = ""
LOGOUT_REDIRECT_URL = "/about"
LOGIN_URL = "/login"
MESSAGE_STORAGE = "django.contrib.messages.storage.cookie.CookieStorage"
# needed to overwrite bootsrap classes
MESSAGE_TAGS = {
message_constants.DEBUG: "debug",
message_constants.INFO: "info",
message_constants.SUCCESS: "success",
message_constants.WARNING: "warning",
message_constants.ERROR: "danger",
}
INTERNAL_IPS = [
"127.0.0.1",
]
I have session and contenttype in my installed apps and sessions in my middleware, is there anything in here that looks obviously wrong?
Here is my .env
DJ_SECRET_KEY=super-secret-key
DJ_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] 0.0.0.0 *
DJ_DEBUG=True
SQL_DATABASE=redonkulator
SQL_ENGINE=django.db.backends.mysql
SQL_USER=[myusername]
SQL_PASSWORD=[mypassword]
SQL_HOST=localhost
SQL_PORT=3306
I know that this .env won't work with my settings, and that's okay as I'm just trying to get sqlite to work for now.
One more thing, starting today, slightly after this problem started, every django import is underlined in yellow. For example "django.contrib.messages" in settings.py is underlined, however I don't get a module import error, so I don't think that's the issue.
Finally, here is the traceback for the content_type error:
Traceback (most recent call last):
File "C:\Users\dwill\Documents\GitHub\MLPT\manage.py", line 22, in <module>
main()
File "C:\Users\dwill\Documents\GitHub\MLPT\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\commands\migrate.py", line 268, in handle
emit_post_migrate_signal(
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\sql.py", line 42, in emit_post_migrate_signal
models.signals.post_migrate.send(
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send
return [
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\management\__init__.py", line 42, in create_permissions
create_contenttypes(app_config, verbosity=verbosity, interactive=interactive, using=using, apps=apps, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\contenttypes\management\__init__.py", line 119, in create_contenttypes
content_types, app_models = get_contenttypes_and_models(app_config, using, ContentType)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\contenttypes\management\__init__.py", line 94, in get_contenttypes_and_models
content_types = {
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 280, in __iter__
self._fetch_all()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_content_type
and the django session error:
Traceback (most recent call last):
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
The above exception (no such table: django_session) was the direct cause of the following exception:
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\admin\sites.py", line 414, in login
return LoginView.as_view(**defaults)(request)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\views.py", line 63, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\views.py", line 92, in form_valid
auth_login(self.request, form.get_user())
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\__init__.py", line 111, in login
request.session.cycle_key()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\base.py", line 344, in cycle_key
self.create()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 51, in create
self._session_key = self._get_new_session_key()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\base.py", line 196, in _get_new_session_key
if not self.exists(session_key):
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 47, in exists
return self.model.objects.filter(session_key=session_key).exists()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 808, in exists
return self.query.has_results(using=self.db)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\query.py", line 550, in has_results
return compiler.has_results()
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1145, in has_results
return bool(self.execute_sql(SINGLE))
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 198, in execute
return self._record(self.cursor.execute, sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 133, in _record
return method(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/login/
Exception Value: no such table: django_session
Try avoiding the .env file to rule that out.
Update settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DBNAME',
'USER': 'USER',
'PASSWORD': 'PASS',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
If this works then we have found the source of the problem and should double-check the location of the .env file and work backwards from there.
After making your migrations, try sync your database:
python manage.py migrate --run-syncdb
It has solved this error code for me several times.
Newbie. Have googled, and seeing nothing.
Trying to get into admin/ and it says:
/usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in get_new_connection, line 346
[It is trying to use SQLlite as database].
But I have MySQL as the database--and the other functions in regards to using MySQL work correctly. (it updates MySQL database when adding new apps).
I even manually checked MySQL database, and it has the superuser that I added!
Anyone have any ideas?
Environment:
full stack trace:
Request Method: POST Request URL: ommitted/
Django Version: 1.6.2 Python Version: 2.6.6 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback: File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py" in wrapper
215. return self.admin_view(view, cacheable)(*args, **kwargs) File "/usr/lib/python2.6/site-packages/django/utils/decorators.py" in
_wrapped_view
99. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.6/site-packages/django/views/decorators/cache.py" in
_wrapped_view_func
52. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py" in inner
197. return self.login(request) File "/usr/lib/python2.6/site-packages/django/views/decorators/cache.py" in
_wrapped_view_func
52. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py" in login
330. return login(request, **defaults) File "/usr/lib/python2.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
75. return view(request, *args, **kwargs) File "/usr/lib/python2.6/site-packages/django/utils/decorators.py" in
_wrapped_view
99. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.6/site-packages/django/views/decorators/cache.py" in
_wrapped_view_func
52. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.6/site-packages/django/contrib/auth/views.py" in login
36. if form.is_valid(): File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in is_valid
129. return self.is_bound and not bool(self.errors) File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in errors
121. self.full_clean() File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in full_clean
274. self._clean_form() File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in
_clean_form
300. self.cleaned_data = self.clean() File "/usr/lib/python2.6/site-packages/django/contrib/admin/forms.py" in clean
28. self.user_cache = authenticate(username=username, password=password) File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py" in authenticate
49. user = backend.authenticate(**credentials) File "/usr/lib/python2.6/site-packages/django/contrib/auth/backends.py" in authenticate
16. user = UserModel._default_manager.get_by_natural_key(username) File "/usr/lib/python2.6/site-packages/django/contrib/auth/models.py" in get_by_natural_key
167. return self.get(**{self.model.USERNAME_FIELD: username}) File "/usr/lib/python2.6/site-packages/django/db/models/manager.py" in get
151. return self.get_queryset().get(*args, **kwargs) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in get
301. num = len(clone) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in
__len__
77. self._fetch_all() File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in
_fetch_all
854. self._result_cache = list(self.iterator()) File "/usr/lib/python2.6/site-packages/django/db/models/query.py" in iterator
220. for row in compiler.results_iter(): File "/usr/lib/python2.6/site-packages/django/db/models/sql/compiler.py" in results_iter
709. for rows in self.execute_sql(MULTI): File "/usr/lib/python2.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
781. cursor = self.connection.cursor() File "/usr/lib/python2.6/site-packages/django/db/backends/__init__.py" in cursor
157. cursor = self.make_debug_cursor(self._cursor()) File "/usr/lib/python2.6/site-packages/django/db/backends/__init__.py" in _cursor
129. self.ensure_connection() File "/usr/lib/python2.6/site-packages/django/db/backends/__init__.py" in ensure_connection
124. self.connect() File "/usr/lib/python2.6/site-packages/django/db/utils.py" in __exit__
99. six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/lib/python2.6/site-packages/django/db/backends/__init__.py" in ensure_connection
124. self.connect() File "/usr/lib/python2.6/site-packages/django/db/backends/__init__.py" in connect
112. self.connection = self.get_new_connection(conn_params) File "/usr/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py" in get_new_connection
346. conn = Database.connect(**conn_params)
Exception Type: OperationalError at /admin/ Exception Value: unable to open database file
settings.py database settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'pymail',
'USER': 'pymail',
'PASSWORD': 'removed',
'HOST': 'removed',
'PORT': '3306',
}
}
During my first attempt at using django-reversion, I was evaluating it to see if I can do certain basic version retrieval operations on my model:
I'm unable to retrieve a list of prior versions of specific model after saving a change to a specific field within scope of reversion as shown below. I get the following error in stack trace when attempting a reversion.get_for_object():
DatabaseError: (1146, "Table 'pvtestmatrix.django_content_type' doesn't exist")
Django: v1.3.1
django-reversion: v1.5.7
Installed django-reversion and managed a syncdb successfully:
bash-3.2$ python manage.py syncdb
Creating tables ...
Creating table reversion_revision
Creating table reversion_version
Installing custom SQL ...
Installing indexes ...
No fixtures found.
Added reversion specific settings in settings.py:
INSTALLED_APPS = (
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.sites',
# 'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.staticfiles',
'collabgrid.testmatrix',
'collabgrid.testcase',
'collabgrid.status',
'reversion',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'reversion.middleware.RevisionMiddleware',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'PVTestMatrix',
...}
}
models.py:
...
class Testmatrix(models.Model):
testmatrixid = models.AutoField(primary_key=True, db_column='TestMatrixId')
platform = models.CharField(max_length=60, db_column='Platform', blank=True)
...
class Meta:
db_table = u'TestMatrix'
def __str__(self):
return '%s__%s__%s' % (self.productid, self.testmatrixid, self.owner)
...
view.py snippet:
from collabgrid.testmatrix.models import Testmatrix
import reversion
reversion.register(Testmatrix)
tm=Testmatrix.objects.get(pk=729)
with reversion.create_revision():
tm.platform="AAA"
tm.save()
version_list = reversion.get_for_object(tm)
stack trace:
>>> from collabgrid.testmatrix.models import Testmatrix
>>> import reversion
>>>
>>> reversion.register(Testmatrix)
>>> tm=Testmatrix.objects.get(pk=729)
>>> with reversion.create_revision():
... tm.platform="AAA"
... tm.save()
...
Traceback (most recent call last):
File "<console>", line 3, in <module>
File "/Library/Python/2.6/site-packages/reversion/revisions.py", line 290, in __exit__
self._context_manager.end()
File "/Library/Python/2.6/site-packages/reversion/revisions.py", line 176, in end
in manager_context.iteritems()
File "/Library/Python/2.6/site-packages/reversion/revisions.py", line 175, in <genexpr>
for obj, data
File "/Library/Python/2.6/site-packages/reversion/revisions.py", line 602, in <lambda>
version_data = lambda: adapter.get_version_data(instance, VERSION_CHANGE, self._revision_context_manager._db)
File "/Library/Python/2.6/site-packages/reversion/revisions.py", line 97, in get_version_data
content_type = ContentType.objects.db_manager(db).get_for_model(obj)
File "/Library/Python/2.6/site-packages/django/contrib/contenttypes/models.py", line 38, in get_for_model
defaults = {'name': smart_unicode(opts.verbose_name_raw)},
File "/Library/Python/2.6/site-packages/django/db/models/manager.py", line 135, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 378, in get_or_create
return self.get(**lookup), False
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 344, in get
num = len(clone)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 82, in __len__
self._result_cache = list(self.iterator())
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 273, in iterator
for row in compiler.results_iter():
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "/Library/Python/2.6/site-packages/django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "/Library/Python/2.6/site-packages/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
DatabaseError: (1146, "Table 'pvtestmatrix.django_content_type' doesn't exist")
>>> version_list = reversion.get_for_object(tm)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.6/site-packages/reversion/revisions.py", line 527, in get_for_object
return self.get_for_object_reference(obj.__class__, obj.pk, db)
File "/Library/Python/2.6/site-packages/reversion/revisions.py", line 506, in get_for_object_reference
content_type = ContentType.objects.db_manager(db).get_for_model(model)
File "/Library/Python/2.6/site-packages/django/contrib/contenttypes/models.py", line 38, in get_for_model
defaults = {'name': smart_unicode(opts.verbose_name_raw)},
File "/Library/Python/2.6/site-packages/django/db/models/manager.py", line 135, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 378, in get_or_create
return self.get(**lookup), False
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 344, in get
num = len(clone)
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 82, in __len__
self._result_cache = list(self.iterator())
File "/Library/Python/2.6/site-packages/django/db/models/query.py", line 273, in iterator
for row in compiler.results_iter():
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "/Library/Python/2.6/site-packages/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "/Library/Python/2.6/site-packages/django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "/Library/Python/2.6/site-packages/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
DatabaseError: (1146, "Table 'pvtestmatrix.django_content_type' doesn't exist")
Am I using reversion correctly here? By running "reversion.get_for_object(tm)" I'm expecting to see a list containing at least the last saved version when issuing "tm.save()" in previous step.
Not sure if this error is specific to reversion handling as I'm able to commit changes to models I would normally without using reversion. Thanks in advance.
Your django_content_type table doesn't exist because django.contrib.contenttypes is commented out in your INSTALLED_APPS. Uncomment it (remove the #) and run syncdb again.
I am using SQLAlchemy 0.8 with Google App Engine and Cloud SQL. I would like to do a full integration test locally before deploying, but I cannot get SQLAlchemy to connect to my development MySQL server using the mysql+gaerdbms dialect
create_engine(
'mysql+gaerdbms:///test?instance=homingbox:instance1'
)
I start my app engine from the command line as follows
python dev_appserver.py --mysql_user=username --mysql_password=root ../Source/HomingBox/gae
Whenever I try to hit the database I get this lovely stack trace
ERROR 2013-04-22 21:35:39,987 webapp2.py:1528] (ImportError) None None
Traceback (most recent call last):
File "/home/leon/Development/google_appengine/lib/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/home/leon/Development/google_appengine/lib/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/home/leon/Development/google_appengine/lib/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/home/leon/Development/google_appengine/lib/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/home/leon/Development/google_appengine/lib/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/home/leon/Development/google_appengine/lib/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/home/leon/Development/Source/HomingBox/gae/rest.py", line 19, in get_list
self.response.write(json.dumps(application.get_list()))
File "/home/leon/Development/Source/HomingBox/gae/dal.py", line 98, in get_list
return query.all()
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/orm/query.py", line 2140, in all
return list(self)
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/orm/query.py", line 2252, in __iter__
return self._execute_and_instances(context)
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/orm/query.py", line 2265, in _execute_and_instances
close_with_result=True)
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/orm/query.py", line 2256, in _connection_from_session
**kw)
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/orm/session.py", line 797, in connection
close_with_result=close_with_result)
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/orm/session.py", line 801, in _connection_for_bind
return self.transaction._connection_for_bind(engine)
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/orm/session.py", line 297, in _connection_for_bind
conn = bind.contextual_connect()
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/engine/base.py", line 1669, in contextual_connect
self.pool.connect(),
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/pool.py", line 272, in connect
return _ConnectionFairy(self).checkout()
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/pool.py", line 425, in __init__
rec = self._connection_record = pool._do_get()
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/pool.py", line 855, in _do_get
return self._create_connection()
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/pool.py", line 225, in _create_connection
return _ConnectionRecord(self)
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/pool.py", line 318, in __init__
self.connection = self.__connect()
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/pool.py", line 368, in __connect
connection = self.__pool._creator()
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/engine/strategies.py", line 80, in connect
return dialect.connect(*cargs, **cparams)
File "/home/leon/Development/Source/HomingBox/gae/sqlalchemy/engine/default.py", line 279, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/home/leon/Development/google_appengine/google/storage/speckle/python/api/rdbms_googleapi.py", line 183, in __init__
super(GoogleApiConnection, self).__init__(*args, **kwargs)
File "/home/leon/Development/google_appengine/google/storage/speckle/python/api/rdbms.py", line 810, in __init__
self.OpenConnection()
File "/home/leon/Development/google_appengine/google/storage/speckle/python/api/rdbms.py", line 832, in OpenConnection
self.SetupClient()
File "/home/leon/Development/google_appengine/google/storage/speckle/python/api/rdbms_googleapi.py", line 193, in SetupClient
self._client = RdbmsGoogleApiClient(**kwargs)
File "/home/leon/Development/google_appengine/google/storage/speckle/python/api/rdbms_googleapi.py", line 106, in __init__
rdbms.OAUTH_CREDENTIALS_PATH)
File "/usr/lib/python2.7/posixpath.py", line 268, in expanduser
import pwd
File "/home/leon/Development/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 827, in load_module
raise ImportError
Any help is much appreciated
Here's my hypothesis, based on the stack trace -- when the application can't find your HOME directory, it attempts to import pwd and get the home directory information that way. The application is trying to call this bit of code in posixpath.py:
if 'HOME' not in os.environ:
import pwd
userhome = pwd.getpwuid(os.getuid()).pw_dir
else:
userhome = os.environ['HOME']
Except, I don't think that GAE will allow pwd to be imported for security reasons. The sandbox environment doesn't look to have it included in its whitelist of allowed modules, and raises an ImportError if the modules aren't in that list.
If I attempt to just do an import pwd inside of a regular handler module, GAE won't allow it.