暗夜之隐 发表于 2020-4-5 11:37:39

flask 表单提交问题

本帖最后由 暗夜之隐 于 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')])

wp231957 发表于 2020-4-5 14:44:19

本帖最后由 wp231957 于 2020-4-5 14:48 编辑

ImmutableMultiDict的父类 是class MultiDict(TypeConversionDict):
@native_itermethods(["keys", "values", "items", "lists", "listvalues"])
class MultiDict(TypeConversionDict):
#这个类代码很长,我只是复制了doc部分,可惜那些句子我都不认识
#但是可以看出来,这是自定义的一种数据类型,大约用法和字典差不多
    """A :class:`MultiDict` is a dictionary subclass customized to deal with
    multiple values for the same key which is for example used by the parsing
    functions in the wrappers.This is necessary because some HTML form
    elements pass multiple values for the same key.

    :class:`MultiDict` implements all standard dictionary methods.
    Internally, it saves all values for a key as a list, but the standard dict
    access methods will only return the first value for a key. If you want to
    gain access to the other values, too, you have to use the `list` methods as
    explained below.

    Basic Usage:

    >>> d = MultiDict([('a', 'b'), ('a', 'c')])
    >>> d
    MultiDict([('a', 'b'), ('a', 'c')])
    >>> d['a']
    'b'
    >>> d.getlist('a')
    ['b', 'c']
    >>> 'a' in d
    True

    It behaves like a normal dict thus all dict functions will only return the
    first value when multiple values for one key are found.

    From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a
    subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will
    render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP
    exceptions.

    A :class:`MultiDict` can be constructed from an iterable of
    ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2
    onwards some keyword parameters.

    :param mapping: the initial value for the :class:`MultiDict`.Either a
                  regular dict, an iterable of ``(key, value)`` tuples
                  or `None`.
    """

wp231957 发表于 2020-4-5 15:08:19

再来一组测试:

>>> fromwerkzeug.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
>>>

暗夜之隐 发表于 2020-4-5 16:33:46

wp231957 发表于 2020-4-5 15:08
再来一组测试:

>>> fromwerkzeug.datastructures import ImmutableMultiDict as wdi


感谢解惑{:5_109:}
页: [1]
查看完整版本: flask 表单提交问题