简体   繁体   中英

How to run python with SimpleHttpRequestHandler

I'm using python3. I want to show a one page but I got 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()

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.

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.

As I know server Apache also restricts access to folders which are below/outside running folder.
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

print(http.server.__file__)

maybe it helps you.

In source code I saw function copyfile which it uses to send file.


Frankly, I would rathern use Flask to create it.


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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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