Commits

Anonymous committed f31a571

midwork commit on static files stuff

Comments (0)

Files changed (9)

-setup.py
 include README.rst
 recursive-include django_wsgiserver *.py
 recursive-include docs *.rst
-recursive-include tests *.py testssl
+recursive-include tests *.py test_* *.html
 - setuptools/pip installable (so install right in virtualenv)
 - small memory footprint
 - by default replaces mimics the django built-in server, serves admin media by
-  default for easy testing and deployment
-- supports https/ssl  
+  default for easy testing and deployment. Will serve from STATICFILES_ROOT if it's defined.
+- supports https/ssl to make testing under https easy
 
 Planned features
 ----------------
 
 ::
 
-   pip install -e hg+https://cleemesser@bitbucket.org/cleemesser/django-cherrypy-wsgiserver#egg=django-wsgiserver
+   pip install -e hg+https://cleemesser@bitbucket.org/cleemesser/django-wsgiserver#egg=django-wsgiserver
 
 4. Alternatively you can download the code and install it so that django_wsgiserver is on your PYTHONPATH
 
 
 To do
 -----
-- looking at settings for serving static media automatically
 - I should probably just add a switch to allow use of the native cherrypy install
-- Upload to the cheeseshop/pypi at some point. Done!
 - Consider other server backends: tornado, uwsgi
+- further security tests
+- add shell command that will serve a django project in a default way without needing to alter settings.py to add to INSTALLED_APPS
+- ? add ability to printout requests like django built in runserver (cf. django-odeon)
 
 Changelog
 ---------
+- 0.7.0 added support for serving static files directory by default if
+	STATICFILES_ROOT is defined. Added more tests: ssl, staticfiles and
+	started to document them.  Experimental: STATICFILES_DIRS during
+	development to avoid needing to collect files all. Added django-odeon's
+	patch to wsgiserver to make it robust to illegal header lines
+- 0.6.9 typo fix
+- 0.6.8 Changed name of bitbucket repo to django-wsgiserver to match it's pypi name
+	
 - 0.6.7 using open().read() in setup file broke setuptools/pip install because README.rst wasn't included. Created MANIFEST.in file and now include README.rst tests/, docs/ 
 - 0.6.6 fix up cherrypy dependency in ssl that was accidently introduced in the
   move to cherrypy.wsgiserver 3.2 branch

django_wsgiserver/management/commands/runwsgiserver.py

 'ssl_private_key': None,
 'autoreload' : False,
 'adminserve' : True,  # please serve the admin media too by default
+'staticserve' : True, # serve static
+'servestaticdirs': False, # will use STATICFILES_DIRS and actuall serve each directory so
+                          # you don't need to collect them all in development
 }
 
 
             gid = default_grp
     return (uid, gid)
     
-    
 def poll_process(pid):
     """
     Poll for process with given pid up to 10 times waiting .25 seconds in between each poll. 
     except KeyboardInterrupt:
         server.stop()
 
-
+def process_staticfiles_dirs(staticfiles_dirs):
+    staticlocations=[]
+    for staticdir in staticfiles_dirs:
+        if isinstance(staticdir, (list, tuple)):
+            prefix, root = root
+        else:
+            prefix = ''
+        staticlocations.append((prefix, root))
+    return staticlocations
 
 
 def start_server_servestatic(options):
     from django.core.handlers.wsgi import WSGIHandler
     from django.conf import settings
     app = WSGIHandler()
+    path = { '/': app}
     if options['adminserve']: # serve the admin media too
         # AdminMediaHandler is middleware for local use
-        import django.core.servers.basehttp
-        app = django.core.servers.basehttp.AdminMediaHandler(app)
-    # another way to serve the admin media three application
-    path = { '/': app,
-             settings.MEDIA_URL: mediahandler.MediaHandler(settings.MEDIA_ROOT),
-             settings.ADMIN_MEDIA_PREFIX: mediahandler.MediaHandler(
-                 os.path.join( django.contrib.admin.__path__[0],
-                               'media' )
-                 )
-             }
+        #import django.core.servers.basehttp
+        #adminapp = django.core.servers.basehttp.AdminMediaHandler(app)
+        # another way to serve the admin media three application
+        import django.contrib.admin
+        path[settings.ADMIN_MEDIA_PREFIX] = mediahandler.MediaHandler(        
+            os.path.join( django.contrib.admin.__path__[0], 'media'))
+
+
+    if options['staticserve']:
+        try:
+            path[settings.STATICFILES_URL] = mediahandler.MediaHandler(settings.STATICFILES_ROOT)        
+        except AttributeError, msg:
+            print msg
+            print "****"
+            print "STATICFILES_URL and STATICFILES_ROOT  must be set in settings file"
+            print "****"
+            raise
+
+        try:
+            staticserverapp = mediahandler.MediaHandler(settings.STATICFILES_ROOT)
+            path[settings.STATICFILES_URL] = staticserverapp
+        except AttributeError, msg:
+            print msg
+            print "****"
+            print "STATICFILES_ROOT and STATICFILES_URL are not set in settings file"
+            print "Continuing anyway..."
+            print "****"
+                 
+        if options['servestaticdirs'] and settings.__dict__.has_key('STATICFILES_DIRS'):
+            staticlocations = process_staticfiles_dirs(settings.STATICFILES_DIRS)
+            # print staticlocations
+            for urlprefix, root in staticlocations:
+                path[os.path.join(settings.STATICFILES_URL, urlprefix)] =  mediahandler.MediaHandler(root)
+                 
     dispatcher =  WSGIPathInfoDispatcher( path )
         
     server = CherryPyWSGIServer(
 # modified version no cherrypy reliance
 setup(
     name="django-wsgiserver",
-    version="0.6.8",
+    version="0.7.0",
     license="BSD",
     description="""django-wsgiserver installs a web server for Django using CherryPy's WSGI server.""",
     author="""Peter Baumgartner Chris Lee-Messer the authors of CherryPy""",
     maintainer="Chris Lee-Messer",
     # from README.rst
     long_description=open('README.rst').read(),
