OperationalError: no such table: django_content_type and django_session - mysql

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.

Related

Django: Getting Interface Error, Exception Value: (0, '') when using remote MySQL DB but not local DB

Trying to login to my app, I am getting this error when I am using a MySQL DB hosted remotely but not when I am connecting to my locally hosted XAMPP one.
I've read a couple entries on my question but they mostly mention cursors that aren't explicitly closed, which I don't need to since I am using with in all my raw queries.
I am using django-allauth for my authentication.
Traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/accounts/login/?next=/
Django Version: 3.1.2
Python Version: 3.8.6
Installed Applications:
['ewhale_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'users.apps.UsersConfig',
'pages.apps.PagesConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'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 (most recent call last):
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
return self.cursor.execute(query, args)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 206, in execute
res = self._query(query)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 319, in _query
db.query(q)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\connections.py", line 259, in query
_mysql.connection.query(self, query)
The above exception ((0, '')) was the direct cause of the following exception:
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\allauth\account\views.py", line 138, in dispatch
return super(LoginView, self).dispatch(request, *args, **kwargs)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\allauth\account\views.py", line 78, in dispatch
response = super(RedirectAuthenticatedUserMixin,
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\allauth\account\views.py", line 94, in get
response = super(AjaxCapableProcessFormViewMixin, self).get(
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\allauth\account\views.py", line 169, in get_context_data
site = get_current_site(self.request)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\sites\shortcuts.py", line 13, in get_current_site
return Site.objects.get_current(request)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\sites\models.py", line 58, in get_current
return self._get_site_by_id(site_id)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\sites\models.py", line 30, in _get_site_by_id
site = self.get(pk=site_id)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 425, in get
num = len(clone)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 269, in __len__
self._fetch_all()
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\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\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
return self.cursor.execute(query, args)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 206, in execute
res = self._query(query)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 319, in _query
db.query(q)
File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\connections.py", line 259, in query
_mysql.connection.query(self, query)
Exception Type: InterfaceError at /accounts/login/
Exception Value: (0, '')
Would appreciate feedback on where to check the issue.
Avoided this issue by recreating a new DB and migrating.

Django can not create test database using MySQL

I'm developing a large Django project and I'm beginning to write some tests. But I ran into a problem when running them. When I run python manage.py test I get the following error:
$ project/ python manage.py test
project/env/lib/python3.7/site-packages/django/db/models/base.py:319: RuntimeWarning: Model 'accounts.manager' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
Creating test database for alias 'default'...
Got an error creating the test database: (1007, "Can't create database 'test_partyadvisor'; database exists")
Type 'yes' if you would like to try deleting the test database 'test_partyadvisor', or 'no' to cancel: yes
Destroying old test database for alias 'default'...
Traceback (most recent call last):
File "project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
File "project/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "project/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "project/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 312, in _query
db.query(q)
File "project/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 224, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.OperationalError: (1170, "BLOB/TEXT column 'content' used in key specification without a key length")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "project/env/lib/python3.7/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv
super(Command, self).run_from_argv(argv)
File "project/env/lib/python3.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "project/env/lib/python3.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "project/env/lib/python3.7/site-packages/django/core/management/commands/test.py", line 62, in handle
failures = test_runner.run_tests(test_labels)
File "project/env/lib/python3.7/site-packages/django/test/runner.py", line 601, in run_tests
old_config = self.setup_databases()
File "project/env/lib/python3.7/site-packages/django/test/runner.py", line 546, in setup_databases
self.parallel, **kwargs
File "project/env/lib/python3.7/site-packages/django/test/utils.py", line 187, in setup_databases
serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
File "project/env/lib/python3.7/site-packages/django/db/backends/base/creation.py", line 69, in create_test_db
run_syncdb=True,
File "project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 131, in call_command
return command.execute(*args, **defaults)
File "project/env/lib/python3.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "project/env/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "project/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "project/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "project/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "project/env/lib/python3.7/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "project/env/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 97, in database_forwards
schema_editor.create_model(model)
File "project/env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 319, in create_model
self.execute(sql, params or None)
File "project/env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 136, in execute
cursor.execute(sql, params)
File "project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "project/env/lib/python3.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "project/env/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "project/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
File "project/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "project/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "project/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 312, in _query
db.query(q)
File "project/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 224, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'content' used in key specification without a key length")
The test database is created, but for some reason I can not use it (?).
My database configuration is, (in the settings.py file):
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"HOST": env.get("database").get("HOST"),
"PORT": env.get("database").get("PORT"),
"NAME": env.get("database").get("NAME"),
"USER": env.get("database").get("USER"),
"PASSWORD": env.get("database").get("PASS")
}
}
Notes:
The user I use to access the db has all grants on it.
I tried to run the tests using the root user, and got the same error.
The normal db and the cache one work perfectly.
Also ran makemigrations and migrate.
Deleted the test db from MySQL shell and re-run python manage.py test, got the same error.
Option --keep-db not working either.
System is Ubuntu 18.04 and I'm using Django 1.11 and MySQL 5.7.

How correct open connections to database in Python/Django

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',
}
}

django-reversion: get_for_object() throws database error "'<db_name>.django_content_type' doesn't exist"

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.

SQLAlchemy with Google Cloud SQL connect to development server

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.