【问题标题】:How to limit to specific directory access on Python simplehttpserver如何限制 Python simplehttpserver 上的特定目录访问
【发布时间】:2019-06-25 05:35:47
【问题描述】:

目前如果我转到“http://localhost:8035/”,我可以看到并可以访问所有文件,包括根目录、client_files 目录和 server_files 目录(即我可以访问所有文件、文件夹及其所有子目录等)。

目标:我想限制文件访问仅限于 client_files 目录中的文件。有没有办法用我现有的代码做到这一点?

当前目录结构:

当前代码(run_server.py - 位于根目录):

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)

【问题讨论】:

    标签: python server localhost simplehttpserver


    【解决方案1】:

    SimpleHTTPRequestHandler 为服务器运行所在目录下的目录堆栈提供服务。最简单的解决方案是

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

    在您启动服务器之前。额外的好处:您可以从任何地方运行脚本,它不会对启动它的目录敏感。

    【讨论】:

    • 它可以工作,但非常hacky。不完全是我正在寻找的答案。如果对于不同的文件夹结构类型,如果程序变得更大或者某些文件即使在 clients_file 中也希望受到限制,则会出现问题。
    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    相关资源
    最近更新 更多