python的web服务代码怎么写?要求能读取请求头和定义返回头的值 (不够...
发布网友
发布时间:2022-04-23 01:10
我来回答
共2个回答
热心网友
时间:2022-05-10 21:02
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)
热心网友
时间:2022-05-10 22:20
用urllib2库的话,也是比较复杂的。