个性化阅读
专注于IT技术分析

Python Flask如何使用Request对象?

点击下载

在客户端-服务器体系结构中, 请求对象包含从客户端发送到服务器的所有数据。正如我们在本教程中已经讨论的那样, 我们可以使用HTTP方法在服务器端检索数据。

在本教程的这一部分中, 我们将讨论下表中给出的Request对象及其重要属性。

SN Attribute Description
1 Form 它是字典对象, 其中包含表单参数的键值对及其值。
2 args 它是从URL解析的。它是URL中在问号(?)之后指定的部分。
3 Cookies 它是包含cookie名称和值的字典对象。它保存在客户端以跟踪用户会话。
4 files 它包含与上载文件相关的数据。
5 method 这是当前的请求方法(获取或发布)。

模板上的表单数据检索

在下面的示例中, / URL呈现一个网页customer.html, 其中包含一个表单, 该表单用于将客户详细信息作为来自客户的输入。

将此表单中填写的数据发布到/ success URL, 该URL触发print_data()函数。 print_data()函数从请求对象收集所有数据, 并呈现result_data.html文件, 该文件显示网页上的所有数据。

该应用程序包含三个文件, 即script.py, customer.html和result_data.html。

script.py

from flask import *
app = Flask(__name__)
 
@app.route('/')
def customer():
   return render_template('customer.html')
 
@app.route('/success', methods = ['POST', 'GET'])
def print_data():
   if request.method == 'POST':
      result = request.form
      return render_template("result_data.html", result = result)
 
if __name__ == '__main__':
   app.run(debug = True)

customer.html

<html>
   <body>
       <h3>Register the customer, fill the following form.</h3>
      <form action = "http://localhost:5000/success" method = "POST">
         <p>Name <input type = "text" name = "name" /></p>
         <p>Email <input type = "email" name = "email" /></p>
         <p>Contact <input type = "text" name = "contact" /></p>
         <p>Pin code <input type ="text" name = "pin" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
   </body>
</html>

result_data.html

<!doctype html>
<html>
   <body>
      <p><strong>Thanks for the registration. Confirm your details</strong></p>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>

要运行该应用程序, 我们必须首先使用命令python script.py运行script.py文件。这将在localhost:5000上启动开发服务器, 可以在浏览器上访问它, 如下所示。

Python Flask如何使用Request对象?

现在, 点击提交按钮。它将传输到/ success URL并显示在客户端输入的数据。

Python Flask如何使用Request对象?

赞(0)
未经允许不得转载:srcmini » Python Flask如何使用Request对象?

评论 抢沙发

评论前必须登录!