python给html传数据_将变量从HTML传递到Python / Flask

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 HTML I've tried the following code, which is inside of main.html

Asset Tag:

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

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.

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?

解决方案

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

I am not sure why you have a

nested within a 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.

Asset Tag:

You need to setup your route to accept a POST request so that it can receive data from the form on your page. See here for 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')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值