使用python和flask传递值

使用python和flask传递值,python,flask,Python,Flask,我对python和flask还很陌生。基本上,我正在构建一个非常基本的web应用程序,允许管理员添加/编辑/删除用户列表。列表显示在主菜单上,管理员可以在第一时间添加/编辑/删除。但是,当我第二次尝试添加/编辑/删除时,它不起作用,如果我重定向回主菜单,在添加/编辑/删除后,用户列表将显示在主菜单中,它也会失败。你知道会是什么问题吗 from flask import Flask, url_for, request, render_template, redirect; from app imp

我对python和flask还很陌生。基本上,我正在构建一个非常基本的web应用程序,允许管理员添加/编辑/删除用户列表。列表显示在主菜单上,管理员可以在第一时间添加/编辑/删除。但是,当我第二次尝试添加/编辑/删除时,它不起作用,如果我重定向回主菜单,在添加/编辑/删除后,用户列表将显示在主菜单中,它也会失败。你知道会是什么问题吗

from flask import Flask, url_for, request, render_template, redirect;
from app import app;
import pypyodbc;

myConnection = pypyodbc.connect('Driver={SQL Server};'
                                'Server=local'
                                'Database=All;'
                                'uid=sa;pwd=23232')
myCursor = myConnection.cursor()
myCursor.execute('SELECT * FROM Users')
rows = myCursor.fetchall();

for r in rows:
    print(r)


@app.route('/')
def home():
    """Renders a sample page."""
    createLink = "<a href='" + url_for("display") + "'>Admin</a>";
    createLink2 = "<a href='" + url_for("user") + "'>User login</a>";
    createLink3 = "<a href='" + url_for("delete") + "'>Delete</a>";
    createLink4 = "<a href='" + url_for("edit") + "'>Edit</a>";
    return """<html>
                    <head>
                        <title>First page</title>
                    </head>
                        <body>
                            <h1>Menu</h1>
                            <div>
                            """ + createLink + """
                            </div>
                            <div>
                            """ + createLink2 + """
                            </div>
                            <div>
                            """ + createLink3 + """
                            </div>
                            <div>
                            """ + createLink4 + """
                            </div>
                        </body>
              </html>"""
@app.route('/display', methods=['GET', 'POST'])
def display():
    if request.method == 'GET':
        myCursor = myConnection.cursor()
        myCursor.execute('SELECT * FROM Users')
        rows = [dict(id=row[0], name=row[1], email=row[2], password=row[3]) for row in myCursor.fetchall()]
        return render_template('DisplayAll.html', rows = rows)
    else:
        return"<h2>Error</h2>"

@app.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'GET':
        return render_template('Add.html');
    elif request.method == 'POST':
        name = request.form['AddName'];
        email = request.form['AddEmail'];
        password = request.form['AddPassword'];

        SQLCommand = ("INSERT INTO Users "
                  "(Name, Email, Pword) "
                  "VALUES (?,?,?)")
        values = [name, email, password]

        myCursor.execute(SQLCommand,values)
        myConnection.commit();
        #print("works")
        #myCursor.execute('SELECT * FROM Users')
        #rows = [dict(id=row[0], name=row[1], email=row[2], password=row[3]) for row in myCursor.fetchall()]
        myConnection.close();
        return ridirect(url_for('display'));

    else:
        return "<h2>Error</h2>";

@app.route('/delete', methods=['GET', 'POST'])
def delete():
    if request.method == 'GET':
        return render_template('Delete.html');
    elif request.method == 'POST':
        try:
            DeleteId = request.form['DeleteId'];

            SQLCommand = ("DELETE FROM Users "
                      "WHERE UsererId = "
                      + DeleteId)

            myCursor.execute(SQLCommand)
            myConnection.commit();
            #myCursor.execute('SELECT * FROM Users')
            #rows = [dict(id=row[0], name=row[1], email=row[2], password=row[3]) for row in myCursor.fetchall()]
            myConnection.close();
            #return render_template("DisplayAll.html", rows = rows);
            return redirect(url_for('display'));
        except:
            return "<h2>Doesn't work</h2>"

    else:
        return "<h2>Error</h2>";

@app.route('/edit', methods=['GET', 'POST'])
def edit():
    if request.method == 'GET':
        return render_template('Edit.html');
    elif request.method == 'POST':
        try:
            Name = request.form['EditName'];
            Email = request.form['EditEmail'];
            Password = request.form['EditPassword'];
            EditId = request.form['EditId'];

            SQLCommand = ("UPDATE Users "
                      "SET Name = '" + Name +
                      "', Email = '" + Email +
                      "', Pword = '" + Password +
                      "' WHERE UsererId = "
                      + EditId)

            myCursor.execute(SQLCommand)
            myConnection.commit();
            #print("works")
            #myCursor.execute('SELECT * FROM Users')
            #rows = [dict(id=row[0], name=row[1], email=row[2], password=row[3]) for row in myCursor.fetchall()]
            myConnection.close();
            #return render_template("DisplayAll.html", rows = rows);
            return redirect(url_for('display'));
        except:
            return "<h2>Doesn't work</h2>"

    else:
        return "<h2>Error</h2>";

首先,在add函数中有一个输入错误。 这一行:

return ridirect(url_for('display'));
应该是

return redirect(url_for('display'));
接下来,在display中定义myCursor,然后使用它。没关系

myCursor = myConnection.cursor()
但是,在“添加、删除和编辑”函数中,您缺少此定义,但仍在使用它。您不能忽略此定义,因为第一个定义仅在显示内部有效,原因是。 也可以尝试将此定义添加到其他函数中

如果这不起作用,可能是因为您还需要为每个请求建立新连接,而不仅仅是在文件的开头。然后,每个函数将以

myConnection = pypyodbc.connect('Driver={SQL Server};'
                            'Server=local'
                            'Database=All;'
                            'uid=sa;pwd=23232')
myCursor = myConnection.cursor()
请让我们知道这是否适合您


注意:我刚刚注意到,在使用myConnection.close添加/删除/编辑连接后,您实际上正在关闭连接。因此,您肯定需要在每次请求时使用上面的代码重新打开连接。

您的第二个建议非常有效。必须为每次添加/编辑/删除声明myConnection和myCursor。谢谢你!我会投票赞成你的解决方案,但不幸的是,这是一个新帐户。