python3 http.server备忘

python3英文的

打印出来应该不错:
https://docs.python.org/3/library/http.server.html#module-http.server

python2.7

我的理解一个webserver需要两个东西:一个是server(用于监听的类)、一个是handler(用于处理连接的类)
python2中常用的库有两个:BaseHTTPServer、SimpleHTTPServer

  • BaseHTTPServer里面只有两个类:一个叫HTTPServer用于监听,一个BaseHTTPRequestHandler用于处理连接。有这两个类就已经够完成工作的了,通常你需要重写handler来精确的处理get、post等请求
#! -*- coding:utf-8 -*-
__author__ = ''
#!/usr/bin/python
from  BaseHTTPServer import   BaseHTTPRequestHandler,HTTPServer
class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            f=open(self.path[1:],'r') # 获取客户端输入的页面文件名称
            self.send_response(200)#如果正确返回200
            self.send_header('Content-type','text/html') #定义下处理的文件的类型
            self.end_headers()#结束处理
            self.wfile.write(f.read())#通过wfile将下载的页面传给客户
            f.close() #关闭
        except IOError:
            self.send_error(404, 'file not found: %s'%self.path)
def main():
    try:
       server=HTTPServer(('127.0.0.1',8080),MyHandler) #启动服务
       print'welcome to  the  server'
       print 'quit  jieshu'
       server.serve_forever()# 一直运行
    except KeyboardInterrupt:
        print 'shutdong  doen server'
        server.socket.close()
if  __name__=='__main__':
     main()
  • SimpleHTTPServer里面只有一个类:SimpleHTTPRequestHandler,也是一个handler,或许和它的名字一样Simple,是它存在的原因

学习资料(还没看)

  • Python 标准库 BaseHTTPServer 中文翻译

https://blog.csdn.net/cc7756789w/article/details/46911021

  • 关于 BaseHTTPServer 的介绍

https://www.cnblogs.com/yubenliu/p/5952861.html

  • 非常简单的Python HTTP服务

https://www.cnblogs.com/xuelu/p/4127112.html

posted @ 2018-05-14 17:25  Linux-top  阅读(1027)  评论(0编辑  收藏  举报