Flask(flask db init): AttributeError: module 'time' has no attribute 'clock' - python

While following a Flask tutorial I stumbled around this very strange problem! While setting up the Migrate directory , after the first step of setting the flask app using set FLASK_APP=sql1.py, when I ran this command flask db init I got this error:
(first_flask_env) C:\Users\aakash\Desktop\python programs>flask db init
Traceback (most recent call last):
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\aakash\Anaconda3\envs\first_flask_env\Scripts\flask.exe\__main__.py", line 7, in <module>
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask\cli.py", line 894, in main
cli.main(args=args, prog_name=name)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask\cli.py", line 557, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\click\core.py", line 1061, in invoke
cmd_name, cmd, args = self.resolve_command(ctx, args)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\click\core.py", line 1100, in resolve_command
cmd = self.get_command(ctx, cmd_name)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask\cli.py", line 500, in get_command
self._load_plugin_commands()
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask\cli.py", line 496, in _load_plugin_commands
self.add_command(ep.load(), ep.name)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\pkg_resources\__init__.py", line 2472, in load
return self.resolve()
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\pkg_resources\__init__.py", line 2478, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask_migrate\__init__.py", line 8, in <module>
from alembic import __version__ as __alembic_version__
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\__init__.py", line 8, in <module>
from . import op # noqa
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\op.py", line 1, in <module>
from .operations.base import Operations
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\operations\__init__.py", line 1, in <module>
from .base import Operations, BatchOperations
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\operations\base.py", line 3, in <module>
from .. import util
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\util\__init__.py", line 6, in <module>
from .pyfiles import ( # noqa
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\util\pyfiles.py", line 6, in <module>
from mako.template import Template
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\template.py", line 10, in <module>
from mako.lexer import Lexer
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\lexer.py", line 11, in <module>
from mako import parsetree, exceptions, compat
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\parsetree.py", line 9, in <module>
from mako import exceptions, ast, util, filters, compat
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\exceptions.py", line 11, in <module>
from mako import util, compat
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\util.py", line 11, in <module>
from mako import compat
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\compat.py", line 124, in <module>
time_func = time.clock
AttributeError: module 'time' has no attribute 'clock'
I'm getting the exact same error while running my .py script also,here's the script:
from flask import Flask
import os
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
basedir = os.path.abspath(os.path.dirname(__file__)) #Full directory path of the file I'm working with..here, sql1.py
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app,db) #Here it connect the application "app.py"
# with the database "db"
class puppy(db.Model):
__tablename__ = 'Name Provided by me!!'
id = db.Column(db.Integer,primary_key = True)
name = db.Column(db.Text)
age = db.Column(db.Integer)
def __init__(self,name,age):
self.name = name
self.age = age
def __repr__(self):
return f"puppy {self.name} is {self.age} year/s old!"
I looked into every solution I found (here and this)and made sure everything was correct! I ran this command when my environment was activated which had installed every package needed including SQLAlchemy and Flask-Migrate.
I even deleted them (packages) and re-installed their latest versions but still getting the same error!
I'm using Python 3.8.5

You have some dependencies that are too old and incompatible with Python 3.8. At the very least, you should update the mako package:
pip install --upgrade mako

I had a similar issue I had to update flask_sqlalchemy even after doing this I had issues. I ended up having to make a new virtual environment, I would make a small hello world project on another virtual environment to see if that works.

For me, it was giving the same error, so I removed __init__.py file from the folder which has app.py
After removing I ran the
flask init db
it worked :)

Related

TypeError: unhashable type: 'Path' (Importing any package)

