python 2.x 模擬樁

断树绳發表於2024-11-08

用python (2.*) 寫一個簡單的模擬樁並且列印出請求頭和訊息體,便於除錯介面,看看請求頭和body是否符合要求

vi mockServer.py

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print("Headers:")
        for header, value in self.headers.items():
            print("{}: {}".format(header, value))
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write("{'code':200,'msg':'success'}".encode('utf-8'))
    def do_POST(self):
        print("Headers:")
        for header, value in self.headers.items():
            print("{}: {}".format(header, value))
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        print("body:{}".format(post_data))
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write("{'code':200,'msg':'success'}".encode('utf-8'))
def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    print('Starting httpd...')
    httpd.serve_forever()
if __name__ == '__main__':
    run()

啟動
python mockServer.py

相關文章