Python3搭建http服务器 Python3搭建http服务器的实现代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python3搭建http服务器 Python3搭建http服务器的实现代码

苏大强太强了   2021-04-21 我要评论

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

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

老教材用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,这里你也可以用别的端口。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们