其他分享
首页 > 其他分享> > 接口自动化基础(三)requests库

接口自动化基础(三)requests库

作者:互联网

文档: https://requests.readthedocs.io/en/master/

get请求demo

import requests
def test_requests():
    r = requests.get('https://httpbin.testing-studio.com/get',
                     params={
                         "a": 1,
                         "b": 2
                     })
    print(r)
    print(r.status_code)
    print(r.json())
    print(r.text)
    print(res.elapsed.total_seconds())

post请求demo

def test_requests():
    r = requests.post('https://httpbin.testing-studio.com/post',
                     data={
                         "a": 1,
                         "b": 2
                     })

文件上传demo

def test_upload():
    r = requests.post('https://httpbin.testing-studio.com/post', 
                        files={
                        'file':open('__init__.py', 'rb')
                        })

header和cookie

def test_upload():
    r = requests.post('https://httpbin.testing-studio.com/post',
                      files={'file': open('__init__.py', 'rb')},
                      headers={'Content-Type': 'application/plain'},
                      cookie={'name':'bigllxx','fdsfdasfasdfasdf':'fdsfasdfasdf'}
                      )

超时及认证

r = requests.get('https://httpbin.testing-studio.com/', timeout=10)
r = requests.get('https://httpbin.testing-studio.com/', anth=('usname','passwd'))

代理使用

proxies={
    'http': 'http://1.1.1.1:1111'
    'https': 'http://2.2.2.2:2222'
}
r = requests.get('https://httpbin.testing-studio.com/', proxies=proxies)

json path断言

import jsonpath
#传统断言
assert r.json()['errcode'] == 0
#json path 借鉴Xpath形成的json定位体系,但是业界尚未统一标准,大致写法如下:
from jsonpath import jsonpath
jsonpath(r, '$..tag[?(@.name=="青铜")]')[0]['id']  # r是被定位的json对象,右边是jsonpath通用定位

标签:httpbin,testing,接口,studio,https,自动化,requests,post
来源: https://www.cnblogs.com/bigllxx/p/15205469.html