Python教程

python HTTP后台响应服务

本文主要是介绍python HTTP后台响应服务,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

from socket import *
from threading import *
import sys
import traceback
from threading import *

class HTTPSever(object):
def init(self,server_addr,static_dir):
# 增加服务器属性对象
self.server_address=server_addr
self.static_dir=static_dir
self.ip=server_addr[0]
self.port=server_addr[1]
self.create_socket()
# 创建套接字
def create_socket(self):
self.s=socket()
self.s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
self.s.bind(self.server_address)
def serve_forever(self):

    self.s.listen(3)
    print('监听端口',self.port)
    while True:
        try:

            c,addr=self.s.accept()
        except KeyboardInterrupt:
            self.s.close()
            sys.exit('服务器退出')
        except Exception:
            traceback.print_exc()
            continue
        # 创建新的线程处理请求
        clientThread=Thread(target=self.handlerRequest,args=(c,))
        clientThread.setDaemon(True)
        clientThread.start()
def get_html(self,c,getRequest):
    print()
    if getRequest=="/":
        filename=self.static_dir+'/1.html'
    else:
        filename=self.static_dir+getRequest
    try:
        print(filename)
        f=open(filename)
    except IOError:
        re='HTTP/1.1    404  not  found\r\n'
        re+='\r\n'
        re+='*****************************'
    else:
        re='HTTP/1.1   200  not  found\r\n'
        re+='\r\n'
        re+=f.read()
    finally:
        c.send(re.encode())
def get_data(self,c,getRequest):
    urls=['/time','/python','/edu']
    if getRequest in urls:
        re='HTTP/1.1   200  ok\r\n'
        re+='\r\n'
        if getRequest =='/time':
            re+='time'
        elif getRequest=='/edu':
            re+='edu'
        elif getRequest=='/python':
            re+='python'
    else:
        re='HTTP/1.1   404  not  found\r\n'
        re+='\r\n'
        re+='*****************************'
    c.send(re.encode())
def handlerRequest(self,c):
    # 接收客户端请求
    request=c.recv(4096) 
    requestHeader=request.splitlines()
    print(requestHeader[0])
    # 获取具体内容
    getRequest=str(requestHeader[0]).split(' ')[1]
    if getRequest=='/' or getRequest[-5:]=='.html':
        self.get_html(c,getRequest)
    else:
        self.get_data(c,getRequest)
    c.close()

if name==“main”:
# 生成对象
server_addr=(’’,8000)
static_dir=’./static’
httpd=HTTPSever(server_addr,static_dir)
# 启动服务器
httpd.serve_forever()
main()

这篇关于python HTTP后台响应服务的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!