-    url="http://bitbucket.org/cleemesser/django-cherrypy-wsgiserver/downloads",
-    download_url="http://bitbucket.org/cleemesser/django-cherrypy-wsgiserver/downloads",
+    url="http://bitbucket.org/cleemesser/django-wsgiserver/downloads",
+    download_url="http://bitbucket.org/cleemesser/django-wsgiserver/downloads",
     packages=[
         "django_wsgiserver",
         "django_wsgiserver.management",

tests/testdjangoproject/settings.py

 # to test django-cherrypy-wsgiserver
 # add django_wsgiserver to the PYTHONPATH
 import sys, os
-settingsdir = os.path.dirname(__file__)
-sys.path.append(os.path.join(settingsdir,"../..")) 
+PROJECT_ROOT = os.path.dirname(__file__)
+# add django_wsgiserver to python path
+sys.path.append(os.path.join(PROJECT_ROOT,"../.."))  
 
 DEBUG = True
 TEMPLATE_DEBUG = DEBUG
 
 # Absolute path to the directory that holds media.
 # Example: "/home/media/media.lawrence.com/"
-MEDIA_ROOT = ''
+MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'sitemedia')
 
 # 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 = ''
+MEDIA_URL = '/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 = '/media/'
+ADMIN_MEDIA_PREFIX = '/media/admin/'
 
 # Make this unique, and don't share it with anybody.
 SECRET_KEY = 'v+ryc^&*s9%9h=r$72%c59h3jgq+u(n^*es6fz02xb4naj+cbt'
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
+    'debug_toolbar.middleware.DebugToolbarMiddleware',
 )
 
 ROOT_URLCONF = 'testdjangoproject.urls'
     # 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.
+    os.path.join(PROJECT_ROOT, 'templates'),
 )
 
 INSTALLED_APPS = (
     'django_wsgiserver',
     # Uncomment the next line to enable the admin:
     'django.contrib.admin',
+    'debug_toolbar',
+)
 
-)
+INTERNAL_IPS = ('localhost',
+                '127.0.0.1',
+                )

tests/testdjangoproject/test_ssl

+#!/bin/sh
+python manage.py runwsgiserver ssl_certificate=`pwd`/testserver.crt ssl_private_key=`pwd`/testserver.key port=8443

tests/testdjangoproject/testssl

-#!/bin/sh
-python manage.py runwsgiserver ssl_certificate=`pwd`/testserver.crt ssl_private_key=`pwd`/testserver.key port=8443

tests/testdjangoproject/urls.py

     # Uncomment the next line to enable the admin:
     (r'^admin/', include(admin.site.urls)),
     #default                       
-    (r'', 'views.hello'),                                              
+    (r'^$', 'views.hello'),                                              
 )
 
 
-from django.contrib.staticfiles.urls import staticfiles_urlpatterns
-print "staticfiles_urlpatterns():", staticfiles_urlpatterns()

tests/testdjangoproject/views.py

+from django.conf import settings
 from django.http import HttpResponse, HttpResponseRedirect
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+import pprint
 
 def hello(request):
-    return HttpResponse(
-        """<html><head><title>django-wsgiserver</title></head>
-        <body><h2>hello django-wsgiserver</h2>
-        <h3>Tests</h3>
-        <ul>
-        <li> <a href="/admin/">Check the default admin css media service</a></li>
-        </ul>
-        </body></html>""")
+    data = {}
+    
+    data['HAS_STATICFILES_ROOT'] = False
+    try:
+        if settings.STATICFILES_ROOT:
+            data['HAS_STATICFILES_ROOT'] = True
+            print "see the STATICFILES_ROOT:", settings.STATICFILES_ROOT
+    except:
+        data['HAS_STATICFILES_ROOT'] = False
+        pass
 
+    c = RequestContext(request, data)
+    return render_to_response("hello.html", context_instance=c)
+
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.