简体   繁体   English

如何使用 SimpleHttpRequestHandler 运行 python

[英]How to run python with SimpleHttpRequestHandler

I'm using python3.我正在使用python3。 I want to show a one page but I got 404 not found file:我想显示一页,但找不到 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()

After testing your full code I can run it when I use self.path = "index.html" or self.path = "folder/index.html" but only if "folder/index.html" is inside folder in which I run code.测试完完整代码后,我可以在使用self.path = "index.html"self.path = "folder/index.html"时运行它,但前提是"folder/index.html"在我运行的文件夹中代码。

It can be for security reason.可能是出于安全原因。 It may not read files which are below/outside folder in which I run code because someone could use path ie.它可能无法读取我在其中运行代码的文件夹下方/外部的文件,因为有人可以使用路径,即。 ../../etc/passwd to steal passwords. ../../etc/passwd窃取密码。

As I know server Apache also restricts access to folders which are below/outside running folder.据我所知,服务器Apache还限制对运行文件夹下方/外部的文件夹的访问。
All server should restric it.所有服务器都应该限制它。

You may have to write own code which read data from file and send to browser.您可能必须编写自己的代码来从文件中读取数据并发送到浏览器。


You can get path to file with http.server to see source code您可以使用http.server获取文件路径以查看源代码

print(http.server.__file__)

maybe it helps you.也许它可以帮助你。

In source code I saw function copyfile which it uses to send file.在源代码中,我看到了copyfile复制文件,它用于发送文件。


Frankly, I would rathern use Flask to create it.坦率地说,我宁愿使用Flask来创建它。


EDIT:编辑:

After digging in source code I can see that original do_GET use translate_path() to convert path into current_folder/path which can be incorrect and it can't find file.挖掘源代码后,我可以看到原始do_GET使用translate_path()path转换为current_folder/path可能不正确并且找不到文件。

Using code from source code I create this version - it runs almost all code from original do_GET except translate_path() so I can use absolute path to display file.我使用源代码中的代码创建了这个版本——它运行几乎所有来自原始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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM