如何在Python中使用HTTPServer()处理GET和POST请求
在Python中,可以使用BaseHTTPServer模块来创建一个简单的HTTP服务端。下面是一个使用HTTPServer处理GET和POST请求的示例。
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<h1>Hello World!</h1>')
else:
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<h1>Page not found!</h1>')
def do_POST(self):
if self.path == '/submit':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST'})
name = form.getvalue('name')
self.wfile.write('<h1>Hello {}!</h1>'.format(name))
else:
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<h1>Page not found!</h1>')
def main():
try:
server = HTTPServer(('', 8080), RequestHandler)
print('Started HTTP server on port 8080')
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down the server')
server.socket.close()
if __name__ == '__main__':
main()
解析上述示例代码:
1. 首先,我们导入BaseHTTPRequestHandler和HTTPServer模块。
2. 然后,我们编写一个自定义的RequestHandler类继承自BaseHTTPRequestHandler,并重写其中的do_GET和do_POST方法。这两个方法分别用于处理GET和POST请求。
- 在do_GET方法中,我们检查请求的路径,如果为根路径/,则返回Hello World!消息,否则返回Page not found!消息。
- 在do_POST方法中,我们首先检查请求的路径,如果为/submit,则处理表单数据并返回欢迎消息,否则返回Page not found!消息。
3. 在main函数中,我们创建一个HTTPServer实例,指定监听的IP地址和端口号,并将RequestHandler类作为处理器传入。
4. 最后,我们开始监听并等待客户端的连接请求,直到接收到KeyboardInterrupt异常(即用户按下 Ctrl+C 键),此时关闭服务器。
使用时,将上述代码保存为一个.py文件,并在命令行中执行python filename.py启动HTTP服务器。服务器将监听http://localhost:8080/端口。通过浏览器访问http://localhost:8080/将显示Hello World!消息。通过浏览器向http://localhost:8080/submit发送POST请求,并传递一个名为name的表单字段,服务器将返回一个欢迎消息,如<h1>Hello John!</h1>。
这是一个简单的例子,仅用于演示如何使用HTTPServer处理GET和POST请求。在实际应用中,可以根据需要进一步扩展和修改RequestHandler类,以实现自定义的处理逻辑。
