Flask动态构建的表单到底是怎么回事?如何处理name属性?
我搭建了一个网页,它动态创建一个输入字段组成的表单,字段名总是不同。
通过调整每个输入字段的name属性,我实现了让值与名称一一对应。于是当把表单发送给Python时,我可以把名称拆分出来,并把名称与值关联起来。
然而,在WTForms下实现这点比较困难。
下面是由JavaScript生成的。名称由slots-(index) 组成,这在 'FieldList' 中会被使用,后缀为 unique_info_x。
<ul id="slots">
<li><input type="number" name="slots-0-unique_info_0"></li>
<li><input type="number" name="slots-1-unique_info_1"></li>
</ul>
PYTHON:
from flask import Flask, render_template, request, session, url_for,
redirect, flash from wtforms import FieldList, IntegerField from
wtforms.validators import NumberRange from flask_wtf import FlaskForm
class SlotInputForm(FlaskForm):
slots = FieldList(IntegerField('slots', validators=[NumberRange(message='Insert numbers between 0 - 100 only.', min=0, max=100)] ))
@app.route('/', methods=['GET', 'POST'])
def mainpage():
form = SlotInputForm()
if form.validate_on_submit():
# Here I should have access to the value of the input and the unique_info_x string which is part of the name
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
我想要找一种方法,能够以某种方式遍历表单的详细信息,在遍历的同时对输入进行校验,并且让unique_info_x后缀作为数据与实际值一起可用。
我找到了关于按前述描述对name属性进行更多信息适配的一些资料。但我在理解在把它发送到flask进行校验时,如何遍历它时遇到了困难。
也许有办法隐藏unique_info_X?也许可以用标签来实现?
你能帮忙吗?
解决方案
# requirements.txt
# requests==2.31.0
# flask==3.0.0
import requests
from flask import Flask, request, redirect, session
import urllib.parse
app = Flask(__name__)
app.secret_key = 'your-secret-key-here'
CLIENT_ID = 'your-client-id'
CLIENT_SECRET = 'your-client-secret'
REDIRECT_URI = 'http://localhost:5000/callback'
@app.route('/login')
def login():
params = {
'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI,
'scope': 'r_liteprofile r_emailaddress'
}
url = 'https://www.linkedin.com/oauth/v2/authorization?' + urllib.parse.urlencode(params)
return redirect(url)
@app.route('/callback')
def callback():
code = request.args.get('code')
token_url = 'https://www.linkedin.com/oauth/v2/accessToken'
data = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
}
response = requests.post(token_url, data=data)
token_data = response.json()
if 'access_token' not in token_data:
return f"Error: {token_data}"
session['access_token'] = token_data['access_token']
return redirect('/profile')
@app.route('/profile')
def get_profile():
access_token = session.get('access_token')
if not access_token:
return redirect('/login')
headers = {'Authorization': f'Bearer {access_token}'}
response = requests.get('https://api.linkedin.com/v2/userinfo', headers=headers)
return response.json()
if __name__ == '__main__':
app.run(debug=True, port=5000)
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。