Search code examples
djangocherrypy

django on cherrypy: running server.py within eclipse is OK, but not in a terminal


I followed the tutorial Tango with Django to build up my Django project. And everything runs OK.

The file structure:

tango/
  rango/
  tango/
    wsgi.py
    settings.py
  manage.py

Now I am trying to deploy the project on the CherryPy server, following this tutorial. The default content of wsgi.py is as follows:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Now in the same folder as wsgi.py, I create the server.py:

from wsgi import application
import cherrypy

if __name__ == '__main__':
    # Mount the application
    cherrypy.tree.graft(application, "/")
    # Unsubscribe the default server
    cherrypy.server.unsubscribe()
    # Instantiate a new server object
    serve = cherrypy._cpserver.Server()

    # Configure the server object
    server.socket_host = "0.0.0.0"
    server.socket_port = 8080
    server.thread_pool = 30
    # Subscribe this server
    server.subscribe()
    # Start the server engine (Option 1 *and* 2)
    cherrypy.engine.start()
    cherrypy.engine.block()

My question:

If I run server.py within Eclipse (Right click server.py --> Run As --> Python Run), everything works just find. However, if I enter the command $ python server.py in a terminal, the following error messages show up:

Traceback (most recent call last):
  File "server.py", line 1, in <module>
    from wsgi import application
  File "<tangoProject>/tango/wsgi.py", line 14, in <module>
    application = get_wsgi_application()
  File "<virtualenv>/local/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
    django.setup()
  File "<virtualenv>/local/lib/python2.7/site-packages/django/__init__.py", line 20, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "<virtualenv>/local/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in __getattr__
    self._setup(name)
  File "<virtualenv>/local/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup
    self._wrapped = Settings(settings_module)
  File "<virtualenv>/local/lib/python2.7/site-packages/django/conf/__init__.py", line 98, in __init__
    % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'tango.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named tango.settings

Note, in the above I used <djangoProject> and <virtualenv> to specify the directories of the project and virtualenv, respectively.

It seemed that the server is not able to find tango/settings.py file. How do I fix it?


Solution

  • In your server.py before importing from wsgi add:

    import sys
    sys.path.append('/the/path/to/your/project')
    

    Then, the line importing from wsgi change it to:

    from tango.wsgi import application