使用python和flask传递值

时间:2015-04-18 13:09:29

标签: python flask

我对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>";

1 个答案:

答案 0 :(得分:0)

首先,你在add()函数中输入了一个拼写错误。 这一行:

return ridirect(url_for('display'));

应该是

return redirect(url_for('display'));

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

myCursor = myConnection.cursor()

但是,在函数添加,删除和编辑中,您缺少此定义,但您仍在使用它。您不能省略此定义,因为第一个定义仅在{(3}}内的display()内有效。 尝试将此定义添加到其他功能。

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

开头
myConnection = pypyodbc.connect('Driver={SQL Server};'
                            'Server=local'
                            'Database=All;'
                            'uid=sa;pwd=23232')
myCursor = myConnection.cursor()

请告诉我们这是否适合您。

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