mini_web框架

小型的服务器:

import socket
import re
import multiprocessing
import time
# import dynamic.mini_frame
import sys


class WSGIServer(object):
def __init__(self, port, app, static_path):
# 1. 创建套接字
self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# 2. 绑定
self.tcp_server_socket.bind(("", port))

# 3. 变为监听套接字
self.tcp_server_socket.listen(128)

self.application = app
self.static_path = static_path

def service_client(self, new_socket):
"""为这个客户端返回数据"""

# 1. 接收浏览器发送过来的请求 ,即http请求
# GET / HTTP/1.1
# .....
request = new_socket.recv(1024).decode("utf-8")
# print(">>>"*50)
# print(request)

request_lines = request.splitlines()
print("")
print(">" * 20)
print(request_lines)

# GET /index.html HTTP/1.1
# get post put del
file_name = ""
ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
if ret:
file_name = ret.group(1)
# print("*"*50, file_name)
if file_name == "/":
file_name = "/index.html"

# 2. 返回http格式的数据,给浏览器
# 2.1 如果请求的资源不是以.py结尾,那么就认为是静态资源(html/css/js/png,jpg等)
if not file_name.endswith(".html"):
try:
f = open(self.static_path + file_name, "rb")
except:
response = "HTTP/1.1 404 NOT FOUND\r\n"
response += "\r\n"
response += "------file not found-----"
new_socket.send(response.encode("utf-8"))
else:
html_content = f.read()
f.close()
# 2.1 准备发送给浏览器的数据---header
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
# 2.2 准备发送给浏览器的数据---boy
# response += "hahahhah"

# 将response header发送给浏览器
new_socket.send(response.encode("utf-8"))
# 将response ic.mini_frame.applicationbody发送给浏览器
new_socket.send(html_content)
else:
# 2.2 如果是以.py结尾,那么就认为是动态资源的请求

env = dict() # 这个字典中存放的是web服务器要传递给 web框架的数据信息
env['PATH_INFO'] = file_name
# {"PATH_INFO": "/index.py"}
# body = dynamic.mini_frame.application(env, self.set_response_header)
body = self.application(env, self.set_response_header)

header = "HTTP/1.1 %s\r\n" % self.status

for temp in self.headers:
header += "%s:%s\r\n" % (temp[0], temp[1])

header += "\r\n"

response = header + body
# 发送response给浏览器
new_socket.send(response.encode("utf-8"))

# 关闭套接
new_socket.close()

def set_response_header(self, status, headers):
self.status = status
self.headers = [("server", "mini_web v8.8")]
self.headers += headers

def run_forever(self):
"""用来完成整体的控制"""

while True:
# 4. 等待新客户端的链接
new_socket, client_addr = self.tcp_server_socket.accept()

# 5. 为这个客户端服务
p = multiprocessing.Process(target=self.service_client, args=(new_socket,))
p.start()

new_socket.close()

# 关闭监听套接字
self.tcp_server_socket.close()


def main():
"""控制整体,创建一个web 服务器对象,然后调用这个对象的run_forever方法运行"""
if len(sys.argv) == 3:
try:
port = int(sys.argv[1]) # 7890
frame_app_name = sys.argv[2] # mini_frame:application
except Exception as ret:
print("端口输入错误。。。。。")
return
else:
print("请按照以下方式运行:")
print("python3 xxxx.py 7890 mini_frame:application")
return

# mini_frame:application
ret = re.match(r"([^:]+):(.*)", frame_app_name)
if ret:
frame_name = ret.group(1) # mini_frame
app_name = ret.group(2) # application
else:
print("请按照以下方式运行:")
print("python3 xxxx.py 7890 mini_frame:application")
return

with open("./web_server.conf") as f:
conf_info = eval(f.read())

# 此时 conf_info是一个字典里面的数据为:
# {
# "static_path":"./static",
# "dynamic_path":"./dynamic"
# }


sys.path.append(conf_info['dynamic_path'])

# import frame_name --->找frame_name.py
frame = __import__(frame_name) # 返回值标记这 导入的这个模板
app = getattr(frame, app_name) # 此时app就指向了 dynamic/mini_frame模块中的application这个函数

# print(app)

wsgi_server = WSGIServer(port, app, conf_info['static_path'])
wsgi_server.run_forever()


if __name__ == "__main__":
main()

小型的框架:

import re
from pymysql import connect


URL_FUNC_DICT = dict()

def route_num(url):
def set_func(func):
URL_FUNC_DICT[url] = func
def call_func(*args,**kwargs):
return func(*args,**kwargs)
return call_func
return set_func


@route_num("/index.html")
def index():
with open("./templates/index.html") as f:
content = f.read()

# my_stock_info = "哈哈哈哈 这是你的本月名称....."
#
# content = re.sub(r"\{%content%\}", my_stock_info, content)
# 创建Connection连接
conn = connect(
host='localhost',
port=3306,
database='stock_db',
user='root',
password='mysql',
charset='utf8'
)
# 获得Cursor对象
cs = conn.cursor()
cs.execute("select * from info")
my_stock_info = cs.fetchall()
# content = re.sub(r"\{%content%\}", str(my_stock_info), content)
conn.commit()
cs.close()
conn.close()

tr_template = """<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>
<input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007">
</td>
</tr>
"""
html = ""
for stock_info in my_stock_info:
html += tr_template % (stock_info[0],stock_info[1],
stock_info[2],stock_info[3],
stock_info[4],stock_info[5],
stock_info[6],stock_info[7])
content = re.sub(r"\{%content%\}", html, content)

return content

@route_num("/center.html")
def center():
with open("./templates/center.html") as f:
content = f.read()

my_stock_info = "这里是从mysql查询出来的数据。。。"

# content = re.sub(r"\{%content%\}", my_stock_info, content)
# 创建Connection连接
conn = connect(
host='localhost',
port=3306,
database='stock_db',
user='root',
password='mysql',
charset='utf8'
)
# 获得Cursor对象
cs = conn.cursor()
cs.execute("select * from v_stock_info")
my_stock_info = cs.fetchall()
# content = re.sub(r"\{%content%\}", str(my_stock_info), content)
conn.commit()
cs.close()
conn.close()
tr_template = """
<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>
<a type="button" class="btn btn-default btn-xs" href="/update/300268.html">
<span class="glyphicon glyphicon-star" aria-hidden="true"></span> 修改 </a>
</td>
<td>
<input type="button" value="删除" id="toDel" name="toDel" systemidvaule="300268">
</td>
</tr>
"""
html = ""
for stock_info in my_stock_info:
html += tr_template % (stock_info[0],stock_info[1],
stock_info[2],stock_info[3],
stock_info[4],stock_info[5],
stock_info[6])
content = re.sub(r"\{%content%\}", html, content)


return content


def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])

file_name = env['PATH_INFO']
# file_name = "/index.py"
"""
if file_name == "/index.html":
return index()
elif file_name == "/center.html":
return center()
else:
return 'Hello World! 我爱你中国....'
"""
try:
return URL_FUNC_DICT[file_name]()
# func = URL_FUNC_DICT[file_name]
# return func()
except Exception as ret:
return "产生了异常:%s" % str(ret)

 

posted @ 2018-03-14 20:51  葫芦娃大战奥特曼  阅读(279)  评论(0编辑  收藏  举报