zoukankan      html  css  js  c++  java
  • 【python接口自动化-requests库】【三】优化重构requests方法

    一、重构post请求方法

      上一张讲了如何使用requests库发送post请求,但是有时候,我们写脚本,不可能这么简单,代码完全不可复用,重复工作,那我们是不是可以想象,把我们的get,post请求,分别分装起来呢,等我们要使用的时候就直接调用好了。

      废话不说,直接实例。

    二、实例

    1.我们先抓取一个接口,这边我直接抓了一个app接口,使用charles抓包。就用它了。如何抓包略。

    2.代码实例

    定义一个发送post的函数,传url,data参数, 返回 结果,最后调用这个函数

    def send_post(url,data):
    
        response = requests.post(url=url,data=data)
    
        return response.text

    send_post(api_url,data)

    3.完整的代码,ps:api自己抓的

    # coding:utf-8
    
    import requests
    
    test_url = "http://app.imolly.top/chaohuasuan/appNative/resource/systemConfig"
    
    data = {
        "channel":"2",
        "imei":"352100070950797",
        "os":"1",
        "version":"1.0"
    }
    
    def send_post(url,data):
    
        response = requests.post(url=url,data=data)
    
        return response.text
    
    print send_post(test_url,data)

    结果->

    三、格式化json

    我们得到的json数值的时候,发现是一长串,跟我们实际看到的json格式好像不一样,那么如何格式化呢?

    首先我们要引入json库,把返回的数据先得到json,然后使用dumps方法,这个方法比较重要的是indent,indent=2 说明每行空两格

    import json
    def send_post(url,data):

    response = requests.post(url=url,data=data).json()

    return json.dumps(response,indent=2)

    结果->

  • 相关阅读:
    LSMW TIPS
    Schedule agreement and Delfor
    Running VL10 in the background 13 Oct
    analyse idoc by creation date
    New Journey Prepare
    EDI error
    CBSN NEWS
    Listen and Write 18th Feb 2019
    Microsoft iSCSI Software Target 快照管理
    通过 Microsoft iSCSI Software Target 提供存储服务
  • 原文地址:https://www.cnblogs.com/totoro-cat/p/10001832.html
Copyright © 2011-2022 走看看