关于python接口基础到进阶随笔

想了很久,闲来无事,今天想了下还是总结了下写下来,部分参考官方源码理解,还有就是这么久的理解,

如果觉得有帮助请记得点赞

先讲下接口url组成拿后台服务为例 通常一个后台请求url格式:

http://www.gamma.tools.hw.com/PipelineSvr/v1/exeplan?plan=plan_002&scheme=scheme_001

当然你也可以直接nslookup www.gamma.tools.hw.com 解析域名加上端口,直接去请求后台像这样,前提你知道环境部署在哪台linux服务器的tomcat 上;

http:10.22.22.34:8039/PipelineSvr/v1/exeplan?plan=plan_002&scheme=scheme_001

这个组成格式为:域名(ip:port)/服务名称/子服务层/子服务下面哪个功能接口,这里是后台pipelineSvr的v1服务的计划方案接口

1.首先介绍接口常用四大类型get,post,delete,put这些method 你可能会想为什么会被定义出来这么多种呢,当然为了规范开发接口统一认识,假如现在我们一个团队get现在大家都公认为查询接口,post为新建接口,从无到有,delete删除服务数据接口,put为修改参数接口,比如更改下某个参数值有了这些规范开发看到方法就知道你想执行什么操作了,即使我对你的服务不熟悉我也可以判断大概这个借口属于那个操作类型;其次不同服务之间对接的数据获取很多都是走接口的,这是就意味着接口数据格式要统一,一般默认响应为json,如果你来个raw,我来个text,数据拿过来不能直接用,还要处理转换那就坑大了;

2.有了规范我们需要进一步,对服务资源进行管理标识,划分服务以及服务业务层,和定义各个服务的编号,每个服务各自状态码类型错误的含义指的是什么比如pipelineSvr现在接口请求响应了一个错误的状态码"DEV-PipelineSeverPlatform-Service-500"表示DEV表示是开发环境下,PipelineSeverPlatform-Service表示pipelineSvr的平台服务,500表示内部响应错误,直接不去找说明就知道什么原因,开发的效率有效提升问题定位迅速;

3.接下来我们深入认识每个类型接口区分特点:

GET :一般典型格式为http://www.gamma.tools.hw.com/PipelineSvr/v1/exeplan?plan=plan_002&scheme=scheme_001

用?隔开参数param,每个请求键值对用&符号隔开,直接地址栏可以看见参数也就意味着参数安全性低

还有一种写法是http://www.gamma.tools.hw.com/PipelineSvr/v1/exeplan?

在param里面以键值对形式存放在表单里面提交

key  xxx    value xxx

key2 xx value2 xxx

以表单formdata形式提交,postman用过的就不多说了

POST: 

典型格式:http:///www.gamma.tools.hw.com/PipelineSvr/DetailPipeline

有请求头header的要带请求header,请求不需要的不带,参数存放于body中,get是存放param里面的这点注意区分,还有一个就是参数类型到底是表单格式还是json要注意开发接口规范怎么要求的,要application/x-www-form-urlencoded给x-www-form-urlencoded,要json给json

不然接口数据获取异常

body格式也是键值对:

key  xxx    value xxx

key2 xx value2 xxx

PUT请求同post

Delete:

典型也是类似get请求:

http://www.gamma.tools.hw.com/PipelineSvr/listjobid?jobid=xx&pipelineid=xxx

还有一种是直接走body传参数的格式,如body为json类型参数的

http://www.gamma.tools.hw.com/PipelineSvr/listjobidkey

body里面如下

{“jobId”: "xxx",

"pipelineId": "xxx"

}

谈到接口还会遇到文件上传,鉴权(基本,摘要),代理设置,请求超时,响应时间获取等等

下面进入逐个样例介绍

get post 例:

import requests

 
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

'Accept-Encoding': 'gzip, deflate, compress',

'Accept-Language': 'en-us;q=0.5,en;q=0.3',

'Cache-Control': 'max-age=0',

'Connection': 'keep-alive',

'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}

 
s = requests.Session()

s.headers.update(headers)

# s.auth = ('superuser', '123')

s.get('https://www.kuaipan.cn/account_login.htm')

 
_URL = 'http://www.kuaipan.cn/index.php'

s.post(_URL, params={'ac':'account', 'op':'login'},

data={'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'})

r = s.get(_URL, params={'ac':'zone', 'op':'taskdetail'})

print(r.json()

 超时与异常

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
 

cookie与会话session

import requests

 
url = 'http://httpbin.org/cookies'

cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}

# 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。

r = requests.get(url, cookies=cookies)

  

     session 

import requests

import json

     session=requests.Session()

#发送json类型数据用户json序列化data

    res=session.request("post",url=xx,data=json.dumps({'some': 'data'}),header={'Accept': 'text/html,application/xhtml+xml,application/xml})

    pythondict=res.json()

鉴权身份认证一般无权限401

1.基本身份认证(HTTP Basic Auth):

import requests
from requests.auth import HTTPBasicAuth
 
r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))
# r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd'))    # 简写
print(r.json())
2.另一种非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的:

requests.get(URL, auth=HTTPDigestAuth('user', 'pass'))

代理设置:

import requests
 
proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}
 
requests.get("http://www.zhidaow.com", proxies=proxies)
 

.

文件上传

import requests
 
url = 'http://127.0.0.1:5000/upload'
files = {'file': open('/home/lyb/sjzl.mpg', 'rb')}
#files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))}     #显式的设置文件名
 
r = requests.post(url, files=files)
print(r.text)
更加方便的是,你可以把字符串当着文件进行上传:

import requests
 
url = 'http://127.0.0.1:5000/upload'
files = {'file': ('test.txt', b'Hello Requests.')}     #必需显式的设置文件名
 
r = requests.post(url, files=files)
print(r.text)
 

响应时间以及其他参数获取:

 r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd')    

r.elapsed.total_seconds() # 获取接口响应开始请求到完成需要的时间

r.status_code #响应状态码
r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
#*特殊方法*#
r.json() #Requests中内置的JSON解码器
r.raise_for_status() #失败请求(非200响应)抛出异常 

原文地址:https://www.cnblogs.com/SunshineKimi/p/10540223.html