当点击删除按钮时,无法在数据库中删除信息,跪求Python大佬指点迷津

程序大体的意思是用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)

无论怎么点击删除按钮,依然删除不了数据,代码中的SQL语句没有问题,在Shell中都可以删除
有没有Pyhton大佬帮忙看一下,小弟十分感激!

可以按照以下步骤设置删除按钮删除treeview和mysql数据库的某一行: 1. 在TreeView添加删除按钮的列,可以使用tkinter库的Button控件实现。 2. 给删除按钮绑定一个点击事件,当用户点击按钮,触发对应的函数。 3. 在函数获取当前选的行,可以使用TreeView的selection()方法。 4. 从选的行获取到需要删除的数据的主键值。 5. 使用mysql-connector-python模块连接到数据库,并且执行删除语句。 6. 从TreeView删除对应的行。 下面是一个示例代码,可以参考一下: ```python import mysql.connector from tkinter import * from tkinter import ttk # 创建数据库连接 conn = mysql.connector.connect( host="localhost", user="root", password="password", database="test_db" ) # 创建TreeView root = Tk() tree = ttk.Treeview(root) tree.pack() # 在TreeView添加删除按钮的列 tree["columns"] = ("name", "age", "action") tree.column("#0", width=0, stretch=NO) tree.column("name", width=100, anchor=W) tree.column("age", width=100, anchor=W) tree.column("action", width=100, anchor=W) tree.heading("#0", text="", anchor=W) tree.heading("name", text="Name", anchor=W) tree.heading("age", text="Age", anchor=W) tree.heading("action", text="Action", anchor=W) # 添加数据到TreeView cursor = conn.cursor() cursor.execute("SELECT * FROM user") for row in cursor.fetchall(): tree.insert("", END, text="", values=row[:-1] + ("Delete",)) # 删除函数 def delete(): # 获取当前选的行 selection = tree.selection() # 获取需要删除的数据的主键值 for item in selection: pk = tree.item(item, "values")[0] # 连接数据库,并且执行删除语句 cursor = conn.cursor() cursor.execute("DELETE FROM user WHERE id=%s", (pk,)) conn.commit() # 从TreeView删除对应的行 tree.delete(item) # 给删除按钮绑定点击事件 tree.bind("<Button-1>", lambda event: delete() if tree.identify_region(event.x, event.y) == "cell" else None) root.mainloop() ``` 在这个示例,我们创建了一个具有删除按钮的TreeView,当用户点击删除按钮,会触发delete()函数。在该函数,我们首先从选的行获取需要删除的数据的主键值,然后连接到mysql数据库,并且执行删除语句。最后,我们从TreeView删除对应的行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值