课堂上的装饰器:有没有更好的方法

时间:2020-10-14 21:14:33

标签: python

我正在尝试创建一个类来管理给定的API。到目前为止,即使我需要添加一些内容以正确处理错误和输出解析,它也可以正常工作。到目前为止,请参见下面的代码:

class ApiRteClient:

urlAuth = "https://digital.iservices.rte-france.com/token/oauth"
API_URL = "https://digital.iservices.rte-france.com/open_api"

def __init__(self,privateKey):
    self.privateKey = privateKey
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)
            self._expirationDate = credentials["expirationDate"]
            if datetime.now() > self._expirationDate:
                self._getAccessToken()
            else:
                self._accessToken = credentials["accessToken"]
                self.session = self._init_session()
    else:
        self._getAccessToken()

def _init_session(self):

    session = requests.session()
    session.headers.update({'Authorization': 'Bearer ' + self._accessToken})

    return session

def _getAccessToken(self):

    headers = {}
    headers.update({"Authorization": "Basic " + self.privateKey})
    headers.update({"Content-Type": 'application/x-www-form-urlencoded'})
    try:
        response = requests.post(self.urlAuth, headers=headers)
    except:
        response.raise_for_status()

    self._accessToken = json.loads(response.content.decode())["access_token"]
    self._expirationDate = datetime.now() + timedelta(0,json.loads(response.content.decode())["expires_in"])
    tokenInfo = {}
    tokenInfo.update({"accessToken": self._accessToken})
    self.session = self._init_session()
    tokenInfo.update({"expirationDate": self._expirationDate})
    with open('token.pickle', 'wb') as token:
        pickle.dump(tokenInfo, token)

def _request(self,method,uri,**kwargs):

    kwargs['timeout'] = 10

    data = kwargs.get('data', None)
    if data and isinstance(data, dict):
        kwargs['data'] = data



    self.response = getattr(self.session, method)(uri, **kwargs)

    return self._handle_response()

def _handle_response(self):
    return self.response.json()

def _request_api(self,method,path,**kwargs):

    uri = self._create_actual_generation_api_uri(path)

    return self._request(method,uri,**kwargs)

def _get(self, path, **kwargs):

    return self._request_api('get', path, **kwargs)

def _create_actual_generation_api_uri(self,path):

    return self.API_URL + "/actual_generation/" + "v1" + "/" + path

def get_actual_generation_per_production_type(self,**kwargs):

    return self._get("actual_generations_per_production_type", **kwargs)

def get_actual_generation_per_production_type(self,**kwargs):

    return self._get("actual_generations_per_unit", **kwargs)

def get_actual_water_reserves(self,**kwargs):

    return self._get("water_reserves", **kwargs)

def get_actual_generationmix_15min_step(self,**kwargs):

    return self._get("generation_mix_15min_time_scale", **kwargs)

在请求的参数中,我将始终有一个开始日期和结束日期来指示,并且API在天数范围方面有一些限制:7天,1年……取决于方法。

我想包含一些使用户无法管理的内容。例如,对于一个限制为7天的一个月内的请求,请拆分为不同的7天请求。

我想使用带有参数的装饰器,但是还有其他选择吗?

致谢

0 个答案:

没有答案