程序大体的意思是用Python写一个简单的web服务器,然后写几个简单的页面,通过对页面的按钮点击实现对数据库的增删改查工作,但是当我点击删除按钮时,无效,数据无法在数据库中删除,请问大佬们,帮我看看我是哪里写的不对。
# web_server.py
import socket
import multiprocessing
import re
import dynamic.mini_frame
class WSGI_server():
def __init__(self):
self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.tcp_server_socket.bind(("", 7890))
self.tcp_server_socket.listen(128)
def client_server(self, new_socket):
request = new_socket.recv(1024).decode("utf-8")
request_lines = request.splitlines()
file_name = ""
ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
if ret:
file_name = ret.group(1)
if ret == "/":
file_name = "/index.html"
if not file_name.endswith(".html"):
try:
f = open("./static" + 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()
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
new_socket.send(response.encode("utf-8"))
new_socket.send(html_content)
else:
env = dict()
env['PATH_INFO'] = file_name
body = dynamic.mini_frame.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
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(self):
while True:
new_socket, new_socket_address = self.tcp_server_socket.accept()
p = multiprocessing.Process(target=self.client_server, args=(new_socket,))
p.start()
new_socket.close()
self.tcp_server_socket.close()
def main():
WSGI_Server = WSGI_server()
WSGI_Server.run()
if __name__ == '__main__':
main()
# frame 框架
import re
import urllib.parse
from pymysql import connect
URL_FUNC_DICT = dict()
def route(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(r"/index.html")
def index(ret):
with open("./templates/index.html") as f:
content = f.read()
conn = connect(host='localhost', port=3306, user='root', password='123456', database='stock_db', charset='utf8')
cs = conn.cursor()
cs.execute("select * from info;")
stock_infos = cs.fetchall()
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="%s">
</td>
</tr>
"""
html = ""
for line_info in stock_infos:
html += tr_template % (
line_info[0], line_info[1], line_info[2], line_info[3], line_info[4], line_info[5], line_info[6], line_info[7],
line_info[1])
content = re.sub(r"\{%content%\}", html, content)
return content
@route(r"/center.html")
def center(ret):
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, user='root', password='123456', database='stock_db', charset='utf8')
# 获得Cursor对象
cs = conn.cursor()
cs.execute(
"select i.code,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info from info as i inner join focus as f on i.id=f.info_id;")
stock_infos = cs.fetchall()
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/%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>
"""
html = ""
for line_info in stock_infos:
html += tr_template % (
line_info[0], line_info[1], line_info[2], line_info[3], line_info[4], line_info[5], line_info[6], line_info[0],
line_info[0])
# content = re.sub(r"\{%content%\}", str(stock_infos), content)
content = re.sub(r"\{%content%\}", html, content)
return content
@route(r"/add/(\d+)\.html")
def add_focus(ret):
# 1. 获取股票代码
stock_code = ret.group(1)
# 2. 判断试下是否有这个股票代码
conn = connect(host='localhost', port=3306, user='root', password='123456', database='stock_db', charset='utf8')
cs = conn.cursor()
sql = """select * from info where code=%s;"""
cs.execute(sql, (stock_code,))
# 如果要是没有这个股票代码,那么就认为是非法的请求
if not cs.fetchone():
cs.close()
conn.close()
return "没有这支股票,大哥 ,我们是创业公司,请手下留情..."
# 3. 判断以下是否已经关注过
sql = """ select * from info as i inner join focus as f on i.id=f.info_id where i.code=%s;"""
cs.execute(sql, (stock_code,))
# 如果查出来了,那么表示已经关注过
if cs.fetchone():
cs.close()
conn.close()
return "已经关注过了,请勿重复关注..."
# 4. 添加关注
sql = """insert into focus (info_id) select id from info where code=%s;"""
cs.execute(sql, (stock_code,))
conn.commit()
cs.close()
conn.close()
return "关注成功...."
@route(r"/del/(\d+)\.html")
def del_focus(ret):
# 1. 获取股票代码
stock_code = ret.group(1)
# 2. 判断试下是否有这个股票代码
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='stock_db',charset='utf8')
cs = conn.cursor()
sql = """select * from info where code=%s;"""
cs.execute(sql, (stock_code,))
# 如果要是没有这个股票代码,那么就认为是非法的请求
if not cs.fetchone():
cs.close()
conn.close()
return "没有这支股票,大哥 ,我们是创业公司,请手下留情..."
# 3. 判断以下是否已经关注过
sql = """ select * from info as i inner join focus as f on i.id=f.info_id where i.code=%s;"""
cs.execute(sql, (stock_code,))
# 如果没有关注过,那么表示非法的请求
if not cs.fetchone():
cs.close()
conn.close()
return "%s 之前未关注,请勿取消关注..." % stock_code
# 4. 取消关注
# sql = """insert into focus (info_id) select id from info where code=%s;"""
sql = """delete from focus where info_id = (select id from info where code=%s);"""
cs.execute(sql, (stock_code,))
conn.commit()
cs.close()
conn.close()
return "取消关注成功...."
@route(r"/update/(\d+)\.html")
def show_update_page(ret):
"""显示修改的那个页面"""
# 1. 获取股票代码
stock_code = ret.group(1)
# 2. 打开模板
with open("./templates/update.html") as f:
content = f.read()
# 3. 根据股票代码查询相关的备注信息
conn = connect(host='localhost', port=3306, user='root', password='123456', database='stock_db', charset='utf8')
cs = conn.cursor()
sql = """select f.note_info from focus as f inner join info as i on i.id=f.info_id where i.code=%s;"""
cs.execute(sql, (stock_code,))
stock_infos = cs.fetchone()
note_info = stock_infos[0] # 获取这个股票对应的备注信息
cs.close()
conn.close()
content = re.sub(r"\{%note_info%\}", note_info, content)
content = re.sub(r"\{%code%\}", stock_code, content)
return content
@route(r"/update/(\d+)/(.*)\.html")
def save_update_page(ret):
""""保存修改的信息"""
stock_code = ret.group(1)
comment = ret.group(2)
comment = urllib.parse.unquote(comment)
conn = connect(host='localhost', port=3306, user='root', password='123456', database='stock_db', charset='utf8')
cs = conn.cursor()
sql = """update focus set note_info=%s where info_id = (select id from info where code=%s);"""
cs.execute(sql, (comment, stock_code))
conn.commit()
cs.close()
conn.close()
return "修改成功..."
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
file_name = env['PATH_INFO']
try:
for url, func in URL_FUNC_DICT.items():
ret = re.match(url, file_name)
if ret:
return func(ret)
else:
return "请求的url(%s)没有对应的函数...." % file_name
except Exception as ret:
return "产生了异常:%s" % str(ret)
有没有Pyhton大佬帮忙看一下,小弟十分感激!