我正在使用 webpy 框架叉。我想在其中一个请求上提供静态文件。webpy框架中是否有特殊方法,或者我只需要读取并返回该文件?
4 回答
如果您正在运行开发服务器(没有 apache):
在运行 web.py 服务器的脚本的位置创建一个名为 static 的目录(也称为文件夹)。然后将您希望提供的静态文件放在静态文件夹中。
例如,URL http://localhost/static/logo.png将图像 ./static/logo.png 发送到客户端。
参考:http ://webpy.org/cookbook/staticfiles
更新。如果你真的需要提供一个静态文件,/
你可以简单地使用重定向:
#!/usr/bin/env python
import web
urls = (
'/', 'index'
)
class index:
def GET(self):
# redirect to the static file ...
raise web.seeother('/static/index.html')
app = web.application(urls, globals())
if __name__ == "__main__": app.run()
在过去的几个小时里,我一直在为此苦苦挣扎……糟糕!
找到了两个对我都有效的解决方案... 1 - 在 .htaccess 中,在 ModRewrite 行之前添加此行:
RewriteCond %{REQUEST_URI} !^/static/.*
这将确保对 /static/ 目录的请求不会被重写以转到您的 code.py 脚本。
2 - 在 code.py 中为几个目录中的每一个添加一个静态处理程序和一个 url 条目:
urls = (
'/' , 'index' ,
'/add', 'add' ,
'/(js|css|images)/(.*)', 'static',
'/one' , 'one'
)
class static:
def GET(self, media, file):
try:
f = open(media+'/'+file, 'r')
return f.read()
except:
return '' # you can send an 404 error here if you want
注意 - 我从 web.py 谷歌组偷了这个,但再也找不到该死的帖子了!
这些中的任何一个都对我有用,无论是在 web.py 的模板中,还是直接调用我放入“静态”的网页
我不建议使用 web.py 提供静态文件。您最好为此配置 apache 或 nginx。
其他答案对我不起作用。您可以先在 app.py 中加载 html 文件,甚至可以在 app.py 中编写 html。然后,您可以使索引类的 GET 方法返回静态 html。
index_html = '''<html>hello world!</html>'''
class index:
def GET(self):
return index_html