一、获取header方法

getheader.py

# _*_ coding:utf-8 _*_

import json,requests
from  Common import readConfig

def get_token():
    "获取登录token"
    login=readConfig.Read_Config()                                        #类实例化
    login_url = login.get_info('Login', 'login_host')                     #获取登录url
    headers = json.loads(login.get_info('Login', 'login_headers'))        #登录headers
    data =json.loads(login.get_info('Login', 'login_account'))            #登录账号、密码
    r = requests.request('POST', login_url, json=data, headers=headers)   #登录接口请求
    return r.json()['access_token']                                       #返回登录token

def host_headers():
    headers={}
    headers['x-key-hash']=readConfig.Read_Config().get_info('HTTP', 'x-key-hash')   #获取x-key-hash
    headers['Content-Type']='application/json;charset=utf-8'                        #添加headers
    headers['Authorization']='Bearer '+get_token()                                  #添加headers
    return headers

if __name__ == '__main__':
    print(host_headers())

 

二、requests请求封装

configHttp.py

# _*_ coding:utf-8 _*_

import requests
from Common import getheader
from requests import exceptions

def req(method,url,**kwargs):
    "封装http请求方法"
    headers = getheader.host_headers()             #调用header方法
    try:
        result = requests.request(method,url,headers=headers,**kwargs)    #调用request方法
        return result
    except exceptions.Timeout:
        return {"请求超时"}
    except exceptions.InvalidURL:
        return {"非法url"}
    except exceptions.HTTPError:
        return {"http请求错误"}
    except Exception as e:
        return {"错误原因:%s" % e}

if __name__ == '__main__':
    url='服务器地址'
    params={"jobid":""}
    r=req('GET',url,params=params)
    print(r.json())

 

版权声明:本文为airb原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/airb/p/13323641.html