简体   繁体   English

request.form.get 返回 None 而不是 input

[英]request.form.get returns None instead of input

I'm creating a game in which someone inputs a word (that produces a search) and you have to guess what word it was by the results produced.我正在创建一个游戏,其中有人输入一个单词(产生搜索),您必须通过产生的结果猜测它是什么单词。 It works by getting the word inputed by player 1 (input1) and comparing it to your guess (input2).它通过获取玩家 1 (input1) 输入的单词并将其与您的猜测 (input2) 进行比较来工作。

When the user submits the input1, my python code gets it and stores it.当用户提交 input1 时,我的 python 代码获取并存储它。 But when the second player inputs input2 and submits, the input1 is overriden and request.form.get = None (although it gets input2 perfectly fine).但是当第二个玩家输入 input2 并提交时, input1 被覆盖并且 request.form.get = None (尽管它得到 input2 非常好)。

What is happening and how could I fix it?发生了什么,我该如何解决? Thank you (PS: I know this looks like a lot of code, but most of it is for context)谢谢(PS:我知道这看起来像很多代码,但大部分都是为了上下文)

HMTL HMTL

<h4 id='playern' style='color:grey; margin:20px;'>Player 1</h4>


<!-- Search -->
<div id='cont1' style='display:flex; flex-direction:column; justify-content:center'>
    <p>Choose search for <em>Player 2</em> to guess.</p>
    <form id='form1' action='/multi' method='post'>
        <div class='form-group'>
            <input name='input1' id="input1" autofocus autocomplete='off' placeholder="cats, face..." type="text">
            <button id='input-btn' type='submit'>Submit</button>
            <hr>
        </div>
    </form>
</div>


<!--iframe-->
<div style='height:70%; width:100%; overflow:hidden;margin:10px 0px 50px 0px; position: sticky; display:flex; justify-content:center; border-style:none'>
    <iframe id='innerSpace' style="display:none;height:200%;width:60vw;margin-top:-120px;border-style:none;" title="Results"></iframe>
</div>


<!-- Guess -->
<div id='cont2' style='display:none; height: max-content; width:100%; position: sticky; border-style:none'>
    <h5>What is the search for these results?</h5>
    <form action='/multi' method='post'>
        <div class='form-group'>
            <input name='input2' id='input2' type='text'  autofocus autocomplete='off' placeholder='Guess'>
            <button id='guess-btn' type='submit'>Submit</button>
        </div>
    </form>
</div>

Javascript Javascript

<script>
  let is = document.getElementById('innerSpace');
  let input1 = document.getElementById('input1');
  let input2 = document.getElementById('input2');

  let playern = document.getElementById('playern');
  let cont1 = document.getElementById('cont1');
  let cont2 = document.getElementById('cont2');

  let spacer = document.getElementById('spacer');

  input1.addEventListener('change', searchFor);
  function searchFor() {
    //create constant variable with the value of input1
    const inp = input1;
    playern.innerHTML = 'Player 2';
    playern.style.marginTop = '0px';
    // hide first form and show the second one
    cont1.style.display = 'none';
    cont2.style.display = 'flex';
    cont2.style.flexDirection = 'column';
    cont2.style.justifyContent = 'center';
    cont2.style.alignItems = 'center';
    spacer.style.display ='none';
    is.style.display = 'flex';
    // search results
    let query = encodeURIComponent(input1.value);
    is.src = `https://search.givewater.com/serp?qc=images&q=weirdest+${query}`;
    // when user submits guess
    input2.addEventListener('change', function(){
        // trying to override None value by replacing with const value
        input1.value = inp.value;
        // tryin to re-submit input1
        document.getElementById("form1").submit();
    });
  }

Python Python

@app.route('/multi', methods =['POST', 'GET'])
@login_required
def multiplayer():

    #If user got here from link
    if request.method == 'GET':
        return render_template('multiplayer.html')

    #If user inputed something
    if request.method == 'POST':

        global inp
        inp = request.form.get('input1')

        #this stops the whole page from loading before user submits a guess
        while not request.form.get('input2'):
            #wait
            print('.', end='')
            time.sleep(1)
            #if guess exists
            if request.form.get('input2'):
                break

        ui = inp

        #Get guess
        guess = request.form.get('input2')

        #Get User id
        userId = session['user_id']

        #Get current score from user (and id)
        rows = db.execute('SELECT * FROM scores WHERE user_id = ?', userId)

        #if this user hasn't played yet
        ##add them to the table with a score of 0
        if not rows:
            db.execute('INSERT INTO scores (user_id, score) VALUES (?, ?)', userId, 0)
            rows = db.execute('SELECT * FROM scores WHERE user_id = ?', userId)

        #Get score of current user
        points = rows[0]['score']


        #If correct guess, increase points by 1
        if guess == inp:
            points += 1
            #Update score
            db.execute('UPDATE scores SET score = ? WHERE user_id = ?', points, userId )
            #copy to another variable
            w = inp
            g = guess
            s = points
            return render_template('results.html', title = 'Correct!', t1 = 'The search was', word = w, t2 = 'Your guess was', guess = g, score = s)
        #If wrong guess
        else:
            w = inp
            g = guess
            s = points
            return render_template('results.html', title = 'Incorrect', t1 = 'The search was', word = w, t2 = 'Your guess was', guess = g, score = s)

Rather than using a global variable for inp and guess , use the session cookie instead:不要为 inp 和guess使用全局变量,而是使用inp cookie:

from flask import session

...

session['inp'] = request.form.get('input1')

...

session['guess'] = request.form.get('input2')

...

if session['inp'] == session['guess]:
   # do stuff

Storing values in a global variable is not the thing you want to be doing here;将值存储在全局变量中并不是您想要做的事情。 it doesn't behave the way you think it would, and it isn't very practical.它的行为不像你想象的那样,也不是很实用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM