将变量从 HTML 传递到 Python/Flask

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41885919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:47:38  来源:igfitidea点击:

Passing Variable from HTML to Python/Flask

pythonhtmlflask

提问by Suever

Let me try this again. I want to enter a variable into my HTML form to submit, so far from reading the link here How to display a variable in HTMLI've tried the following code, which is inside of main.html

让我再试一次。我想在我的 HTML 表单中输入一个变量来提交,到目前为止还没有阅读这里的链接How to display a variable in HTML我已经尝试了下面的代码,它在里面main.html

  <form>
      Asset Tag:<br>
      <input type="text" name="Asset Tag"><br>
      <input type="submit" value="Submit">
      <form action="{{ asset_tag }}" method="get">
  </form>

I then have a python script that goes like this,

然后我有一个像这样的python脚本,

from flask import Flask, render_template
app = Flask('server')

@app.route('/py')
def server():
    return render_template('main.html')
#API URL
JSS_API = 'https://apiresource.com'

#Pre-Defined username and password
username = 'username'
password = 'password'

#Ask User for the Asset tag
asset_tag = {{ }}

After the asset tag is entered it just searches through a JSON file for match, the rest doesn't matter so much so I didn't include the next piece of the script.

输入资产标签后,它只是在 JSON 文件中搜索匹配,其余的无关紧要,所以我没有包含脚本的下一部分。

So Flask renders my HTML just fine and I can submit a value but it's not being passed back to the script, which makes sense as I'm doing the opposite of the link I provided, but I just can't not think of how it's done. Any suggestions?

所以 Flask 可以很好地呈现我的 HTML,我可以提交一个值,但它没有被传递回脚本,这是有道理的,因为我正在做与我提供的链接相反的操作,但我想不出它是怎么回事完毕。有什么建议?

回答by Suever

You have a few issues that I've outlined below. Overall though, the frontend ispassing the variable to the backend, it's just that the variables are only accessible via the requestobject from within the route to which the data is passed.

我已经在下面概述了您的一些问题。总体来说,前端传递变量到后端,它只是两个变量仅通过访问request对象从该数据传递路线之内

  • I am not sure why you have a <form>nested within a <form>here, but you'll want to remove the inner one since it's not doing anything.

  • You want to setup your form to POST the data to your backend when submitted. If you don't specify an action, then it will POST to the same page the same page that you're currently viewing.

    <form method="POST">
        Asset Tag:<br>
        <input type="text" name="tag"><br>
        <input type="submit" value="Submit">
    </form>
    
  • You need to setup your route to accept a POST request so that it can receive data from the form on your page. See herefor more information on HTTP methods.

    @app.route('/py', methods=['GET', 'POST'])
    
  • Inside of your route, you'll want to check whether it was a GET request (and load a normal page) or whether it was a POST (form data was sent so we should use it)

    from flask import request
    
    @app.route('/py', methods=['GET', 'POST'])
    def server():
        if request.method == 'POST':
            # Then get the data from the form
            tag = request.form['tag']
    
            # Get the username/password associated with this tag
            user, password = tag_lookup(tag)
    
            # Generate just a boring response
            return 'The credentials for %s are %s and %s' % (tag, user, password) 
            # Or you could have a custom template for displaying the info
            # return render_template('asset_information.html',
            #                        username=user, 
            #                        password=password)
    
        # Otherwise this was a normal GET request
        else:   
            return render_template('main.html')
    
  • 我不知道为什么你有一个<form>嵌套在<form>这里,但你会想要删除内部的,因为它没有做任何事情。

  • 您想设置表单以在提交时将数据发布到后端。如果您未指定action,则它将 POST 到您当前正在查看的同一页面的同一页面。

    <form method="POST">
        Asset Tag:<br>
        <input type="text" name="tag"><br>
        <input type="submit" value="Submit">
    </form>
    
  • 您需要设置您的路由以接受 POST 请求,以便它可以从您页面上的表单接收数据。有关HTTP 方法的更多信息,请参见此处

    @app.route('/py', methods=['GET', 'POST'])
    
  • 在路由内部,您需要检查它是 GET 请求(并加载普通页面)还是 POST(发送了表单数据,因此我们应该使用它)

    from flask import request
    
    @app.route('/py', methods=['GET', 'POST'])
    def server():
        if request.method == 'POST':
            # Then get the data from the form
            tag = request.form['tag']
    
            # Get the username/password associated with this tag
            user, password = tag_lookup(tag)
    
            # Generate just a boring response
            return 'The credentials for %s are %s and %s' % (tag, user, password) 
            # Or you could have a custom template for displaying the info
            # return render_template('asset_information.html',
            #                        username=user, 
            #                        password=password)
    
        # Otherwise this was a normal GET request
        else:   
            return render_template('main.html')