Python课程写

2024-04-25 06:19:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现一个父WebContentClass和子类,以便从实际的网站实体获取http响应。下面有一些高级代码,我想知道人们对用面向对象的方式实现这一点有什么看法

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)

Tags: selfclientidappurlgetsecretsession