EDIT: I've narrowed this down to django rest framework, but not exactly why. About to start deep package debugging :/
I've got a weird one here. I've setup a mini Django project, and in the urls.py file, if I try any "from package import X", it results in an exception: TypeError: unhashable type: 'Path'
With no imports in this file, it all works perfectly and the server starts etc.
File "/app/app/urls.py", line 2, in <module>
2023-01-21T04:41:15.890469838Z from rest_framework.response import Response
2023-01-21T04:41:15.890486088Z File "/usr/local/lib/python3.8/site-packages/rest_framework/response.py", line 11, in <module>
2023-01-21T04:41:15.890490338Z from rest_framework.serializers import Serializer
2023-01-21T04:41:15.890492504Z File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 27, in <module>
2023-01-21T04:41:15.890516629Z from rest_framework.compat import postgres_fields
2023-01-21T04:41:15.890534421Z File "/usr/local/lib/python3.8/site-packages/rest_framework/compat.py", line 33, in <module>
2023-01-21T04:41:15.890571546Z import coreapi
2023-01-21T04:41:15.890591004Z File "/usr/local/lib/python3.8/site-packages/coreapi/__init__.py", line 2, in <module>
2023-01-21T04:41:15.890598088Z from coreapi import auth, codecs, exceptions, transports, utils
2023-01-21T04:41:15.890600588Z File "/usr/local/lib/python3.8/site-packages/coreapi/auth.py", line 1, in <module>
2023-01-21T04:41:15.890602963Z from coreapi.utils import domain_matches
2023-01-21T04:41:15.890605254Z File "/usr/local/lib/python3.8/site-packages/coreapi/utils.py", line 5, in <module>
2023-01-21T04:41:15.890724213Z import pkg_resources
2023-01-21T04:41:15.890736088Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3249, in <module>
2023-01-21T04:41:15.891071296Z def _initialize_master_working_set():
2023-01-21T04:41:15.891081671Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3223, in _call_aside
2023-01-21T04:41:15.891363838Z f(*args, **kwargs)
2023-01-21T04:41:15.891371088Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 3261, in _initialize_master_working_set
2023-01-21T04:41:15.891722921Z working_set = WorkingSet._build_master()
2023-01-21T04:41:15.891733421Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 608, in _build_master
2023-01-21T04:41:15.891780379Z ws = cls()
2023-01-21T04:41:15.891790796Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 601, in __init__
2023-01-21T04:41:15.891883463Z self.add_entry(entry)
2023-01-21T04:41:15.891889546Z File "/usr/local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 655, in add_entry
2023-01-21T04:41:15.892080713Z self.entry_keys.setdefault(entry, [])
2023-01-21T04:41:15.892097713Z TypeError: unhashable type: 'Path'
Here is the full repo ready to run https://gitlab.com/mainmast/import-issue/-/tree/main
You will need to add an .env file in services/shared/ folder. Then you can run "make up"
POSTGRES_PASSWORD=ai
POSTGRES_USER=ai
POSTGRES_DBNAME=ai
POSTGRES_HOST=postgres-ai
POSTGRES_TEST=test_ai
SECRET_KEY=%&jxaf6ijs36d82#r+^hq%=d7w8*2)r9afv*z#5y=(vt$h38m5
REGISTRATION_SALT=sx<)XYH.G0\"3GhqGLfY7~3Nt'63\"Yp
DJANGO_DEBUG=True
DEBUG_DB=True
ALLOWED_HOSTS=*
CORS_ORIGIN_WHITELIST=http://0.0.0.0
CORS_ALLOWED_ORIGINS=http://0.0.0.0
WEB_SERVER=app.myapp.co
WEB_APP_URL=app.myapp.co
EMAIL_URL=
AXES_BEHIND_REVERSE_PROXY=off
SITE_ID=3
ACCESS_TOKEN_EXPIRE_SECONDS=600
SUPPORT_EMAIL=
ACCOUNT_ACTIVATION_DAYS=2
SENTRY_ID=
SENTRY_ENDPOINT=
SENTRY_ENVIRONMENT=SomeEnv
MAX_IMAGE_UPLOAD_SIZE_BYTES=10000000
# Application environment settings
APP_ENV=local
APP_USE_AWS_S3_STATIC=False
APP_USE_AWS_S3_MEDIA=False
SSL_CERT_CHAIN=ssl\/local.crt
SSL_CERT_KEY=ssl\/local.key
SSL_CERT_DHPARAM=ssl\/dhparams.local.pem
I've never come across this before, although this is the first time I'm doing experimenting with sharing Django code across smaller independent container services.
Any help would be greatly appreciated. I see that something around coreapi dies, and no matter what I import, coreapi seems to be there as the last thing trying to import pkg_resources - but I can't figure out why?

Using Boto3 to Manage AWS from Google App Engine

