重要的是装饰器的使用
import socket
import re
from sh_heima_python7_3 import mini_web01
import multiprocessing
# 定义一个类
class Server(object):
# 在类属性中添加套接字
def __init__(self):
# 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(("", 1314))
# 3. 变为监听套接字
self.tcp_server_socket.listen(128)
# 定义一个函数具体的运行
def run_server(self, client_socket):
content = client_socket.recv(1024).decode("utf-8")
path = ""
if content:
path = re.match(r"[^/]*([^ ]*)", content).group(1)
if path == "/":
path = "/index.html"
if path.endswith(".html"):
url_parms = dict()
url_parms["path"] = path
print("文件路径",url_parms)
body = mini_web01.application(url_parms, self.start_response)
header = "HTTP/1.1 %s\r\n"%self.a
for temp in self.b:
header += "%s:%s\r\n"%(temp[0],temp[1])
head_body = header + "\r\n" + body
client_socket.send(head_body.encode("utf-8"))
else:
try:
with open("./static%s"%path) as f:
content = f.read()
except:
header = "HTTP/1.1 200 OK\r\n"
body = "没有文件"
head_body = header + "\r\n" + body
client_socket.send(head_body.encode("utf-8"))
client_socket.close()
else:
body = content
header = "HTTP/1.1 200 OK\r\n"
head_body = header + "\r\n" + body
client_socket.send(head_body.encode("utf-8"))
client_socket.close()
def run(self):
while True:
client_socket, client_addr = self.tcp_server_socket.accept()
p = multiprocessing.Process(target= self.run_server, args=(client_socket,))
p.start()
client_socket.close()
self.tcp_server_socket.close()
def start_response(self,a, b):
self.a = a
self.b = b
a = Server()
a.run()
import re
from pymysql import connect
from urllib.parse import unquote
url_dict = dict()
# 定义wsgi协议
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
# 根据不同的地址进行判断
file_name = environ['path']
# print("file_name",file_name)
# print("字典", url_dict)
for key, value in url_dict.items():
match= re.match(key, file_name)
if match:
return value(match)
else:
return "没有这个文件"
# 定义一个装饰器
def set_args(args):
def set_fun(func):
url_dict[args] = func
def call_fun(*args, **kwargs):
return func(*args, **kwargs)
return call_fun
return set_fun
# 定义一个函数index
@set_args("/index.html")
def index(match):
with open("./templates/index.html") as f:
content = f.read()
# 2. 得到要替换的数据
row_str = """<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="%s">
</td>
</tr> """
# 连接数据
# 1得到连接
# 2执行sql语句
# 关闭连接
# alt+enter:修正
# 1. 连接数据
# 创建Connection连接
conn = connect(host='localhost', port=3306, database='stock_db', user='root', password='mysql', charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# 2. 执行sql语句
cs1.execute(""" select * from info; """);
table_content = cs1.fetchall()
# 3. 关闭
cs1.close()
conn.close()
# 得到正确的数据
table_show = ""
for temp in table_content:
table_show += row_str % (temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[1])
# 3. 替换
content = re.sub(r'\{%content%\}', table_show, content)
return content
# 定义一个函数center
@set_args("/center.html")
def center(match):
# 1.找到模板
# 2.得到正确的数据
# 1.网页的代码
# 2. 数据库的数据
# 3. 替换
# 4.return返回
# 找到模板
with open("./templates/center.html") as f:
content = f.read()
# 替换的数据
row_str = """ <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/%s.html"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> 修改 </a>
</td>
<td>
<input type="button" value="删除" id="toDel" name="toDel" systemidvaule="%s">
</td>
</tr> """
sql_str = """ select info.code,info.short,info.chg,info.turnover,info.price,info.highs,focus.note_info from info,focus where info.id = focus.info_id; """
# 正确的数据
# 1. 连接数据
# 创建Connection连接
conn = connect(host='localhost', port=3306, database='stock_db', user='root', password='mysql', charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# 2. 执行sql语句
cs1.execute(sql_str);
table_content = cs1.fetchall()
# 3. 关闭
cs1.close()
conn.close()
# 所数据的数据进行拆分组装到我们的显示的条目上
table_str = ""
for temp in table_content:
table_str += row_str % (temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[0], temp[0])
# 替换
content = re.sub(r"\{%content%\}", table_str, content)
return content
# 定义一个函数add
@set_args(r"/add/(\d+)\.html")
def add(match):
num = match.group(1)
print("num",type(num))
conn = connect(host='localhost', port=3306, database='stock_db', user='root', password='mysql', charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
cs1.execute("""select * from focus where info_id in (select id from info where code = %s)""",(num,))
con = cs1.fetchone()
if con:
cs1.close()
conn.close()
return "已经关注过了"
else:
cs1.execute("""insert into focus(info_id) (select id from info where code = %s)""",(num,))
conn.commit()
cs1.close()
conn.close()
return "关注成功"
@set_args(r"/del/(\d+)\.html")
def del_data(match):
code = match.group(1)
conn = connect(host='localhost', port=3306, database='stock_db', user='root', password='mysql', charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
cs1.execute("delete from focus where info_id in (select id from info where code = %s)",code)
conn.commit()
cs1.close()
conn.close()
return "删除成功"
# update/000007.html
@set_args(r"/update/(\d+)\.html")
def update(match):
code = match.group(1)
with open("./templates/update.html") as f :
con = f.read()
con = re.sub(r"\{%code%\}" ,code, con )
conn = connect(host='localhost', port=3306, database='stock_db', user='root', password='mysql', charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
cs1.execute("""select note_info from focus where info_id in (select id from info where code = %s)""",code)
content = cs1.fetchone()
print("content",content)
con = re.sub(r"\{%note_info%\}", content[0], con)
cs1.close()
conn.close()
return con
# update/000007/123456sdasfdsf.html
@set_args(r"/update/(\d+)/(.*)\.html")
def update(match):
code = match.group(1)
content = match.group(2)
content = unquote(content)
conn = connect(host='localhost', port=3306, database='stock_db', user='root', password='mysql', charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
cs1.execute("""update focus set note_info = %s where info_id = (select id from info where code = %s )""",(content,code))
conn.commit()
cs1.close()
conn.close()
return "修改成功"