使用Python创建简单的http服务器


命令行 (文件传输)

只需要一行就可以创建一个文件服务器: python -m http.server 

运行后就可以在浏览器打开http://localhost:8000/访问文件。

使用Python创建简单的http服务器

如果在局域网中(ipconfig查看联网方式对应的Ipv4 address)或者服务器有公网ip,就可以通过服务器的ip地址访问文件了。

下面是一些额外选项:

  1. 1. 默认端口为8000,也可以指定端口: python -m http.server <port>

  2. 2. -d可以指定目录: python -m http.server -d /tmp

  3. 3. 可以绑定ip(通常不需要 
    python -m http.server <port> -b <ip>

实现http服务器

除了提供简单的文件服务,http.server还可以处理get和post等请求。

from http.server import  HTTPServer, BaseHTTPRequestHandler
import time

class MyHttp(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type""text/html")
        self.end_headers()

        self.wfile.write(bytes("<html><body><h1> HELLO WORLD!</h1></body></html>""utf-8"))

    def do_POST(self):
        self.send_response(200)
        self.send_header("Content-type""application/json")
        self.end_headers()

        date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        data_str = f'{{"time":"{date}"}}'
        self.wfile.write(bytes(data_str, "utf-8"))


HOST = 'ip address' # your ip v4 address 
PORT = 8888
server = HTTPServer((HOST, PORT), MyHttp)

print("server is running...")
server.serve_forever()
server.server_close()
print("server is closed!")

通过继承BaseHTTPRequestHandler并重写do_GETdo_POST方法,实现了对getpost请求的响应。运行该程序后,主机将会持续等待/响应请求。

在windows下,可以用curl命令来测试。

使用Python创建简单的http服务器

注:curl是windows命令行工具curl。
发送Get请求:curl <ip>:<port> 
发送POST请求:curl <ip>:<port> -X POST


参考:

[1]httpserver文档:https://docs.python.org/zh-cn/3/library/http.server.html
[2]视频:https://youtu.be/DeFST8tvtuI



原文始发于微信公众号(一只大鸽子):使用Python创建简单的http服务器

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/237649.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!