软件测试|测试平台开发-Flask 入门:Flask HTTP请求详解
  X7HGjGJ7MG9G 2023年11月02日 32 0

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

简介

上一篇文章我们介绍了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应用程序变得更加简单。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  bzUvzvVq9oY1   2023年11月02日   23   0   0 数据类型json数据库
X7HGjGJ7MG9G
最新推荐 更多