如何使用Python的BaseHTTPRequestHandler服务任何文件类型 [英] How to serve any file type with Python's BaseHTTPRequestHandler
本文介绍了如何使用Python的BaseHTTPRequestHandler服务任何文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下示例:
import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith(".html"):
f = open(curdir + sep + self.path) #self.path has /test.html
#note that this potentially makes every file on your computer readable by the internet
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
def main():
try:
server = HTTPServer(('', 80), MyHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main()
如果我还想存储一个ZIP文件怎么办...我该怎么做? 我认为这条线行不通吗?
What if I want to server a ZIP file also... how would I do that? I don't think this line would work right?
self.wfile.write(f.read())
推荐答案
将二进制文件作为参数传递给open().这个:
Pass binary as a parameter to open(). This:
f = open(curdir + sep + self.path, 'rb')
代替此:
f = open(curdir + sep + self.path)
UNIX不区分二进制和文本,而Windows区分.但是,如果脚本在UNIX上执行,则"b"将被忽略,因此您很安全.
UNIX doesn't distinguish between binary and text, but windows does. But if the script executes on UNIX, the "b" will just be ignored so you're safe.
这篇关于如何使用Python的BaseHTTPRequestHandler服务任何文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文