2011-08-05 9 views
6

Me encantaría poder cambiar el directorio estático webpy sin la necesidad de configurar y ejecutar nginx localmente. En este momento, parece que webpy solo creará un directorio estático si/static/exists. En mi caso, quiero usar/foo/bar/como mi directorio estático, pero no pude encontrar ninguna información relacionada con la configuración de esto (aparte de ejecutar apache o nginx localmente).Cambiar la ruta del directorio estático en webpy

Esto es solo para uso local, no para producción. ¿Algunas ideas? Gracias

Respuesta

5

Si necesita tener una diferencia de directorio para el mismo camino, entonces puede subclase web.httpserver.StaticMiddleware o escribir su propio middleware como esto (engaña StaticApp modificando PATH_INFO):

import web 
import os 
import urllib 
import posixpath 

urls = ("/.*", "hello") 
app = web.application(urls, globals()) 

class hello: 
    def GET(self): 
     return 'Hello, world!' 


class StaticMiddleware: 
    """WSGI middleware for serving static files.""" 
    def __init__(self, app, prefix='/static/', root_path='/foo/bar/'): 
     self.app = app 
     self.prefix = prefix 
     self.root_path = root_path 

    def __call__(self, environ, start_response): 
     path = environ.get('PATH_INFO', '') 
     path = self.normpath(path) 

     if path.startswith(self.prefix): 
      environ["PATH_INFO"] = os.path.join(self.root_path, web.lstrips(path, self.prefix)) 
      return web.httpserver.StaticApp(environ, start_response) 
     else: 
      return self.app(environ, start_response) 

    def normpath(self, path): 
     path2 = posixpath.normpath(urllib.unquote(path)) 
     if path.endswith("/"): 
      path2 += "/" 
     return path2 


if __name__ == "__main__": 
    wsgifunc = app.wsgifunc() 
    wsgifunc = StaticMiddleware(wsgifunc) 
    wsgifunc = web.httpserver.LogMiddleware(wsgifunc) 
    server = web.httpserver.WSGIServer(("0.0.0.0", 8080), wsgifunc) 
    print "http://%s:%d/" % ("0.0.0.0", 8080) 
    try: 
     server.start() 
    except KeyboardInterrupt: 
     server.stop() 

O puede crear un enlace simbólico llamado "estático" y señalarlo a otro directorio.

+0

Gracias! Obtengo: 'AttributeError: el objeto 'module' no tiene ningún atributo 'StaticMiddleware'' –

+0

¿Cuál es el resultado de' print web .__ version__'? Funciona con Python 2.6.1 y web.py 0.36. –

+0

Ah, estoy en 0.32. Actualicé a 0.36 y eso funciona, pero no es 100% lo que necesito. Necesito hacer un mapa/static/to/foo/static /. ¡Gracias por la ayuda! –

Cuestiones relacionadas