usar librerias como python django apache wsgi

python - librerias - ¿Cómo dejo de obtener ImportError: no se pueden importar las configuraciones ''mofin.settings'' cuando se usa django con wsgi?



como usar librerias en python (16)

(Escribí esta misma respuesta para el problema de implementación de Django en Apache / mod_wsgi. ImportError: no se pudo importar la configuración ''site.settings'' en caso de que alguien solo encuentre esta pregunta).

Esto no parece ser el problema en su caso, pero me topé con el mismo ImportError cuando utilicé la directiva WSGIPythonPath (en lugar del archivo .wsgi) para configurar sys.path . Eso funcionó bien hasta que cambié a ejecutar WSGI en modo daemon. Una vez que hace eso, debe usar el argumento python-path para la directiva WSGIDaemonProcess.

No puedo obtener wsgi para importar mi archivo de configuración para mi proyecto ''mofin''.

La lista de errores del registro de errores de apache es la siguiente

mod_wsgi (pid=4001): Exception occurred within WSGI script ''/var/www/wsgi-scripts/django.wsgi''. Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 228, in __call__ self.load_middleware() File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 31, in load_middleware for middleware_path in settings.MIDDLEWARE_CLASSES: File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__ self._import_settings() File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 59, in _import_settings self._target = Settings(settings_module) File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 94, in __init__ raise ImportError, "Could not import settings ''%s'' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) ImportError: Could not import settings ''mofin.settings'' (Is it on sys.path? Does it have syntax errors?): No module named mofin.settings

Tengo el "¡mundo de hola!" La aplicación wsgi listada aquí ( http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide ) funciona bien.

El archivo settings.py carga bien con python manage.py (runserver | shell | syncdb | test store) como lo hace la aplicación.

Aquí está mi archivo wsgi:

import os import sys sys.path.append(''/home/django/mofin/trunk'') sys.path.append(''/home/django/mofin/trunk/mofin'') print >> sys.stderr, sys.path os.environ[''DJANGO_SETTINGS_MODULE''] = ''mofin.settings'' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()

el sys.path tal como está impreso en el registro de errores es

[''/usr/lib/python25.zip'', ''/usr/lib/python2.5'', ''/usr/lib/python2.5/plat-linux2'', ''/usr/lib/python2.5/lib- tk '','' /usr/lib/python2.5/lib-dynload '','' /usr/lib/python2.5/site-packages '','' /usr/lib/python2.5/site-packages/gtk-2.0 '','' / home / django / mofin / trunk '','' / home / django / mofin / trunk / mofin '']

si abro un shell interactivo con manage.py, sys.path es

[''/ home / django / mofin / trunk / mofin'', ''/usr/lib/python25.zip'', ''/usr/lib/python2.5'', ''/usr/lib/python2.5/plat-linux2'' , ''/usr/lib/python2.5/lib-tk'', ''/usr/lib/python2.5/lib-dynload'', ''/usr/lib/python2.5/site-packages'', ''/ usr / lib / python2.5 / site-packages / gtk-2.0 '']

El archivo de configuración de mi django tiene el siguiente aspecto: # Configuración de Django para el proyecto de mofin.

DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # (''Dan xxxx'', ''[email protected]''), ) MANAGERS = ADMINS DATABASE_ENGINE = ''mysql'' # ''postgresql_psycopg2'', ''postgresql'', ''mysql'', ''sqlite3'' or ''oracle''. DATABASE_NAME = ''mofin'' # Or path to database file if using sqlite3. DATABASE_USER = ''aaaaaa'' # Not used with sqlite3. DATABASE_PASSWORD = ''bbbbbb'' # Not used with sqlite3. DATABASE_HOST = '''' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '''' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = ''Europe/London'' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = ''en-GB'' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = ''/home/django/media/'' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = ''http://mofin.mywebsite.co.uk/media/'' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = ''/admin_media/'' # Make this unique, and don''t share it with anybody. SECRET_KEY = ''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( ''django.template.loaders.filesystem.load_template_source'', ''django.template.loaders.app_directories.load_template_source'', # ''django.template.loaders.eggs.load_template_source'', ) MIDDLEWARE_CLASSES = ( ''django.middleware.common.CommonMiddleware'', ''django.contrib.sessions.middleware.SessionMiddleware'', ''django.contrib.auth.middleware.AuthenticationMiddleware'', ) ROOT_URLCONF = ''mofin.urls'' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don''t forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( ''django.contrib.auth'', ''django.contrib.contenttypes'', ''django.contrib.sessions'', ''django.contrib.sites'', ''django.contrib.admin'', ''mofin.store'' )


A primera vista, diría que el camino de Python es incorrecto, pero en comparación con el shell interactivo, se ve bien. Entonces quizás intente esto:

from django.core.management import setup_environ from mofin import settings setup_environ(settings)


Acabo de tener este error y la solución fue habilitar mi entorno virtual a través de myvenv / source / activate.


Agregue dos líneas más de código

sys.path.append(''/home/django/mofin/mofin'') sys.path.append(''/home/django/mofin/trunk/mofin/mofin'')

a su archivo wsgi debajo de la línea:

sys.path.append(''/home/django/mofin/trunk/mofin/'')


Creo que debes tener una barra inclinada hacia adelante sobre eso es lo que tengo que hacer en mi script wsgi en apache antes de cargar django.

import os import sys sys.path.append(''/home/django/mofin/trunk/'') sys.path.append(''/home/django/mofin/trunk/mofin/'') print >> sys.stderr, sys.path os.environ[''DJANGO_SETTINGS_MODULE''] = ''mofin.settings'' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()

En mi caso

