【问题标题】:How to run python with SimpleHttpRequestHandler如何使用 SimpleHttpRequestHandler 运行 python
【发布时间】:2021-07-25 06:59:08
【问题描述】:

我正在使用 python3。 我想显示一页,但我得到 404 not found file:

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()

【问题讨论】:

    标签: python simplehttpserver


    【解决方案1】:

    测试完您的完整代码后,我可以在使用 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()
    

    【讨论】:

    • 我想当我输入这个网址时:http://localhost:8080/test?activity=&time=&date= 我应该看到else 里面的打印。但我得到了 404 not found 页面。
    • 我通过以下方式运行我的代码:python -m SimpleHTTPServer 8080
    • 当您运行 test?activity=&time=&date= 时,它会搜索名称为 test 的文件或文件夹 - 你有吗?如果您没有,则显示404 not found page.
    • 当您运行 python -m SimpleHTTPServer 8080 时,它会运行标准类 SimpleHTTPServer - 而不是您的代码 - 所以它无法在 else 中运行代码。你应该以python your_script.py 的身份运行
    猜你喜欢
    • 2015-07-14
    • 1970-01-01
    • 2023-04-01
    • 2018-09-26
    • 2011-09-10
    • 2019-05-21
    • 2021-03-09
    • 2016-02-01
    • 1970-01-01
    相关资源
    最近更新 更多