美文网首页
Python结合Postman获取特定返回值

Python结合Postman获取特定返回值

作者: 莫依痕 | 来源:发表于2018-04-11 16:21 被阅读0次

    1、通过postman设置接口内容,发出请求,返回正确结果。

    postman设置接口,正确返回数据.png

    2、点击Save下面的“Code”按钮,选择Python->Requests,导出Python代码

    点击Code,获取Python代码.png

    3、我用的是Sublime Text编辑器,导出的Python文件需要导入requests相关文件,否则会报错。大家可以根据报错提示,提示缺什么内容就去找什么内容。可以从下面这个链接去查找Python第三方库。

    https://www.lfd.uci.edu/~gohlke/pythonlibs/

    4、把.whl的文件下载下来后修改为.zip,然后解压后文件放到python的lib目录下,我设置的路径在“E:\Python3.6.4\Lib”。需要以下5个文件解压后,获取文件夹里是py文件的那个文件(没有数字,名字比较短的那个文件夹)放到Python的lib目录下。

    image.png
    image.png

    5、postman获取的代码放到sublime text后,添加需要实现的功能。

    image.png

    6、具体功能见以下代码。

    import requests
    import json
    
    url = "http://xxx/apis"
    
    querystring = {"$limit":"100","$count":"true"}
    headers = {
        'Content-Type': "application/json;charset=utf-8",
        'Authorization': "DEBUG userid=123456,realm=xx",
        'Cache-Control': "no-cache",
        'Postman-Token': "0a668021-d810-a3dd-85b2-e8e4ebbe3705"
        }
    
    response = requests.request("GET", url, headers=headers, params=querystring)
    
    print(response.text)
    
    project = []
    
    res = json.loads(response.text)
    for d in res["items"]:
        names = [d["name"]]
        for x in d["hosts"]:
            names.append(x)
        for y in d["uris"]:
            names.append(y)
        names.append(d["upstream_url"])
        project.append(" ".join(names))
    
    f = open("C:/Users/ND/Desktop/testApiList.txt", "w+")
    f.write("API名称\t请求host\t请求Path\t后端服务URL\n")
    for i in range(0, len(project)):
        f.write(project[i] + "\n")
    f.close()
    print("文件创建成功")
    
    

    第二次看这个文章,在pycharm使用这个代码,遇到新的问题

    1、代码中有中文注释和输出里有中文,无法正常通过
    SyntaxError: Non-ASCII character '\xe8' in file D:/workplace/batchGetData/venv/com/get_org_id.py on line 26, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
    2、接口返回数据是中文,内容存成string可以正常中文输出,但是放入list输出就一直是乱码
    [u'\u6d4b\u8bd5\u521b\u5efa\u5b66\u6821 490079345147']
    3、刚开始代码复制到pycharm,会报requests找不到
    解决方法:
    1、在开头代码第一行输入:# -*- coding: UTF-8 -*-,代码中有中文就可以正常使用
    2、把最后的list输出用这个形式输出:print json.dumps(list, encoding="UTF-8", ensure_ascii=False)
    结果就正常了:"测试创建学校 490079345147"
    3、去修改了python的地址,就可以正常导入requests库了

    修改python正确位置.png

    相关文章

      网友评论

          本文标题:Python结合Postman获取特定返回值

          本文链接:https://www.haomeiwen.com/subject/vafzhftx.html