I am trying to use Boto3 in order to manage some EC2 instances from my GAE app, but importing Boto3 results in the following error:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/Users/squad/Desktop/Squad/Squad/squad.py", line 6, in <module>
from boto3 import Session
File "/Users/squad/Desktop/Squad/Squad/lib/boto3/__init__.py", line 16, in <module>
from boto3.session import Session
File "/Users/squad/Desktop/Squad/Squad/lib/boto3/session.py", line 17, in <module>
import botocore.session
File "/Users/squad/Desktop/Squad/Squad/lib/botocore/session.py", line 32, in <module>
from botocore.loaders import create_loader
File "/Users/squad/Desktop/Squad/Squad/lib/botocore/loaders.py", line 188, in <module>
class Loader(object):
File "/Users/squad/Desktop/Squad/Squad/lib/botocore/loaders.py", line 201, in Loader
CUSTOMER_DATA_PATH = os.path.join(os.path.expanduser('~'),
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 261, in expanduser
import pwd
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 963, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named pwd
I am able to use Boto just fine, so this in no way is a pressing need, but I would prefer to use Boto3 if possible.
I am using Python2.7, if that is of any help.
Thanks for the help.
You will have to fake the pwd module.
Create a file named fake_pwd.py with the necessary shims:
class struct_passwd_dummy(object):
def __init__(self, uid):
self.pw_name = "user"
self.pw_passwd = "x"
self.pw_uid = uid
self.pw_gid = uid
self.pw_gecos = "user"
self.pw_dir = "/home/user"
self.pw_shell = "/bin/sh"
def getpwuid(uid):
return struct_passwd_dummy(uid)
Then, in appengine_config.py, try this hack:
try:
import boto3
except ImportError:
import sys
import fake_pwd
sys.modules["pwd"] = fake_pwd
import boto3

SQLAutoCode - error when attempting to generate schema

I'm trying to auto generate a schema for use in SQLalchemy, I'm using sqlautocode to do this, I use the following command
D:~ admin$ sqlautocode mysql://'user':"pass"#xx.xx.xx.xx:3306/db_name -o tables.py
but I keep getting the following error..
Traceback (most recent call last):
File "/usr/local/bin/sqlautocode", line 9, in <module>
load_entry_point('sqlautocode==0.7', 'console_scripts', 'sqlautocode')()
File "/Library/Python/2.7/site-packages/distribute-0.6.45-py2.7.egg/pkg_resources.py", line 343, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/Library/Python/2.7/site-packages/distribute-0.6.45-py2.7.egg/pkg_resources.py", line 2354, in load_entry_point
return ep.load()
File "/Library/Python/2.7/site-packages/distribute-0.6.45-py2.7.egg/pkg_resources.py", line 2060, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/Library/Python/2.7/site-packages/sqlautocode/main.py", line 4, in <module>
from declarative import ModelFactory
File "/Library/Python/2.7/site-packages/sqlautocode/declarative.py", line 17, in <module>
from sqlalchemy.ext.declarative import _deferred_relation as _deferred_relationship
ImportError: cannot import name _deferred_relation
https://pypi.python.org/pypi/sqlautocode
Use sqlacodegen instead:
D:~ admin$ sqlacodegen mysql://'users':"pass"#xx.xx.xx.xx:3306/db_name --outfile tables.py
this is because you sqlalchemy version is above 07.
find declarative.py in C:\Python27\Lib\site-packages\sqlautocode
change from sqlalchemy.ext.declarative import _deferred_relationship To
from sqlalchemy.ext.declarative.clsregistry import _deferred_relationship
this work in my work.

Using a Django model from a mercurial python hook

I'm trying to queue up some build requests in a DB during a changegroup hook. The DB table is managed by a Django app. So, in the hook, I want to use the Django model to submit the build request. However, I'm unable to get my settings right to import the model successfully.
Based on this (https://docs.djangoproject.com/en/1.3/ref/django-admin/) info, all I need to do is add my django site to the sys path, and set the DJANGO_SETTINGS_MODULE. The django site lives in /opt/mysite, so - trying this from the python console:
>>> import sys
>>> import os
>>> sys.path.append('/opt')
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
>>> from mysite.myapp.models import Build
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/mysite/myapp/models.py", line 1, in <module>
from django.db import models
File "/usr/lib/pymodules/python2.7/django/db/__init__.py", line 78, in <module>
connection = connections[DEFAULT_DB_ALIAS]
File "/usr/lib/pymodules/python2.7/django/db/utils.py", line 93, in __getitem__
backend = load_backend(db['ENGINE'])
File "/usr/lib/pymodules/python2.7/django/db/utils.py", line 33, in load_backend
return import_module('.base', backend_name)
File "/usr/lib/pymodules/python2.7/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/lib/pymodules/python2.7/django/db/backends/mysql/base.py", line 28, in <module>
from django.db import utils
ImportError: cannot import name utils
>>>
Second Attempt:
Based on this (http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/) I can use setup_environ(), when I try this in the python shell, it works:
>>> import sys
>>> sys.path.append('/opt')
>>> from django.core.management import setup_environ
>>> from mysite import settings
>>> setup_environ(settings)
'/opt/mysite'
>>> from mysite.myapp.models import Build
>>> Build.objects.all()
[<Build: #1 F nkj sdfsdfsdfs43qg test_branch>, <Build: #2 F nkj sdfsdfsdfs43qg test_branch>, <Build: #13 Q >, <Build: #14 Q nkj_bug243>, <Build: #11 F nkj 444hwe45hedrrt nkj_bug272>, <Build: #12 F nkj sdfsdfsdfs43qg test_branch>]
However, when I try this in my Mercurial hook, I get blasted with errors the minute I try to import my Build model:
#!/usr/bin/env python
import sys
path = '/opt'
if path not in sys.path:
sys.path.append(path)
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
from mysite.myapp.models import Build
import datetime
... do stuff ...
When it gets to the 'from mysite.myapp.models import Build' line I get the following error output:
** unknown exception encountered, please report by visiting
** http://mercurial.selenic.com/wiki/BugTracker
** Python 2.7.2+ (default, Oct 4 2011, 20:06:09) [GCC 4.6.1]
** Mercurial Distributed SCM (version 1.9.1)
** Extensions loaded:
Traceback (most recent call last):
File "/usr/bin/hg", line 38, in <module>
mercurial.dispatch.run()
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 27, in run
sys.exit(dispatch(request(sys.argv[1:])))
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 64, in dispatch
return _runcatch(req)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 87, in _runcatch
return _dispatch(req)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 679, in _dispatch
cmdpats, cmdoptions)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 454, in runcommand
ret = _runcommand(ui, options, cmd, d)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 733, in _runcommand
return checkargs()
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 687, in checkargs
return cmdfunc()
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 676, in <lambda>
d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
File "/usr/lib/python2.7/dist-packages/mercurial/util.py", line 385, in check
return func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/mercurial/commands.py", line 3884, in push
newbranch=opts.get('new_branch'))
File "/usr/lib/python2.7/dist-packages/mercurial/localrepo.py", line 1428, in push
lock=lock)
File "/usr/lib/python2.7/dist-packages/mercurial/localrepo.py", line 1849, in addchangegroup
source=srctype, url=url)
File "/usr/lib/python2.7/dist-packages/mercurial/localrepo.py", line 224, in hook
return hook.hook(self.ui, self, name, throw, **args)
File "/usr/lib/python2.7/dist-packages/mercurial/hook.py", line 160, in hook
mod = extensions.loadpath(path, 'hghook.%s' % hname)
File "/usr/lib/python2.7/dist-packages/mercurial/extensions.py", line 45, in loadpath
return imp.load_source(module_name, path)
File "/opt/unapse/belvedere/mercurial_hook.py", line 14, in <module>
from unapse.belvedere.models import Build
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 109, in _demandimport
mod = _origimport(name, globals, locals)
File "/opt/unapse/belvedere/models.py", line 1, in <module>
from django.db import models
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 109, in _demandimport
mod = _origimport(name, globals, locals)
File "/usr/lib/pymodules/python2.7/django/db/__init__.py", line 14, in <module>
if not settings.DATABASES:
File "/usr/lib/pymodules/python2.7/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/usr/lib/pymodules/python2.7/django/conf/__init__.py", line 42, in _setup
self._wrapped = Settings(settings_module)
File "/usr/lib/pymodules/python2.7/django/conf/__init__.py", line 139, in __init__
logging_config_func(self.LOGGING)
File "/usr/lib/python2.7/logging/config.py", line 776, in dictConfig
dictConfigClass(config).configure()
File "/usr/lib/python2.7/logging/config.py", line 575, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure handler 'mail_admins': __import__() argument 1 must be string, not DictConfigurator
Any ideas as to what could be causing this problem?
The DictConfigurator error is a bug in python, hopefully fixed in the next 2.7 release (http://bugs.python.org/issue12718), something (probably mercurial) is overriding import and python's logging code fails in that case.
Until then here is what I did to fix it. Copy dictconfig.py from django/utils to somewhere in your python system path (I put it alongside my hook). Change the line
importer = __import__
to:
def importer(self, *args):
return __import(*args)__
And then in settings.py for your django project add to the end:
LOGGING_CONFIG = 'website.dictconfig.dictConfig'
Update website.dictconfig to whatever path you put the dictconfig file into so python can find it.
UPDATE: I think there is an even easier way. Add this to the top of your hook script, before importing anything else:
from mercurial import demandimport;
demandimport.disable()
This makes Mercurial revert the import override and seems to solve the problem cleanly.
If you're running with your environment in a virtualenv dir you'll need to add that to the site packages and I'd also suggest that you put the django dir at the front of sys.path instead of the end.
Here's the code we use to integrate our Django app into other python apps.
import os
import sys
# point this at the virtualenv dir that your django deployment runs out of
# you are using virtualenv. right?
DJANGO_ENV = '/home/core/python-envs/production'
# where your code lives (ie where settings.py is)
DJANGO_DIR = '/home/core/code/production'
# add our site packages
import site
site_packages = os.path.join(DJANGO_ENV, 'lib', 'python%s' % sys.version[:3], 'site-packages')
site.addsitedir(site_packages)
# put the main Django directory on first
sys.path.insert(0, DJANGO_DIR)
# setup the Django environment pointing to our settings
import settings
import django.core.management
django.core.management.setup_environ(settings)
# finally, import our objects
from yourapp.models import YourModel
One last thing to note is that when we import our code into some applications we've run into scoping issues and imports clashing. To get around it we wrap the work we want to do in a function so that it gets its own scope.
For example, instead of:
from yourapp.models import YourModel
objs = YourModel.objects.filter(something=True)
...
Do something like:
def do_work():
from yourapp.models import YourModel
objs = YourModel.objects.filter(something=True)
...
do_work()

django and mod_wsgi having database connection issues

I've noticed that whenever I enable the database settings on my django project (starting to notice a trend in my questions?) it gives me an internal server error. Setting the database settings to be blank makes the error go away. Here are the apache error logs that it outputs.
mod_wsgi (pid=770): Exception occurred processing WSGI script '/Users/teifionjordan/rob2/apache/django.wsgi'.
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/django/core/handlers/wsgi.py", line 239, in __call__
response = self.get_response(request)
File "/Library/Python/2.5/site-packages/django/core/handlers/base.py", line 67, in get_response
response = middleware_method(request)
File "/Library/Python/2.5/site-packages/django/contrib/sessions/middleware.py", line 9, in process_request
engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
File "/Library/Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line 2, in <module>
from django.contrib.sessions.models import Session
File "/Library/Python/2.5/site-packages/django/contrib/sessions/models.py", line 4, in <module>
from django.db import models
File "/Library/Python/2.5/site-packages/django/db/__init__.py", line 16, in <module>
backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, [''])
File "/Library/Python/2.5/site-packages/django/db/backends/mysql/base.py", line 10, in <module>
import MySQLdb as Database
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 4, in __bootstrap__
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 841, in resource_filename
self, resource_name
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 1310, in get_resource_filename
self._extract_resource(manager, self._eager_to_zip(name))
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 1332, in _extract_resource
self.egg_name, self._parts(zip_path)
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 921, in get_cache_path
self.extraction_error()
File "/Library/Python/2.5/site-packages/setuptools-0.6c9-py2.5.egg/pkg_resources.py", line 887, in extraction_error
raise err
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 20] Not a directory: '/Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp'
The Python egg cache directory is currently set to:
/Library/WebServer/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
And here is the django.wsgi file
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'rob2.settings'
sys.path.append('/Users/teifionjordan')
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
I have several other scripts that all connect to a mysql database just fine, if I run the tutorial server then it displays the admin panel correctly. I have tried changing the environ variables for eggs but still nothing changes.
You need to set the PYTHON_EGG_CACHE environment variable. Apache/mod_wsgi is trying to extract the egg into a directory that Apache doesn't have write access to....or that doesn't exist.
It's explained in the Django docs here.
Does /Library/WebServer/.python-eggs exist? What does your Apache config file look like?

Categories

Resources