简体   繁体   中英

How to limit to specific directory access on Python simplehttpserver

Currently if I go to " http://localhost:8035/ ", I can see and have access to all the files, including root directory, client_files directory, and server_files directory(ie I have access to all files, folders, and all its subdirectories, etc).

Goal: I want to limit the file access to only the files in the client_files directory. Is there a way to do that with the current code I have?

Current Directory Structure:

在此处输入图片说明

Current Code (run_server.py - located in root directory):

from http.server import HTTPServer, SimpleHTTPRequestHandler

class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET')
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
        return super(CORSRequestHandler, self).end_headers()

def func_run_server(url, port):
    httpd = HTTPServer((url, port), CORSRequestHandler)
    httpd.serve_forever()

func_run_server('localhost', 8035)

The SimpleHTTPRequestHandler serves the directory stack below the directory from which the server is running. The simplest solution is

import os
curD = os.path.dirname(os.path.abspath(__file__))
os.chdir(os.path.join(curD, “client_files”))

before you start the server. Added bonus: you can run the script from anywhere and it won't be sensitive to the directory from which it was launched.

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