Python中flask框架list类型和字典类型数据前后端交互以及表单提交

  • Post author:
  • Post category:python





Python中flask框架表单提交

Web框架中前后端交互是开发中必不可少的流程,下面我们来介绍一下在pycharm中是如何进行前后端交互以及表单提交的





前端向后端进行表单提交

1、 html页面代码如下

action属性是指提交到的地址或者页面,method是指提交方法,有POST和GET等方法

<body>
    <form action="{{ url_for('result')}}" method="POST">
        <p>姓名:<input type="text" name="姓名"> </p>
        <p>年龄:<input type="text" name="年龄"> </p>
        <p>性别:<input type="text" name="性别"> </p>
        <p>单身:<input type="text" name="单身"> </p>
        <p><input type="submit" value="提交"></p>
    </form>
</body>

2、后端路由控制接收提交的表单如下

这里的’/result’是接收表单之后返回的界面,methods=[‘post’,‘get’]这里是两种提交方法都支持,下面分情况讨论:注释写的很清楚了。

#接收表单提交的路由,这里需要指定方法为post
@app.route('/result',methods=['post','get'])  #支持两种方法接收表单
def result():
    if request.method=="POST":     #如果提交方式是POST方法,执行如下代码
        result=request.form         #使用request方法获取表单信息并传给result
        return render_template("result.html",result=result)         #返回一个html界面,并将这里的变量result传递给HTML界面的result





后端向前端进行传递参数

后端向前端传递参数上面的表单提交后面已经说明了,代码如上:

下面的代码单纯介绍后端向前端传递数据


@简单的变量传递

@app.route('/index1')
def index1():
    time=datetime.datetime.now().time()         #获取当前时间
    return render_template("html.html",a=time)      #将time赋值给html界面的 a参数

html界面接收参数

<body>
    现在的时间是{{ a }}
</body>


@list数组变量传递


路由界面代码

@app.route('/index1')     #/index地址,地址栏访问localhost:5000/index即可得到该路由指定的html界面
def index1():
    list = ["渣", "渣", "林"]         #定义list数组
    return render_template("html.html",list=list)      #将list赋值给html界面的list参数

html界面代码

<body>
    {%for list in list%}      {#使用for循环输出list,这里要注意格式#}
    <li>{{ list }}</li>
    {% endfor %}                {#for循环结束语句#}
</body>


@字典类型变量


路由界面

@app.route('/index1')     #/index地址,地址栏访问localhost:5000/index即可得到该路由指定的html界面
def index1():
    json = {"渣渣林": "帅", "多帅": "最帅"}        #定义json数组
    return render_template("html.html",json=json)      #将json赋值给html界面的json参数

html界面

<body>
    <table border="1">
        {%for key, value in json.items()%}  {#迭代器将字典格式的数据转换为[( , ),( , )]的数据#}
        <tr>                               {# 一行数据#}
            <td>{{key}}</td>
            <td>{{value}}</td>
        </tr>
        {% endfor %}
    </table>
</body>



版权声明:本文为qq_48736958原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。