Flask - не удается обновить базу данных в MySQL - PullRequest
0 голосов
/ 08 мая 2019

Структура базы данных:

enter image description here

Я успешно завершил регистрацию и модель входа в систему (это означает, что с соединением все в порядке)

Но когда я пытался обновить базу данных, получая сообщения из радио-формы, она глючила.

Таблица до обновления: enter image description here И после того, как я отправил форму ввеб-страница, она остается прежней.

код в веб-интерфейсе:

<form method="POST" action="">
    <div class="col-xs-6">
        <div class="form-group" style="text-align: center">
            <div align="center">
                <img src="/static/img/cxk.jpeg" class="img-responsive" style="max-height: 200px">
            </div>
            <br>
            <br>
            <label>Beautiful Chicken &nbsp;&nbsp;</label>
            <!-- the name variable should be the same to the item inside "request.form['name']" -->
            <input type="radio" name="vote_form" value="cxk">
            <br>
            <h5>Brief introduction....</h5>
        </div>
        <div id='bc_canvas'>

        </div>
    </div>
    <div class="col-xs-6">
        <div class="form-group" style="text-align: center">
            <div align="center">
                <img src="/static/img/23333.jpg" class="img-responsive" style="max-height: 200px">
            </div>
            <br>
            <br>
            <label>Panda Face Guy &nbsp;&nbsp;</label>
            <input type="radio" name="vote_form" value="panda">
            <br>
            <h5>Brief introduction....</h5>  
        </div>
        <div id=pds_canvas>

        </div>
        </div>   
            <br>
            <input type="submit" class="btn btn-primary" value="Vote" style="margin-left:48%;margin-top:20px;margin-bottom: 20px"> 
</form>

код в .py:


@app.route('/vote',methods=['GET','POST'])
@is_logged_in
def vote():
    if request.method=='POST':
        cur=mysql.connection.cursor()
        # Check if this user had voted for somebody
        is_voted = cur.execute("SELECT TUTOR_VOTED FROM USERS WHERE USERNAME='%s'" % str(session["username"]))
        if is_voted==0:
            flash("You had voted",'warning')
        else:
            try:
            # selected_value=request.form('vote_form') will cause ImmutableMultiDict error
                selected_value=request.form['vote_form']
            except:
                # if error
                flash("Please Vote For one Tutor",'warning')
            else:
                # need cur.fetchall. the cur.execute just return the row it points to
                cxk_old_row=cur.execute("SELECT VOTE_COUNT FROM VOTE_MSG WHERE NAME= %s",['Beautiful_Chicken'])
                fuck1 = cur.fetchall()
                cxk_old=fuck1[0].get('VOTE_COUNT')
                panda_old_row=cur.execute("SELECT VOTE_COUNT FROM VOTE_MSG WHERE NAME='Panda_Face'")
                fuck2 = cur.fetchall()
                panda_old=fuck2[0].get('VOTE_COUNT')

                if selected_value=='cxk':
                    cxk_new=cxk_old+1
                    cur.execute("UPDATE VOTE_MSG SET VOTE_COUNT=%s WHERE NAME='Beautiful_Chicken'"%int(cxk_new))
                    cur.execute("UPDATE USERS SET TUTOR_VOTED=1 WHERE USERNAME='%s'" % str(session["username"]))
                    flash(cxk_new,'success')
                elif selected_value=='panda':
                    panda_new=panda_old+1
                    cur.execute("UPDATE VOTE_MSG SET VOTE_COUNT=%s WHERE NAME=%s",(panda_new,"Panda_Face"))
                    cur.execute("UPDATE USERS SET TUTOR_VOTED=1 WHERE USERNAME=%s",(session['username']))
                    flash("You are succesfully voted for Panda Face Guy",'success')
    return render_template('vote.html')

1 Ответ

0 голосов
/ 08 мая 2019

Мне не хватает mysql.connection.commit() в .py файле

Таким образом, код после cur.execute (update sth) должен быть mysql.connection.commit()

следующим образом:

conn=mysql.connection
cur=conn.cursor()

cur.execute("UPDATE USERS SET TUTOR_VOTED=1 WHERE USERNAME=%s",(session['username']))
conn.commit()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...