首页后端开发Python软件测试|测试平台开发-Flask 入门:Flask HTTP请求详解

软件测试|测试平台开发-Flask 入门:Flask HTTP请求详解

时间2023-12-03 03:01:02发布访客分类Python浏览616
导读:简介上一篇文章我们介绍了flask的基本使用,编写了flask的第一个脚本。在本文中,我们将详细介绍如何使用Flask进行HTTP请求。我们将学习如何创建Flask应用程序,并通过不同的HTTP方法(GET、POST、PUT、DELETE等...

简介

上一篇文章我们介绍了flask的基本使用,编写了flask的第一个脚本。在本文中,我们将详细介绍如何使用Flask进行HTTP请求。我们将学习如何创建Flask应用程序,并通过不同的HTTP方法(GET、POST、PUT、DELETE等)发送请求。

app.route()

要使用不同的http方法发送请求,我们要先了解flask是如何创建路由的,我们可以查看app.route()的源代码,对这一方法先进行了解,鼠标悬停至app.route()处,按住ctrl+鼠标左键即可查看源代码。源代码如下:

@setupmethod
    def route(self, rule: str, **options: t.Any) ->
     t.Callable[[T_route], T_route]:
        """Decorate a view function to register it with the given URL
        rule and options. Calls :meth:`add_url_rule`, which has more
        details about the implementation.

        .. code-block:: python

            @app.route("/")
            def index():
                return "Hello, World!"

        See :ref:`url-route-registrations`.

        The endpoint name for the route defaults to the name of the view
        function if the ``endpoint`` parameter isn't passed.

        The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
        ``OPTIONS`` are added automatically.

        :param rule: The URL rule string.
        :param options: Extra options passed to the
            :class:`~werkzeug.routing.Rule` object.
        """
     def decorator(f: T_route) ->
 T_route:
       endpoint = options.pop("endpoint", None)
       self.add_url_rule(rule, endpoint, f, **options)
       return f

	return decorator
  • Calls:meth: add_url_rule
  • end_poiont 如果未传递 endpoint 参数,则路由的端点名称默认为视图函数的名称,如果已为注册函数,则会引发错误
  • methods 参数默认值是 "GET",所以当你不传 methods 参数时,只有发送 GET 请求才能匹配上对应的路由

创建http请求

  1. 创建get请求

上面我们提到了,methods参数默认值是'get',所以我们不加参数也可以直接实现get请求,代码如下:

# 不指定 methods,默认就是 GET
@app.route('/', methods=['GET'])
def index():
    return 'Hello, Flask!'


@app.route('/get', methods=["GET"])
def get_():
    # 返回字符串
    return '这是get请求'
  1. 创建post请求
@app.route('/api/data', methods=['POST'])
def post_data():
    data = request.json
    # 处理POST请求数据并返回响应
    return jsonify({
"message": "Data received successfully!", "data": data}
)
  1. 创建PUT、DELETE 请求
@app.route('/putordelete', methods=['PUT', 'DELETE'])
def update_or_delete_data(id):
    if request.method == 'PUT':
        # 处理PUT请求并更新数据
        return jsonify({
"message": f"Data with ID {
id}
 updated successfully!"}
)
    elif request.method == 'DELETE':
        # 处理DELETE请求并删除数据
        return jsonify({
"message": f"Data with ID {
id}
 deleted successfully!"}
)

注:视图函数的返回值类型只能是 string、dict、tuple,若返回的是其他类型的数据,将会报错。

注:post请求和put、delete请求需要导入flask的requestjsonify方法

验证请求

我们上面用代码创建了各种请求,现在我们要验证我们的请求是否构造成功了,我们可以使用postman来验证请求,也可以使用requests来验证我们是否成功构造了请求,代码如下:

import requests

base_url = 'http://127.0.0.1:5000'

# GET请求
response = requests.get(base_url)
print(response.text)

response = requests.get(base_url+ '/get')
print(response.text)

# POST请求
data = {
'name': 'John', 'age': 30}

response = requests.post(base_url+'/api/data', json=data)
print(response.json())

# PUT请求
response = requests.put(base_url+'/api/data/1', json={
'name': 'Updated Data'}
)
print(response.json())

# DELETE请求
response = requests.delete(base_url+'/api/data/1')
print(response.json())


###################
运行脚本,结果如下:
Hello, Flask!
这是get请求
{
'data': {
'age': 30, 'name': 'John'}
, 'message': 'Data received successfully!'}

{
'message': 'Data with ID 1 updated successfully!'}

{
'message': 'Data with ID 1 deleted successfully!'}
    

总结

本文主要介绍了使用Flask进行HTTP请求的基本过程。你可以根据自己的需求在视图函数中处理数据、数据库交互等。Flask提供了强大的扩展和中间件,使得构建功能丰富的Web应用程序变得更加简单。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 软件测试|测试平台开发-Flask 入门:Flask HTTP请求详解
本文地址: https://pptw.com/jishu/565624.html
软件测试|测试平台开发-Flask 入门:URL组成部分详解 软件测试|测试平台开发-Flask入门:Flask动态路由

游客 回复需填写必要信息