利用python的http.server定制自己的页面和响应

python http.server简介

python http.server是一个简单的基础的httpserver,默认查找网站根目录的index.html文件,如果没有index.html文件,则放回网站根目录文件视图
这里我们想对http.server进行修改,实现我们特定的需求,如果只变化html确实能展现不能的静态页面,但是没有办法进行交互,如果我们需要获取一些服务器的内容还是比较困难的
所以需要重新定制http.server,然后再结合html实现不同的功能,毕竟html只能是前端语言,只能再浏览器客户端运行

定制sever.py

还是再http.server 模块的基础上,只是最后的运行方式变成python server.py

from http.server import HTTPServer, BaseHTTPRequestHandler
import os
import urllib
from http import HTTPStatus

# ip, port config
host = ('192.168.0.108', 8888)


class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        print(self.path)
        if self.path == '/':
            self.send_response(200)
            self.end_headers()
            f = open("index.html", 'r')
            content = f.read()
            content = content.replace(
                '</body>', self.get_directory('.') + '</body>')
            # 里面需要传入二进制数据,用encode()函数转换为二进制数据
            self.wfile.write(content.encode())
        else:
            try:
                path = urllib.parse.unquote(self.path[1:])
                f = open(path, 'rb')
                self.send_response(200)
                self.end_headers()
                self.wfile.write(f.read())
            except FileNotFoundError:
                self.send_response(404)
                self.end_headers()
                self.wfile.write(b'<h1>File Not Found</h1>')

    def do_POST(self):
        self.send_response(200)
        self.end_headers()

        self.parse_query()
        remainbytes = int(self.headers['content-length'])

        fileName = self.queries['fileName'][0]
        if not fileName:
            print("fail to find fn")
            return (False, "Can't find out file name...")

        print(fileName)
        try:
            out = open(fileName, 'wb')
        except IOError:
            return (False, "Can't create file to write, do you have permission to write?")

        out.write(self.rfile.read(remainbytes))
        print('finish')
        out.close()

    def parse_query(self):
        self.queryString = urllib.parse.unquote(self.path.split('?', 1)[1])
        self.queries = urllib.parse.parse_qs(self.queryString)
        print(self.queries)

    def get_directory(self, path) -> str:
        try:
            list = os.listdir(path)
        except OSError:
            self.send_error(
                HTTPStatus.NOT_FOUND,
                "No permission to list directory")
            return None
        list.sort(key=lambda a: a.lower())
        r = []
        displaypath = os.path.abspath(path)
        title = 'Directory listing for %s' % displaypath
        r.append('<h1>%s</h1>' % title)

        for name in list:
            fullname = os.path.join(path, name)
            displayname = linkname = name
            # Append / for directories or @ for symbolic links
            if os.path.isdir(fullname):
                displayname = name + "/"
                linkname = name + "/"
            if os.path.islink(fullname):
                displayname = name + "@"
                # Note: a link to a directory displays with @ and links with /
            r.append('<li><a href="%s">%s</a></li>' % (linkname, displayname))
        # print(''.join(r))
        return ''.join(r)


if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()


再此基础上进行调整,首先post不需要了,我们只要处理get 部分,把index.html换掉,再添加几个get的事件关联跳转连接,
前端的静态页面我们使用了docsify的模板,可以实现markdwon转html的实时转换和展示,主要有封面和index.html和侧边栏组成,都是自动识别扫描文件的,和路径无关,

posted @ 2024-03-04 14:13  学不会xuebuhui  阅读(744)  评论(0编辑  收藏  举报
Language: javascript