Python中如何使用WSGIRef.util进行静态文件的处理
发布时间:2023-12-28 06:00:56
在Python中,可以使用WSGIRef.util模块来处理静态文件。WSGIRef.util模块提供了一个static_file()函数,该函数可以根据请求的URL路径返回相应的静态文件。
下面是一个使用WSGIRef.util处理静态文件的例子:
from wsgiref.simple_server import make_server
from wsgiref.util import setup_testing_defaults, static_file
def application(environ, start_response):
setup_testing_defaults(environ)
# 获取请求的路径
path = environ['PATH_INFO']
if path == '/':
# 根路径,返回 index.html 文件
response_body = static_file('index.html', '/')
status = '200 OK'
elif path.endswith('.css'):
# CSS文件
response_body = static_file(path[1:], '/static/css')
status = '200 OK'
elif path.endswith('.jpg') or path.endswith('.png'):
# 图片文件
response_body = static_file(path[1:], '/static/images')
status = '200 OK'
else:
# 未找到文件
response_body = 'File Not Found'
status = '404 Not Found'
# 设置响应头
response_headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(response_body)))]
# 发送响应
start_response(status, response_headers)
return [response_body.encode()]
# 创建服务器
with make_server('', 8000, application) as httpd:
print('Serving on port 8000...')
# 开始监听请求
httpd.serve_forever()
在上面的例子中,首先使用make_server函数创建一个简单的HTTP服务器。然后在application函数中根据请求的路径来处理静态文件。当请求的路径是根路径时,将返回index.html文件;当路径以.css结尾时,将返回/static/css目录下对应的CSS文件;当路径以.jpg或.png结尾时,将返回/static/images目录下对应的图片文件。若找不到对应的文件,则返回404 Not Found。
最后,设置响应头并发送响应。
上述例子中使用的静态文件都放在了/static目录下,你可以根据自己的实际情况修改路径和文件名。
使用以上代码启动服务器后,你可以在浏览器中访问http://localhost:8000来查看index.html文件,或者访问http://localhost:8000/static/css/style.css来查看CSS文件。
