python的web服务代码怎么写?要求能读取请求头和定义返回头的值 (不够可以加分)

2020-10-30 国际 126阅读
server端口: 8888端口
server根目录: "../http/"
如下代码是一个简单的例子,并没有限制对其他目录的访问:
#!/usr/bin/env python
import BaseHTTPServer
import os
httpPort = 8888
documentRoot = os.curdir + "../http/"
class exampleHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
try:
print self.server
print self.path
print self.client_address
print self.command
print self.request_version
print self.headers
if self.path.endswith(".html") or self.path.endswith(".htm"):
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
f = open(documentRoot + self.path)
self.wfile.write(f.read())
f.close()
else:
self.send_error(404, "%s was not supported" % self.path)
except IOError:
self.send_error(404, "%s was not found" % self.path)
def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', httpPort)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
if __name__ == '__main__':
run(handler_class = exampleHandler)
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com