|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 暗夜之隐 于 2020-4-5 11:50 编辑
- from flask import Flask, render_template, request
- import json
- app = Flask(__name__)
- @app.route('/')
- def student():
- return render_template('student.html')
- @app.route('/result',methods = ['POST', 'GET'])
- def result():
- if request.method == 'POST':
- print(request.method)#这是一个post请求
- result = request.form
- print(result)
- print(json.dumps(request.form))
-
- return render_template("result.html",result = result)
- if __name__ == '__main__':
- app.run(debug = True)
复制代码
上面这一段 request.form 出来的是什么数据 我打印出来的是这样的ImmutableMultiDict([('Name', '20'), ('Physics', '30'), ('chemistry', '40'), ('Mathematics', '50')]) 是包含了提交的内容,但不明白他是用的什么方法把数据取出来 不是字典也不是单纯属列表 也不只是元组
我也查看有获取提交表单的方法json.dumps(request.form) 可以得到提交的表单 字典格式
- <html>
- <body>
-
- <form action = "http://localhost:5000/result" method = "POST">
- <p>Name <input type = "text" name = "Name" /></p>
- <p>Physics <input type = "text" name = "Physics" /></p>
- <p>Chemistry <input type = "text" name = "chemistry" /></p>
- <p>Maths <input type ="text" name = "Mathematics" /></p>
- <p><input type = "submit" value = "submit" /></p>
- </form>
-
- </body>
- </html>
复制代码
这上面的是提交数据
- <!doctype html>
- <html>
- <body>
- <table border = 1>
- {% for key, value in result.items() %}
- <tr>
- <th> {{ key }} </th>
- <td> {{ value }} </td>
- </tr>
- {% endfor %}
- </table>
- </body>
- </html>
复制代码
这里就是不明白数据是如何提取出来的 传入这个模板的数据是result = request.form ,用到的是result.items() 我在网上也没看到这个方法,另外出来的应该是字典 但for 循环里面有2个值,难道result.items() 的结果是一个列表或元组吗 我打印过这个result.items()数据出来的是<generator object MultiDict.items at 0x000002430B561390>
我能想到的就还是这个数据 request.form 出来的数据是这样的这里面有4个元组,但这是如何提取出来的呢 ImmutableMultiDict([('Name', '20'), ('Physics', '30'), ('chemistry', '40'), ('Mathematics', '50')])
再来一组测试:
>>> from werkzeug.datastructures import ImmutableMultiDict as wdi
>>> d =wdi([('a', 'b'), ('a', 'c')])
>>> d.getlist("a")
['b', 'c']
>>> d["a"]
'b'
>>> for key,value in d.items():print(key)
...
a
>>> for key,value in d.items():print(key,value)
...
a b
>>> d.items()
<generator object MultiDict.items at 0x000002080A816E48>
>>> list(d.items())
[('a', 'b')]
>>> dict(d.items())
{'a': 'b'}
>>> d
ImmutableMultiDict([('a', 'b'), ('a', 'c')])
>>> len(d)
1
>>> d =wdi([('a', 'b'), ('a', 'c'),("333","tte"),("444","sdfs")])
>>> d
ImmutableMultiDict([('a', 'b'), ('a', 'c'), ('333', 'tte'), ('444', 'sdfs')])
>>> len(d)
3
>>> for key,value in d.items():print(key,value)
...
a b
333 tte
444 sdfs
>>>
|
|