python - 如何使用 SimpleHttpRequestHandler 运行 python

标签 python simplehttpserver

我使用的是python3。 我想显示一页,但我收到 404 未找到文件:

import pymysql.cursors
import http.server
import socketserver
from furl import furl



class MyServer(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        print("jkjhjkhk") #printed
        print(self.path)
        if self.path == '/':
            self.path = './desktop/formdailyactivities/index.html'
        else:
            self.send_response(200)
            print (self.path)
            f = furl(self.path)
            
            # activity = f.args["activity"]
            # time = f.args["time"]
            # date = f.args["date"]

            # print(activity)
            # print(time)
            # print(date)

            
           # s1.insert(activity, time, date)
        return http.server.SimpleHTTPRequestHandler.do_GET(self)


handler_object = MyServer

PORT = 8080
my_server = socketserver.TCPServer(("",PORT), handler_object)
my_server.serve_forever()

最佳答案

测试完整代码后,我可以在使用 self.path = "index.html"self.path = "folder/index.html" 时运行它但前提是 "folder/index.html" 位于我运行代码的文件夹内。

这可能是出于安全原因。它可能无法读取我运行代码的文件夹下面/外部的文件,因为有人可以使用路径即。 ../../etc/passwd 窃取密码。

据我所知,服务器 Apache 还限制对运行文件夹下方/外部的文件夹的访问。
所有服务器都应该限制它。

您可能需要编写自己的代码来从文件读取数据并将其发送到浏览器。


您可以使用http.server获取文件路径来查看源代码

print(http.server.__file__)

也许对你有帮助。

在源代码中我看到了它用来发送文件的函数copyfile


坦白说,我宁愿使用 Flask 来创建它。


编辑:

深入研究源代码后,我可以看到原始的 do_GET 使用 translate_path()path 转换为 current_folder/path 这可能不正确并且找不到文件。

使用源代码中的代码我创建了这个版本 - 它运行原始 do_GET 中的几乎所有代码(除了 translate_path()),因此我可以使用绝对路径来显示文件。

import http.server
import socketserver
import os

#print('source code for "http.server":', http.server.__file__)

class MyServer(http.server.SimpleHTTPRequestHandler):
    
    def do_GET(self):

        print(self.path)
        
        if self.path == '/':
            #self.path = '/home/furas/test/index.html'
            self.path = './desktop/formdailyactivities/index.html'
            
            print('original  :', self.path)
            print('translated:', self.translate_path(self.path))
            
            try:
                f = open(self.path, 'rb')
            except OSError:
                self.send_error(HTTPStatus.NOT_FOUND, "File not found")
                return None

            ctype = self.guess_type(self.path)
            fs = os.fstat(f.fileno())
            
            self.send_response(200)
            self.send_header("Content-type", ctype)
            self.send_header("Content-Length", str(fs[6]))
            self.send_header("Last-Modified",
                self.date_time_string(fs.st_mtime))
            self.end_headers()            
            
            try:
                self.copyfile(f, self.wfile)
            finally:
                f.close()
                
        else:
            # run normal code
            print('original  :', self.path)
            print('translated:', self.translate_path(self.path))
            super().do_GET()
    
# --- main ---

handler_object = MyServer

PORT = 8080

print(f'Starting: http://localhost:{PORT}')

try:
    socketserver.TCPServer.allow_reuse_address = True  # solution for `OSError: [Errno 98] Address already in use`
    my_server = socketserver.TCPServer(("", PORT), handler_object)
    my_server.serve_forever()
except KeyboardInterrupt:
    # solution for `OSError: [Errno 98] Address already in use - when stoped by Ctr+C
    print('Stoped by "Ctrl+C"')
finally:
    # solution for `OSError: [Errno 98] Address already in use
    print('Closing')
    my_server.server_close()

关于python - 如何使用 SimpleHttpRequestHandler 运行 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67359204/

相关文章:

python - 在Python中对字典的字母数字键进行排序

python - 无法使用 Twine 上传到 PyPi

python - 如何在 Windows 10 上启动 python simpleHTTPServer

python - 在后台启动简单的 python Web 服务器并继续执行脚本

C 线程 Http 服务器错误

在线程中启动的 Python 的 SimpleHTTPServer 不会关闭端口

python - 随机数网格 4 x 6 Python 3

python - Hadoop 集群 - 在运行作业之前,我是否需要在所有机器上复制我的代码?

python - 在 OSX 10.11 上编译支持 SSL 的 Python 2.7.10

python - 如何在 Python 中将请求重定向到不同的 URL