【问题标题】:Changing the static directory path in webpy更改 webpy 中的静态目录路径
【发布时间】:2011-10-21 01:51:52
【问题描述】:

我希望能够更改 webpy 静态目录,而无需在本地设置和运行 nginx。现在,似乎 webpy 只会在 /static/ 存在的情况下创建一个静态目录。就我而言,我想使用 /foo/bar/ 作为我的静态目录,但找不到任何与配置相关的信息(除了在本地运行 apache 或 nginx)。

这仅供本地使用,不用于生产。有任何想法吗?谢谢

【问题讨论】:

    标签: python web.py


    【解决方案1】:

    如果您需要为同一路径设置不同的目录,那么您可以继承 web.httpserver.StaticMiddleware 或编写自己的中间件(它通过修改 PATH_INFO 来欺骗 StaticApp):

    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()
    

    或者您可以创建名为“static”的符号链接并将其指向另一个目录。

    【讨论】:

    • 谢谢!我得到:AttributeError: 'module' object has no attribute 'StaticMiddleware'
    • print web.__version__ 的输出是什么?它适用于 Python 2.6.1 和 web.py 0.36。
    • 啊,我在 0.32。我升级到 0.36 并且可以工作,但不是 100% 我需要的。我需要将 /static/ 映射到 /foo/static/。感谢您的帮助!
    • 查看httpserver.py的来源,静态中间件在StaticMiddlewareStaticApp(SimpleHTTPRequestHandler)类中实现。您可以创建自己的具有目录设置的中间件。
    • 我用StaticMiddleware 更新了我的示例,它具有两种设置,尽管将environ["PATH_INFO"]/static/... 更改为/foo/bar/... 有点棘手。
    猜你喜欢
    • 1970-01-01
    • 2019-08-30
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2019-09-30
    • 1970-01-01
    相关资源
    最近更新 更多