• 【星海出品】flask (二) request替代VUE测试flask接口


    flask 是一门使用 python 编写的后端框架。

    VUE前端UI装饰推荐学习Element组件库
    之后就不使用UI去测试flask了,环节太多,影响直观反映,直接使用postman或request测试更加直观.

    url携带参数

     @app.route('/my/blog/')
     def blog_detail(blog_id):  # put application's code here
         return '您访问的博客是{}'.format(blog_id)```
    
    • 1
    • 2
    • 3

    flask里的requests方法
    要获取来自前端的参数,可以使用request.args.get方法。
    有时候我们需要在前端没有传递该参数时,设置一个默认值。这个时候可以使用request.args.get的第二个参数。下面是设置默认值的代码

    age = request.args.get(‘page’, default=18)

     from flask import Flask,request
     @app.route('/book/list')
     def book_detail():  # put application's code here
         page = request.args.get('page', default=1, type=int)
         return '你获取的是{}'.format(page)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在前端有时候我们需要传递多个参数,例如下面的代码:

    http://localhost:5000/login?username=python123&password=12345

    这里username和password都是需要获取的参数。我们可以分别使用request.args.get方法获取各个参数:

    username = request.args.get('username')
    password = request.args.get('password')
    
    • 1
    • 2

    http://localhost:5000/search?keywords=python&keywords=flask&keywords=web&page=1

    keywords = request.args.getlist('keywords')
    page = request.args.get('page')
    
    • 1
    • 2

    可以将获取的值转换成int

    page = int(request.args.get('page', default=1))
    
    • 1

    http://localhost:5000/search?is_valid=true

    获取boole值

    is_valid = request.args.get('is_valid', default='false') == 'true'
    
    • 1
    request.form.get("key", type=str, default=None) 
    //获取表单数据
    request.args.get("key") 
    //获取get请求参数
    request.values.get("key") 
    //获取所有参数
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    我们用代码的方式去展示

    C/S模式

    Client

    requests是一个Python第三方库,用于发送HTTP请求。它提供了一种简单而优雅的方式来发送HTTP/1.1请求,并且可以自动处理
    连接池,重定向等问题。requests库可以在Python 2.7和Python 3中使用,支持HTTP和HTTPS请求,支持Cookie、代理、SSL证书验证等功能。
    使用requests库可以方便地发送GET、POST、PUT、DELETE等请求,并且支持上传文件和发送JSON数据等操作。通过requests库,我们可以轻松地与Web服务进行交互,获取数据或提交数据。requests库已经成为Python中最常用的HTTP客户端库之一,被广泛应用于Web开发、数据分析、爬虫等领域。

    python request 的使用
    pip3 install requests

    方法2:源码安装
    下载 requests源码 http://mirrors.aliyun.com/pypi/simple/requests/
    下载文件到本地之后,解压到Python安装目录,之后打开解压文件
    运行命令行输入python setup.py install 即可安装

    Server

    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
    • 1
    • 2
    • 3

    Client

    requests.request(url)	构造一个请求,支持以下各种方法
    requests.get()	发送一个Get请求
    requests.post()	发送一个Post请求
    requests.head()	获取HTML的头部信息
    requests.put()	发送Put请求
    requests.patch()	提交局部修改的请求
    requests.delete()	提交删除请求
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    import requests
    ip = "192.168.0.100"
    port = "5000"
    url = 'http://' + ip + ':' + port
    print(url)
    r = requests.get(url)
    print('code')
    print(r.status_code)
    print(type(r.status_code))
    print('header')
    print(r.headers)
    print(type(r.headers))
    print('content')
    print(r.headers)
    print(type(r.headers))
    print('text')
    print(r.text)
    print(type(r.text))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    http://192.168.0.100:5000
    code
    200

    header
    {‘Server’: ‘Werkzeug/3.0.0 Python/3.10.11’, ‘Date’: ‘Tue, 07 Nov 2023 07:25:38 GMT’, ‘Content-Type’: ‘text/html; charset=utf-8’, ‘Content-Length’: ‘12’, ‘Connection’: ‘close’}

    content
    {‘Server’: ‘Werkzeug/3.0.0 Python/3.10.11’, ‘Date’: ‘Tue, 07 Nov 2023 07:25:38 GMT’, ‘Content-Type’: ‘text/html; charset=utf-8’, ‘Content-Length’: ‘12’, ‘Connection’: ‘close’}

    text
    Hello World!

    Client

    Head = r.headers
    print(type(Head))
    print(type(r.headers))
    if 'Content-Type' in Head:
        print("B")
        B = Head.get('Content-Type')
        print(B)
        print(type(B))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8



    B
    text/html; charset=utf-8

    url = url + '/user/login'
    print(url)
    auth = {
        "userName" : "admin",
        "password" : "123456"
    }
    r = requests.post(url,json=auth)
    print(r.status_code)
    print(r.content)
    
    print( r.json() )
    print( type(r.json() ) )
    print(r.json().get('data').get('token') )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    http://192.168.0.100:5000/user/login
    200
    b’{\n “code”: 0,\n “data”: {\n “token”: “666666”\n }\n}\n’
    {‘code’: 0, ‘data’: {‘token’: ‘666666’}}

    666666

    urlB = url + '/user/info'
    print(urlB)
    headers = {
      'token': '666666',
      'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", urlB, headers=headers)
    print(response.text)
    print(response.json().get('data').get('realName').encode('utf-8').decode('gbk'))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    http://192.168.0.100:5000/user/info
    {
    “code”: 0,
    “data”: {
    “id”: “1”,
    “realName”: “\u5f20\u4e09”,
    “userName”: “admin”,
    “userType”: 1
    }
    }
    张三

    server

    @app.route('/book/list', methods=["GET", "POST"])
    def book_detail():
        page = request.args.get('page',default=1,type=int)
        return 'you get is {}'.format(page)
    
    • 1
    • 2
    • 3
    • 4

    client

    urlC = url + '/book/list' + "?page=z"
    print(urlC)
    r = requests.request("GET",urlC)
    print(r.status_code)
    print(r.text)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    传输的不是规定的类型,就会按照default赋值

    http://192.168.0.100:5000/book/list?page=z
    200
    you get is 1

  • 相关阅读:
    基于 SpringBoot+Vue的电影影城管理系统,附源码,数据库
    论文精读(2)—基于稀疏奖励强化学习的机械臂运动规划算法设计与实现(内含实现机器人控制的方法)
    基于SpringBoot的在线小说阅读平台系统
    golang 内存那些事--如何快速分配内存,减少系统 GC (三)
    语义召回进阶之路:从传统到深度学习的搜索革新
    20220910编译ITX-3588J的Buildroot的系统1(编译uboot)
    红队学习之路
    【Linux学习】跨平台开发 Linux + VS2019 环境配置(Ubantu16.04)
    每日4道算法题——第020天
    Transwarp Inceptor中的对象
  • 原文地址:https://blog.csdn.net/weixin_41997073/article/details/134261807