美文网首页
Python Web 服务器

Python Web 服务器

作者: 可爱喵星人 | 来源:发表于2018-03-07 14:56 被阅读0次

对于web开发,Pyhon 3 提供了HTTP Server模块,这个模块提供了创建和监听Http socket,并对http 请求进行调度的一系列类。

想创建一个本地的http服务器时,又不想安装IIS等静态服务器,那么python的httpserver是一个很好的选择。

那么如何创建一个http服务器呢?

1.首先,导入对http server模块进行导入:

#server.py

import http.server

from http.server import HTTPServer

2.监听端口,运行服务

#server.py

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

httpd = HTTPServer(("", PORT), Handler)

httpd.serve_forever()

3.同级别目录创建一个 index.html文件,内容如下

python http server !

4.命令行输入:python server.py

5.打开浏览器输入:http://localhost:8000/  显示:python http server !

下面的代码同样可以实现上面的httpsever的功能

import http.server

import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:

print("serving at port", PORT)

httpd.serve_forever()

区别是处理监听和相应http响应的类不同,此处使用的是socketserver.TCPServer类。上面使用的 HTTPServer



HTTPServe 类是socketserver.TCPServer的子类

参考:

https://docs.python.org/3/library/http.server.html#module-http.server

相关文章

网友评论

      本文标题:Python Web 服务器

      本文链接:https://www.haomeiwen.com/subject/idyjfftx.html