【问题标题】:How to change the default folder "static" in web.py如何更改 web.py 中的默认文件夹“静态”
【发布时间】:2017-09-13 23:38:19
【问题描述】:

我的项目中的一个库需要一个包含应用程序根目录中名为“主题”的 CSS 文件的文件夹。 web.py 默认情况下,使用文件夹“static”返回静态文件并重命名她...不是我在网上找到的解决方案之一如下

在urls中需要添加一行

'/(?:img|js|css)/.*',  'app.controllers.public.public',

app.controllers.public

需要下一个代码

class public:
    def GET(self): 
        public_dir = 'themes'
        try:
            file_name = web.ctx.path.split('/')[-1]
            web.header('Content-type', mime_type(file_name))
            return open(public_dir + web.ctx.path, 'rb').read()
        except IOError:
            raise web.notfound()

def mime_type(filename):
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream' 

但是这个解决方案不起作用,文件仍然从静态中提取...

是否有简单明了的解决方案?也许我们应该更改 web.py 中文件夹的名称?

【问题讨论】:

    标签: python python-2.7 web.py


    【解决方案1】:

    没有简单的方法可以更改 web.py 对/static/ 的使用,但有一种非常简单的方法可以添加您自己的,无需在urls 列表中添加任何内容。

    查看 web.py 的代码,你会发现 web.httpserver.StaticMiddleware 是定义它的地方。你的工作是用新的前缀创建另一个 WSGI 中间件。然后,因为这是 WSGI 中间件,所以将你的新类添加到运行链中。

    from web.httpserver import StaticMiddleware
    
    if __name__ == '__main__':
        app = web.application(urls, globals())
        app.run(lambda app: StaticMiddleware(app, '/themes/')
    

    如果这对您来说过于简洁,请考虑这与显式创建新子类并将该子类传递给 app.run() 相同:

    from web.httpserver import StaticMiddleware
    
    class MyStaticMiddleware(StaticMiddleware):
        def __init__(self, app, prefix='/themes/'):
            StaticMiddleware.__init__(self, app, prefix)
    
    if __name__ == '__main__':
        app = web.application(urls, globals())
        app.run(MyStaticMiddleware)
    

    请注意,'/static/' 仍然可以工作,从 /static/ 子目录加载文件:您所做的只是添加 另一个 处理器,它做同样的事情,但来自 ' /themes/' 子目录。

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2016-03-28
      • 2021-10-23
      • 2010-09-08
      • 2017-11-05
      • 2023-04-09
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      相关资源
      最近更新 更多