浏览器配套

from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
from urllib.parse import urlparse

# 保存结果
filename = r'res1.txt'

"""

var data = new FormData();

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "http://127.0.0.1:8000/www.baidu.com");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Pragma", "no-cache");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("no-cache", "1");

xhr.send(data);

"""


class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        self._set_response()
        if self.path == '/res1.txt':
            fin = open("res1.txt")
            content = fin.read()
            fin.close()
            self.wfile.write("{}".format(str(content)).encode('utf-8'))
            return
        if self.path == '/':
            self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))
        else:
            self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))

            # 写入数据
            with open(filename, 'a+') as f:
                f.write(urlparse(self.path[1:]).netloc + '\n')



def do_POST(self):
    content_length = int(self.headers['Content-Length'])  # <--- Gets the size of data
    post_data = self.rfile.read(content_length)  # <--- Gets the data itself
    logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
                 str(self.path), str(self.headers), post_data.decode('utf-8'))

    self._set_response()
    self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))


def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')


if __name__ == '__main__':
    run(port=int(8081))
上一篇:cookie,cookie的封装,cookie的删除,同步和异步,Ajax,Ajax的编写步骤


下一篇:2021-03-18