• requests(五)


    声明:

    本文来自柠檬班py30期学员,处理公司接口请求时遇到的问题及相应的解决方案。

    以本文作为记录,方便其它学员遇到类似问题时,可以参考解决。

    背景

    尝试用python语言的requests库,编写脚本登陆公司的APP。

    遇到的问题

    问题1:

           将手机号、密码数据传入后,始终登陆不成功,经过与开发沟通后知道需要签名才能登陆。

    问题2:

           签名算法写好后仍然无法登陆成功。

          通过后台日志发现是传入数据格式不正确导致的,公司的post接口入参方式为form-data , 而我是用json串的方式入参的。

    解决方案中涉及到的知识点

    1、签名时需要的时间戳

    import time
    
    t = time.time()
    
    print (t)            #原始时间数据
    
    print (int(t))          #秒级时间戳
    
    print (int(round(t * 1000)))   #毫秒级时间戳
    
    print (int(round(t * 1000000))) #微秒级时间戳
    
    # 取出来的时间戳想验证时间是否正确,可以百度(https://tool.lu/timestamp/)在线时间戳工具转换看看


    2、签名时需要的MD5加密

    import hashlib
    data = “待加密数据”
    m = hashlib.md5(data)

    Tips:

    如遇报错:Unicode-objects must be encoded before hashing

    解决方法:

    此处必须为encode,但是python3此处默认为unicode,所以修改如下:

     hashlib.md5(data.encode(encoding='UTF-8')).hexdigest()

    注:编码方式有很多种,此处用UTF-8编码举例,实际中可按照编码不同自己选择


    3、发送http请求时,以form-data的格式作为requests的参数

    使用requests的requests_toolbelt模块 ,需要自行安装。

    from requests_toolbelt import MultipartEncoder
    import requests
    
    m = MultipartEncoder(
        fields={'field0': 'value',
               'field1': 'value',
                'field2': ('文件名称', open('文件地址/file.py', 'rb'), 'text/plain')}
        )
    
    r = requests.post('http://httpbin.org/post',
                      data=m,
                      headers={'Content-Type': m.content_type})

    requests官方网站地址:https://www.osgeo.cn/requests/user/quickstart.html#more-complicated-post-requests

    requests_toolbelt官方网站地址:https://toolbelt.readthedocs.io/en/latest/user.html

     

    最终处理代码

  • 相关阅读:
    CodeForces 58C Trees
    【转】二分匹配题集
    HDU2604 Queuing
    HDU1281 棋盘游戏
    HDU3360 National Treasures
    HDU2444 The Accomodation of Students
    HDU1498 50 years, 50 colors
    HDU1068 Girls and Boys
    【转】常用的latex宏包
    【转】网络流题集
  • 原文地址:https://www.cnblogs.com/Simple-Small/p/13224636.html
Copyright © 2020-2023  润新知