将变量从 HTML 传递到 Python/Flask

3 html python flask

让我再试一次。我想在我的 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>
Run Code Online (Sandbox Code Playgroud)

然后我有一个像这样的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 = {{ }}
Run Code Online (Sandbox Code Playgroud)

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

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

Sue*_*ver 8

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

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

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

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

    @app.route('/py', methods=['GET', 'POST'])
    
    Run Code Online (Sandbox Code Playgroud)
  • 在路由内部,您需要检查它是 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')
    
    Run Code Online (Sandbox Code Playgroud)

  • 我接受了答案,因为它对我来说合乎逻辑。我意识到我在实践中还没有完全准备好。有点跳入深渊,而没有先学会游泳。谢谢! (2认同)