从HTML传递变量到Python/Flask

3
让我再试一次。我想在我的HTML表单中输入一个变量来提交,到目前为止,从这里阅读链接如何在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,

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 = {{ }}

在输入资产标签后,它只是在JSON文件中搜索匹配项,其余部分并不太重要,因此我没有包含脚本的下一部分。

所以Flask可以正确地渲染我的HTML,我可以提交一个值,但它没有被传回脚本,这很合理,因为我正在做与我提供的链接相反的事情,但我就是想不出怎么做。 有什么建议吗?

1个回答

10

以下是您需要注意的一些问题。总体而言,前端确实将变量传递到后端,只是这些变量只能通过request对象在数据传递到的路由内部进行访问。

  • 我不确定为什么您在这里嵌套了<form>,但是您需要删除内部的一个,因为它没有任何作用。

  • 当提交表单时,您需要设置表单将数据POST到您的后端。如果未指定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')
    

    2
    我接受了这个答案,因为它在逻辑上对我有意义。但我现在意识到,在实践中我还没有准备好。有点像在不会游泳的情况下跳进深水区。谢谢! - user7116090

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接