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

在本机搭建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,这里你也可以用别的端口。

以上是 Python3搭建http服务器的实现代码 的全部内容, 来源链接: utcz.com/z/350711.html

回到顶部