Python类写

时间:2019-06-04 15:34:53

标签: python

我正在尝试实现父WebContentClass和子类,以从实际网站实体获取HTTP响应。下面有一些高级代码,我想知道人们对于以一种OOP方式实现这一目标的巧妙方式有何看法。

import requests
from onelogin.api.client import OneLoginClient


class WebContent(object):

    def __init__(self, client_id, client_secret, login, password, sub_domain, app_id, app_url):

        self.client_id = client_id
        self.client_secret = client_secret
        self.app_id = app_id
        self.app_url = app_url
        self.login = login
        self.password = password
        self.sub_domain = sub_domain

    def _login(self):
        client = OneLoginClient(self.client_id, self.client_secret)
        saml = client.get_saml_assertion(self.login,
                                         self.password,
                                         self.app_id,
                                         self.sub_domain)
        saml_data = saml.saml_response

        session = requests.Session()
        saml_payload = {'SAMLResponse': saml_data}
        session.post("{}/sso/response".format(self.app_url), saml_payload)
        return session

    def get_content(self, endpoint):
        if endpoint:
            session = self._login()
            result = session.get(endpoint)
            session.close()
            return result.content


class WebMarketingContent(WebContent):
    def get_endpoint(self, entity_id):
        base_url = "{app_url}/{entity_id}?{query_params}"
        params = '&entity_id={}'.format(entity_id)
        return base_url.format(app_url=self.app_url, query_params=params)


class WebEducationContent(WebContent):
    def get_endpoint(self, entity_id):
        base_url = "{app_url}/category/adhoc_element/{entity_id}?{query_params}"
        params = '&entity_id={}'.format(entity_id)
        return base_url.format(app_url=self.app_url, query_params=params)


if __name__ == '__main__':
    web_marketing_content = WebMarketingContent('client_id',
                                                'client_secret',
                                                'email',
                                                'password',
                                                'sub_domain',
                                                'app_id',
                                                'app_url')

    endpoint = web_marketing_content.get_endpoint(123)
    result = web_marketing_content.get_content(endpoint)

0 个答案:

没有答案