如何用Python3编写代码来构建一个HTTP服务器?

2026-06-10 01:226阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计282个文字,预计阅读时间需要2分钟。

如何用Python3编写代码来构建一个HTTP服务器?

在本地搭建Web服务器有多种简单方法,可以利用IIS功能。可自行搜索本机IIS搭建Web服务器,无需编写代码,直接利用Windows自带的Web服务器功能。Python2提供了BaseHTTPServer模块,Py3中已不再包含。

在本机搭建Web服务器其实也有更简单的方法,可以利用iis功能。可以自行搜索本机iis搭建Web服务器。不用写代码,Windows自带的web服务器功能。

Python2提供了BaseHTTPServer模块,不过在Py3把它合并到了http.server中。

如何用Python3编写代码来构建一个HTTP服务器?

老教材用BaseHTTPServer你可以直接用http.server代替即可。

这里利用http.server搭建最简单的web服务器:

from http.server import HTTPServer,BaseHTTPRequestHandler class Request(BaseHTTPRequestHandler): def do_GET(self): print(self.path) self.send_response(200) # 标识传递数据类型 self.send_header('Content-type','text/html') self.end_headers() self.wfile.write('这里用来传数据') # 下面的形式可以用来传html文件 # with open('D:\\Python网络编程基础\\Python代码\\http.html','rb') as t: # print('输出了') # self.wfile.write(t.read()) def run(): host='localhost' port=80 server=HTTPServer((host,port),Request) server.serve_forever() if __name__=='__main__': # print(Request.path) run()

然后可以用浏览器,访问localhost,默认的是80端口。
一般80是http,443是https,这里你也可以用别的端口。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计282个文字,预计阅读时间需要2分钟。

如何用Python3编写代码来构建一个HTTP服务器?

在本地搭建Web服务器有多种简单方法,可以利用IIS功能。可自行搜索本机IIS搭建Web服务器,无需编写代码,直接利用Windows自带的Web服务器功能。Python2提供了BaseHTTPServer模块,Py3中已不再包含。

在本机搭建Web服务器其实也有更简单的方法,可以利用iis功能。可以自行搜索本机iis搭建Web服务器。不用写代码,Windows自带的web服务器功能。

Python2提供了BaseHTTPServer模块,不过在Py3把它合并到了http.server中。

如何用Python3编写代码来构建一个HTTP服务器?

老教材用BaseHTTPServer你可以直接用http.server代替即可。

这里利用http.server搭建最简单的web服务器:

from http.server import HTTPServer,BaseHTTPRequestHandler class Request(BaseHTTPRequestHandler): def do_GET(self): print(self.path) self.send_response(200) # 标识传递数据类型 self.send_header('Content-type','text/html') self.end_headers() self.wfile.write('这里用来传数据') # 下面的形式可以用来传html文件 # with open('D:\\Python网络编程基础\\Python代码\\http.html','rb') as t: # print('输出了') # self.wfile.write(t.read()) def run(): host='localhost' port=80 server=HTTPServer((host,port),Request) server.serve_forever() if __name__=='__main__': # print(Request.path) run()

然后可以用浏览器,访问localhost,默认的是80端口。
一般80是http,443是https,这里你也可以用别的端口。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。