2015-04-18 42 views
1

我對python和flask非常陌生。基本上,我正在構建一個非常基本的Web應用程序,允許管理員添加/編輯/刪除用戶列表。該列表顯示在主菜單上,管理員可以第一次添加/編輯/刪除。但是,當我嘗試再次添加/編輯/刪除時,它不起作用,如果在添加/編輯/刪除後,我重定向回主菜單(用戶列表所在的位置),也會失敗。任何想法可能是什麼問題?使用python和flask傳遞值

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

回答

0

首先,您在add()函數中存在拼寫錯誤。 這條線:

return ridirect(url_for('display')); 

應該

return redirect(url_for('display')); 

接下來,在顯示屏()定義myCursor,然後你使用它。沒關係

myCursor = myConnection.cursor() 

但是,在函數添加,刪除和編輯你缺少這個定義,但你仍然在使用它。您不能忽略此定義,因爲第一個僅在display()中有效,因爲variable scope。 嘗試將此定義添加到其他函數中。

如果這不起作用,可能是因爲您還需要爲每個請求創建一個新連接,而不僅僅是在文件的開頭。然後,每個功能將開始

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

請讓我們知道這是否適合您。

注意:我剛剛注意到您實際上在添加/刪除/編輯myConnection.close()後關閉了連接。因此,您肯定需要使用上面的代碼重新打開每個請求的連接。

+0

你的第二個建議像魅力一樣工作。必須爲每個添加/編輯/刪除聲明myConnection和myCursor。謝謝你!我會爲您的解決方案投票,但不幸的是這是一個新帳戶。 –

+0

很高興幫助! – kecer