Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从python http web服务器发送html字符串?_Python_Simplehttpserver - Fatal编程技术网

如何从python http web服务器发送html字符串?

如何从python http web服务器发送html字符串?,python,simplehttpserver,Python,Simplehttpserver,我从中找到了一个python http web服务器 如果目录中有一个名为index.html的文件,则该文件将用作初始文件。如果没有index.html,则会列出目录中的文件 如何修改脚本以便将自定义html发送到浏览器?正如名称和文档所暗示的那样,SimpleHTTPServer非常简单,旨在用作在标准库中的框架之上构建自己的服务器的示例代码 所以,如果你想用它做任何事情,你可能想复制和修改,或者只是把它当作灵感 如果你想做一些严肃的事情,你可能想使用一个为编写真正的HTTP服务器而设计的框

我从中找到了一个python http web服务器

如果目录中有一个名为index.html的文件,则该文件将用作初始文件。如果没有index.html,则会列出目录中的文件


如何修改脚本以便将自定义html发送到浏览器?

正如名称和文档所暗示的那样,
SimpleHTTPServer
非常简单,旨在用作在标准库中的框架之上构建自己的服务器的示例代码

所以,如果你想用它做任何事情,你可能想复制和修改,或者只是把它当作灵感

如果你想做一些严肃的事情,你可能想使用一个为编写真正的HTTP服务器而设计的框架,比如or,或者只使用一个普通的HTTP服务器,通过,比如,将动态页面委托给Python

但如果你真的想这么做,你可以。没有什么可以阻止您对
SimpleHTTPServer.SimpleHTTPRequestHandler
进行子类化并重写其方法。例如:

class MyHandler(SimpleHTTPRequestHandler):
    def send_head(self):
        if self.translate_path(self.path).endswith('/foo'):
            body = gaping_security_hole(self.path)
            self.send_response(200)
            self.send_header("Content-type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            return StringIO(body)
        else:
            return super(MyHandler, self).send_head()

显然,您可以在那里检查您想要的任何内容,而不是
endswith('/foo')
。例如,从中可以看到,默认实现会检查
os.path.isdir
,如果是真的,则会检查它是否
endswith(“/”)
,以及目录是否有名为
index.html
index.htm
的内容,然后再决定做什么。

你到底为什么要这样做?Apache和Nginx的存在是有原因的。SimpleHTTPServer是一个完整的玩具实现,它不适合任何东西,真的。@TylerEaves我想在服务器上以root用户身份执行一个命令,并将其结果显示给浏览器。使用类似Flask的最小框架。不需要服务器,只需将html转储到/tmp中的一个文件并执行一个browserI无法将其发送到init
Handler=MyHandler()TypeError:\uu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
class MyHandler(SimpleHTTPRequestHandler):
    def send_head(self):
        if self.translate_path(self.path).endswith('/foo'):
            body = gaping_security_hole(self.path)
            self.send_response(200)
            self.send_header("Content-type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            return StringIO(body)
        else:
            return super(MyHandler, self).send_head()