Skip to main content
 首页 » 编程设计

python之将变量从 HTML 传递到 Python/Flask

2025年05月04日26jiqing9006

让我再试一次。我想在我的 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> 

然后我有一个像这样的 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 = {{ }} 

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

所以 Flask 可以很好地呈现我的 HTML,我可以提交一个值,但它不会被传递回脚本,这是有道理的,因为我正在做与我提供的链接相反的事情,但我不能不去想它是如何完成的。有什么建议吗?

请您参考如下方法:

我在下面概述了您遇到的一些问题。总的来说,前端是将变量传递给后端,只是变量只能通过 request 访问。来自数据传递到的路径中的对象。

  • 我不确定你为什么有一个 <form>嵌套在 <form> 中在这里,但你会想要删除内部的,因为它没有做任何事情。

  • 您希望将表单设置为在提交时将数据 POST 到后端。如果您不指定 action , 然后它将 POST 到您当前正在查看的同一页面。

    <form method="POST"> 
        Asset Tag:<br> 
        <input type="text" name="tag"><br> 
        <input type="submit" value="Submit"> 
    </form> 
    
  • 您需要将路由设置为接受 POST 请求,以便它可以从您页面上的表单接收数据。参见 here有关 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')