Python importa MySQLdb, error interno del servidor Apache
Tengo un problema similar al descrito en ".cgi problema con el servidor web", aunque revisé y probé las soluciones sugeridas anteriormente sin éxito.
Estoy ejecutando el mismo programa en Mac OS X 10.5.8, Apache 2.2.13, usando Python 2.6.4. Puedo ejecutar con éxito el código en el shell de Python y la línea de comandos de la terminal, pero obtengo<type 'exceptions.ImportError'>: No module named MySQLdb
cuando trato de ejecutarlo en "http: //localhost/cgi-bin/test.cgi". Se ejecuta correctamente si comentoimport MySQLdb
.
#!/usr/bin/env python
import cgitb
cgitb.enable()
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
[editar] Basado en la primera respuesta:
Si modificotest.cgi
como se especifica y ejecutarlo desde la línea de comandos del terminal, el directorio deMySQLdb
se muestra ensys.path
. Sin embargo, cuando lo ejecuto a través del servidor web, aparece el mismo error. Si comentoimport MySQLdb
entest.cgi
Con el nuevo bucle for, la página no se abre.
¿Cómo configuro el PYTHONPATH de Apache? En el shell de Python, probé:
import MySQLdb
import os
print os.path.dirname(MySQLdb.__file__)
Luego, en base a otras publicaciones, intenté agregar la ruta resultante en el originaltest.cgi
:
import sys
sys.path.append('/Library/Frameworks/Python.framework/Versions/6.0.0/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.5-i386.egg/')
pero esto produjo el mismo error.
[editar]
Lamentablemente, ninguna de las soluciones funcionó. Agregar la ruta asys.path
me dio el mismo error que antes. Codificar la ruta al binario de Python#!/Library/Frameworks/Python.framework/Versions/Current/bin/python
produjo un largo error, parte del cual se muestra:
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
/Library/WebServer/CGI-Executables/test.cgi in ()
15 #sys.path.append('/Library/Frameworks/Python.framework/Versions/6.0.0/lib/python2.6/site-packages/')
16
17 import MySQLdb
18 #import _mysql
19
MySQLdb undefined
/Library/WebServer/CGI-Executables/build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py in ()
/Library/WebServer/CGI-Executables/build/bdist.macosx-10.5-i386/egg/_mysql.py in ()
/Library/WebServer/CGI-Executables/build/bdist.macosx-10.5-i386/egg/_mysql.py in __bootstrap__()
/Library/Frameworks/Python.framework/Versions/6.0.0/lib/python2.6/site-packages/pkg_resources.py in resource_filename(self=<pkg_resources.ResourceManager instance at 0x3c8a80>, package_or_requirement='_mysql', resource_name='_mysql.so')
848 """Return a true filesystem path for specified resource"""
849 return get_provider(package_or_requirement).get_resource_filename(
850 self, resource_name
851 )
852
self = <pkg_resources.ResourceManager instance at 0x3c8a80>, resource_name = '_mysql.so'
...
<class 'pkg_resources.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 13] Permission denied: '/Library/WebServer/.python-eggs' 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.
args = ("Can't extract file(s) to egg cache\n\nThe followin...nt\nvariable to point to an accessible directory.\n",)
cache_path = '/Library/WebServer/.python-eggs'
manager = <pkg_resources.ResourceManager instance at 0x3c8a80>
message = "Can't extract file(s) to egg cache\n\nThe followin...nt\nvariable to point to an accessible directory.\n"
original_error = OSError(13, 'Permission denied')
Este error parece implicar que puede tener algo que ver con la configuración de PYTHON_EGG_CACHE y / o los permisos ...
[editar] Solución:
Para probar qué versión de Python que estaba usando Apache, agregué el siguiente código:
import sys
version = sys.version
path = sys.path
...
print "<h1>%s</h1>" % version
print "<h1>%s</h1>" % path
lo que indicaba que Apache estaba utilizando Python 2.5.1 instalado por el fabricante, y no Python 2.6.4 con el módulo MySQLdb asociado. Por lo tanto, agregando el siguiente código al originaltest.cgi
solucionó el problema:
import os
os.environ['PYTHON_EGG_CACHE'] = '/tmp'
import sys
sys.path.append('/Library/Frameworks/Python.framework/Versions/6.0.0/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.5-i386.egg')
Posiblemente hay una solución sistemática al alterar el PYTHONPATH en httpd.conf de APACHE, pero aún no lo he descubierto.