import os import sys if os.uname()[1] == ''vivien'': sys.path.append(''/home/www/sitebuilder.blacknight.ie/web/'') os.environ[''DJANGO_SETTINGS_MODULE''] = ''gibo.dev_settings'' elif os.uname()[1] == ''thingy'': sys.path.append(''/home/www/sitebuilder.blacknight.ie/web/'') os.environ[''DJANGO_SETTINGS_MODULE''] = ''gibo.dev_settings'' else: sys.path.append(''/home/www/sitebuilder.blacknight.ie/web/'') os.environ[''DJANGO_SETTINGS_MODULE''] = ''gibo.settings'' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()


En mi caso, tuve una importación circular que causaba este error. Desde settings.py Importaba una función en otro módulo, y desde ese módulo estaba importando una variable de configuración. Para solucionarlo, en lugar de importar directamente desde la configuración, hice esto:

from django.conf import settings


Encontré la respuesta ... permisos de archivos. / home / django se configuró en 700. es decir, solo django puede ver los contenidos. apache se ejecuta como Apache y no puede pasar / home / django.


Esto también puede suceder si tiene una aplicación (subdirectorio al proyecto con un archivo init) nombrado con el mismo nombre que el proyecto. Su archivo settings.py puede estar en su carpeta de proyecto, pero parece que una parte del sistema django busca primero un módulo dentro del proyecto con el mismo nombre que el proyecto y cuando no puede encontrar un settings.py allí , falla con un mensaje engañoso.

-uniquename1 ---settings.py ---manage.py ---application1 -----file.py -----file2.py ---uniquename1 (problem, rename this to some other unique name) -----file.py -----file2.py

Algo más para comprobar si alguien más tiene este problema. Se aplica a Django 1.3 y probablemente a otros.


Iba a decir que puedes simplemente insertar / anexar tu directorio de proyecto a tu sys.path en tu archivo wsgi, pero si tu archivo de configuración está en

/home/django/mofin/trunk/mofin/settings.py

Entonces deberías ser bueno allí.

Is it on sys.path? Does it have syntax errors?

Eso resume bastante lo que estás buscando.

Es interesante que el error se propague sin embargo:

for middleware_path in settings.MIDDLEWARE_CLASSES:

pero tienes lo que parece ser el predeterminado exacto .

Es posible que desee comprobar a qué intérprete de python apunta wsgi. ¿Pretendes usar un virtualenv pero wsgi está mirando la instalación de tu sistema?

También puede configurar el usuario y grupo con el que wsgi se está ejecutando. Yo uso algo como:

WSGIDaemonProcess mysite.com user = skyl group = skyl processes = n threads = N python-path = / home / skyl / pinax / pinax-env2 / lib / python2.6 / site-packages


Otra causa de este problema es que no puede asignar el mismo nombre a su aplicación que a otro módulo de Python. Por ejemplo, llamé a mi site , sin darme cuenta de que ese site ya es un módulo de Python.

Puede verificar esto iniciando Python y ejecutando el import site , help(site) , y le mostrará que no está utilizando su módulo. Por supuesto, esto le da errores cuando django intenta importar site.settings que no existe.


Oye, solo agrego una respuesta adicional a este problema. Tenía exactamente el mismo problema, pero no era un permiso de archivo. Estaba agregando "ruta / a / proyecto", pero no agregando "ruta / a". Linked es la explicación de integración de Django de mod_wsgi que me mostró la respuesta.


Permítanme agregar y mi experiencia para ese tema. Después de golpear la cabeza durante unas horas e intentarlo todo con las respuestas anteriores, descubrí que pocas líneas en el archivo settings.py causan el problema:

from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^dynamicsites.fields.FolderNameField"]) add_introspection_rules([], ["^dynamicsites.fields.SubdomainListField"])

Después de eso hice una copia de settings.py, llamado scripts_settings.py sin esas líneas, y usé ese archivo y todo está bien ahora.


Posible problema:

Olvidó el archivo __init__.py, que debe estar en su proyecto y en todos los directorios que considere un módulo de Python para la importación.

Otra cosa que podría intentar es agregar la ruta directamente en el archivo manage.py, como:

import sys ... ... sys.path.insert(0, ''/home/django/mofin/trunk'')

Espero que ayude


Tuve el mismo problema pero otra solución:

Mi carpeta de proyecto fue nombrada exactamente como una de mi aplicación.

Tuve :

/ home / myApp
/home/myApp/settings.py
/home/myApp/manage.py
/home/myApp/rights.py
/ home / myApp / static /
/ home / myApp / static /
/ home / myApp / myApp /model.py
/ home / myApp / myApp /admin.py
/ home / myApp / myApp /views.py

Este tipo de árbol no parece ser posible fácilmente. Cambié el nombre de la carpeta raíz de mi proyecto y ¡el problema fue resuelto!


Tuve un problema de permisos similar, y aunque mi settings.py tenía los permisos adecuados, ¡el .pyc no lo hizo! Así que ten cuidado con esto.


Tuve un problema similar, lo resolví con el siguiente fragmento en mi pitón:

ALLDIRS = [''/var/www/MarkerDB/''] import sys import site # Remember original sys.path. prev_sys_path = list(sys.path) # Add each new site-packages directory. for directory in ALLDIRS: site.addsitedir(directory) # Reorder sys.path so new directories at the front. new_sys_path = [] for item in list(sys.path): if item not in prev_sys_path: new_sys_path.append(item) sys.path.remove(item) sys.path[:0] = new_sys_pat

Fuente: http://code.google.com/p/modwsgi/wiki/VirtualEnvironments#Application_Environments