此处我们使用github的token进行简单测试验证
# coding=utf-8 import requests BASE_URL = "https://api.github.com" def construct_url(endpoint): return ‘/‘.join([BASE_URL, endpoint]) def basic_auth(): ‘‘‘ 基本认证 :return: ‘‘‘ response = requests.get(construct_url(‘user‘), auth=(‘reblue520‘,‘reblue520‘)) print response.text print response.status_code print response.request.headers def basic_oauth(): # 添加github中添加的token认证 headers = {‘Authorization‘: ‘token 748fa57d10‘} # user/emails response = requests.get(construct_url(‘user/emails‘), headers=headers) print response.request.headers print response.text print response.status_code from requests.auth import AuthBase class GithubAuth(AuthBase): # 自定义auth,对aut进行优化 def __init__(self, token): self.token = token def __call__(self, r): # requests 加 headers信息 r.headers[‘Authorization‘] = ‘ ‘.join([‘token‘, self.token]) return r def oath_advanced(): auth = GithubAuth(‘748fa57d10‘) response = requests.get(construct_url(‘user/emails‘), auth=auth) print response.text if __name__ == ‘__main__‘: # basic_auth() # basic_oauth() oath_advanced()
原文地址:https://www.cnblogs.com/reblue520/p/11230938.html
时间: 2024-10-27 16:27:40