HttpServer Setting配置文件代码:
#HTTP SERVER配置文件
#httpserver地址
HOST=‘0.0.0.0’
PORT=8000
ADDR=(HOST,PORT)
#webframe地址
frame_ip = ‘127.0.0.1’
frame_port = 8080
frame_addr = (frame_ip,frame_port)
HttpServer.py 服务端代码:
#coding=utf-8
‘’’
name:Levi
time:2018-10-1
‘’’
from socket import *
#进程
import sys
#正则
import re
#多线程并发
from threading import Thread
#配置文件模块
from setting import *
import time
class HTTPServer(object):
def init(self, addr = (‘0.0.0.0’,80)):#httpserver默认80
self.sockfd = socket()
self.sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
self.addr = addr
self.bind(addr)
def bind(self,addr):
self.ip=addr[0]
self.port=addr[1]
self.sockfd.bind(addr)
#HTTP服务器启动
def serve_forever(self):
self.sockfd.listen(10)
print('Listen the port %d...'%self.port)
while True:
connfd,addr = self.sockfd.accept()
print('Connect from',addr)
#每当客户端进来创建一个新的线程
handle_client=Thread(target=self.handle_request,args=(connfd,))
handle_client.setDaemon(True)
handle_client.start()
def handle_request(self,connfd):
#接收浏览器请求
request = connfd.recv(4096)
# print(request)
request_lines=request.splitlines()
#获取请求行
request_line=request_lines[0].decode()
#正则提取请求方法和请求内容
pattern = r'(?P<METHOD>[A-Z]+)\s+(?P<PATH>/\S*)'
try:
env = re.match(pattern,request_line).groupdict()#捕获组的字典,名字为键值对
except:
response_headlers = "HTTP/1.1 500 Server Error\r\n"
response_headlers+='\r\n'
response_body="Server Error"
response=response_body+response_headlers
connfd.send(response.encode())
return
# print(env)#打印匹配到的字典
#将请求发给frame得到返回的数据结果
status,response_body=self.send_request(env['METHOD'],env['PATH'])
#根据响应码组织响应头的内容
response_headlers = self.get_headlers(status)
#将结果组织为http response 发送给客户端
response = response_headlers+response_body
connfd.send(response.encode())
connfd.close()
#和框架frame 交互 发送 request 获取 response
def send_request(self,method,path):
s = socket()
s.connect(frame_addr)
#向webframe发送method 和 path
s.send(method.encode())
time.sleep(0.1)
s.send(path.encode())
#等待接收webframe回发的结果
status = s.recv(128).decode()
response_body = s.recv(4096*1000).decode()
return status,response_body
def get_headlers(self,status):
if status=='200':
response_headlers = 'HTTP/1.1 200 OK\r\n'
response_headlers+='\r\n'
elif status =='404':
response_headlers = 'HTTP/1.1 400 Not Found\r\n'
response_headlers+='\r\n'
return response_headlers
if name == ‘main’:
httpd=HTTPServer(ADDR)#传过来
httpd.serve_forever()
WebFrame setting.py配置文件代码:
#WebFrame设置
frame_ip = ‘127.0.0.1’
frame_port = 8080
frame_addr = (frame_ip,frame_port)
#静态文件存储路径
STATIC_DIR=’./static’#写绝对路径更好点,请求路径后面带了斜杠
WebFrame.py代码:
#coding=utf-8
from setting import *
from socket import *
import time
from urls import *
from views import *
class Application(object):
def init(self):
self.sockfd = socket()
self.sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
self.sockfd.bind(frame_addr)
def start(self):
self.sockfd.listen(5)
while True:
connfd,addr = self.sockfd.accept()
#接收请求方法
method = connfd.recv(128).decode()
#接受请求内容
path = connfd.recv(128).decode()#防止粘包
print(method,path)
#判断请求类型
if method == 'GET':
if path == '/' or path[-5:]=='.html':
status,response_body = self.get_html(path)#静态网页
else:
status,response_body = self.get_data(path)#内容
#将结果给httpserver
connfd.send(status.encode())
time.sleep(0.1)
connfd.send(response_body.encode())
elif method == 'POST':
pass
def get_html(self,path):
if path=='/':
get_file = STATIC_DIR + '/index.html'
else:
get_file = STATIC_DIR + path
try:
f=open(get_file)
except IOError:
response = ('404','=========Sorry not found the page========')
else:
response = ('200',f.read())
finally:
return response
def get_data(self,path):
for url,handler in urls:
if path==url:
response_body = handler()
return '200',response_body
return '404','Sorry, Not found the data'
if name == ‘main’:
app = Application()
app.start() #启动框架等待request
用于直接查找数据功能的配置文件代码:
views.py代码:
from time import ctime
def show_time():
return ctime()
def say_hello():
return “Hello Python”
def say_bye():
return ‘Good bye’
urls.py代码:
#所有可以被访问的URL列表
#能够处理文件请求
from views import *
urls=[
(’/time’,show_time),
(’/hello’,say_hello),
(’/bye’,say_bye)
]