Python aiohttp.CookieJar() Examples

The following are 12 code examples of aiohttp.CookieJar(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp , or try the search function .
Example #1
Source File: spider.py    From Amipy with MIT License 6 votes vote down vote up
def _init_session(self):
        _safe = self.settings.SPIDER_COOKIES_UNSAFE_MODE
        path = self.settings.SPIDER_COOKIES_LOAD_PATH
        _c_cookies = self.settings.SPIDER_COOKIES_CUSTOM
        jar = aiohttp.CookieJar(unsafe=_safe)
        if _c_cookies:
            cookies = _c_cookies
        else:
            cookies = None
        self.conn = aiohttp.TCPConnector(limit=self.settings.CONCURRENCY)
        self.session = aiohttp.ClientSession(connector=self.conn,
                                             cookies=cookies,
                                             cookie_jar=jar)
        if path:
            if os.path.exists(path):
                try:
                    self.session.cookie_jar.load(path)
                    if cookies:
                        self.session.cookie_jar.update_cookies(cookies)
                except:
                    return
                self.logger.debug(f'Loaded [{self.name}] cookie jar.') 
Example #2
Source File: __main__.py    From aiounifi with MIT License 5 votes vote down vote up
def main(host, username, password, port, site, sslcontext=False):
    """Main function."""
    LOGGER.info("Starting aioUniFi")

    websession = aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar(unsafe=True))

    controller = await unifi_controller(
        host=host,
        username=username,
        password=password,
        port=port,
        site=site,
        session=websession,
        sslcontext=sslcontext,
        callback=signalling_callback,
    )

    if not controller:
        LOGGER.error("Couldn't connect to UniFi controller")
        await websession.close()
        return

    await controller.initialize()
    await controller.sites()
    await controller.site_description()
    controller.start_websocket()

    try:
        while True:
            await asyncio.sleep(1)

    except asyncio.CancelledError:
        pass

    finally:
        controller.stop_websocket()
        await websession.close() 
Example #3
Source File: http_client.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def __init__(self, store_credentials):
        self._store_credentials = store_credentials
        self.bearer = None
        self.user = None
        self._cookie_jar = CookieJar()
        self._auth_lost_callback = None

        super().__init__(cookie_jar=self._cookie_jar) 
Example #4
Source File: utils.py    From pytest-sanic with Apache License 2.0 5 votes vote down vote up
def __init__(self, app, loop=None,
                 host='127.0.0.1',
                 protocol=None,
                 ssl=None,
                 scheme=None,
                 **kwargs):
        if not isinstance(app, Sanic):
            raise TypeError("app should be a Sanic application.")

        if loop:
            warnings.warn("passing through `loop` is deprecated.",
                          DeprecationWarning,
                          stacklevel=2)
        self._app = app
        # we should use '127.0.0.1' in most cases.
        self._host = host
        self._ssl = ssl
        self._scheme = scheme
        self._protocol = HttpProtocol if protocol is None else protocol
        self._closed = False
        self._server = TestServer(
                    self._app, loop=loop,
                    protocol=self._protocol, ssl=self._ssl,
                    scheme=self._scheme)
        cookie_jar = CookieJar(unsafe=True)
        self._session = ClientSession(cookie_jar=cookie_jar,
                                      **kwargs)
        # Let's collect responses objects and websocket objects,
        # and clean up when test is done.
        self._responses = []
        self._websockets = [] 
Example #5
Source File: api.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, server_login=None):
		self.server_login = server_login
		self.cookie_jar = aiohttp.CookieJar()
		self.session = None
		self.site = None
		self.key = None
		self.map_info_page_size = 1 
Example #6
Source File: mxkarmaapi.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, app):
		self.api_url = 'https://karma.mania-exchange.com/api2'
		self.app = app
		self.cookie_jar = aiohttp.CookieJar()
		self.session = None
		self.key = None
		self.activated = False 
Example #7
Source File: utils.py    From synapse with Apache License 2.0 5 votes vote down vote up
def getHttpSess(self, auth=None, port=None):
        '''
        Get an aiohttp ClientSession with a CookieJar.

        Args:
            auth (str, str): A tuple of username and password information for http auth.
            port (int): Port number to connect to.

        Notes:
            If auth and port are provided, the session will login to a Synapse cell
            hosted at localhost:port.

        Returns:
            aiohttp.ClientSession: An aiohttp.ClientSession object.
        '''

        jar = aiohttp.CookieJar(unsafe=True)
        conn = aiohttp.TCPConnector(ssl=False)

        async with aiohttp.ClientSession(cookie_jar=jar, connector=conn) as sess:

            if auth is not None:

                if port is None: # pragma: no cover
                    raise Exception('getHttpSess requires port for auth')

                user, passwd = auth
                async with sess.post(f'https://localhost:{port}/api/v1/login',
                                     json={'user': user, 'passwd': passwd}) as resp:
                    retn = await resp.json()
                    self.eq('ok', retn.get('status'))
                    self.eq(user, retn['result']['name'])

            yield sess 
Example #8
Source File: http.py    From fortnitepy with MIT License 5 votes vote down vote up
def __init__(self, client: 'Client', *,
                 connector: aiohttp.BaseConnector = None) -> None:
        self.client = client
        self.connector = connector
        self._jar = aiohttp.CookieJar()
        self.headers = {}
        self.device_id = self.client.auth.device_id

        self.create_connection() 
Example #9
Source File: test_utils.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def __init__(self, app_or_server, *, scheme=sentinel, host=sentinel,
                 cookie_jar=None, server_kwargs=None, loop=None, **kwargs):
        if isinstance(app_or_server, BaseTestServer):
            if scheme is not sentinel or host is not sentinel:
                raise ValueError("scheme and host are mutable exclusive "
                                 "with TestServer parameter")
            self._server = app_or_server
        elif isinstance(app_or_server, Application):
            scheme = "http" if scheme is sentinel else scheme
            host = '127.0.0.1' if host is sentinel else host
            server_kwargs = server_kwargs or {}
            self._server = TestServer(
                app_or_server,
                scheme=scheme, host=host, **server_kwargs)
        else:
            raise TypeError("app_or_server should be either web.Application "
                            "or TestServer instance")
        self._loop = loop
        if cookie_jar is None:
            cookie_jar = aiohttp.CookieJar(unsafe=True, loop=loop)
        self._session = ClientSession(loop=loop,
                                      cookie_jar=cookie_jar,
                                      **kwargs)
        self._closed = False
        self._responses = []
        self._websockets = [] 
Example #10
Source File: test_utils.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def __init__(self, app_or_server, *, scheme=sentinel, host=sentinel,
                 cookie_jar=None, server_kwargs=None, loop=None, **kwargs):
        if isinstance(app_or_server, BaseTestServer):
            if scheme is not sentinel or host is not sentinel:
                raise ValueError("scheme and host are mutable exclusive "
                                 "with TestServer parameter")
            self._server = app_or_server
        elif isinstance(app_or_server, Application):
            scheme = "http" if scheme is sentinel else scheme
            host = '127.0.0.1' if host is sentinel else host
            server_kwargs = server_kwargs or {}
            self._server = TestServer(
                app_or_server,
                scheme=scheme, host=host, **server_kwargs)
        else:
            raise TypeError("app_or_server should be either web.Application "
                            "or TestServer instance")
        self._loop = loop
        if cookie_jar is None:
            cookie_jar = aiohttp.CookieJar(unsafe=True, loop=loop)
        self._session = ClientSession(loop=loop,
                                      cookie_jar=cookie_jar,
                                      **kwargs)
        self._closed = False
        self._responses = []
        self._websockets = [] 
Example #11
Source File: rapidleech.py    From BotHub with Apache License 2.0 4 votes vote down vote up
def get_direct_ip_specific_link(link: str):
    # https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/extractor/openload.py#L246-L255
    # https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/extractor/googledrive.py#L16-L27
    GOOGLE_DRIVE_VALID_URLS = r"(?x)https?://(?:(?:docs|drive)\.google\.com/(?:(?:uc|open)\?.*?id=|file/d/)|video\.google\.com/get_player\?.*?docid=)(?P<id>[a-zA-Z0-9_-]{28,})"
    # https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/extractor/googledrive.py#L16-L27
    dl_url = None
    
    if re.search(GOOGLE_DRIVE_VALID_URLS, link):
        file_id = re.search(GOOGLE_DRIVE_VALID_URLS, link).group("id")
        async with aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar()) as session:
            step_zero_url = "https://drive.google.com/uc?export=download&id={}".format(file_id)
            http_response = await session.get(step_zero_url, allow_redirects=False)
            if "location" in http_response.headers:
                # in case of small file size, Google downloads directly
                file_url = http_response.headers["location"]
                if "accounts.google.com" in file_url:
                    dl_url = {
                        "err": "Private Google Drive URL"
                    }
                else:
                    dl_url = {
                        "url": file_url
                    }
            else:
                # in case of download warning page
                http_response_text = await http_response.text()
                response_b_soup = BeautifulSoup(http_response_text, "html.parser")
                warning_page_url = "https://drive.google.com" + response_b_soup.find("a", {"id": "uc-download-link"}).get("href")
                file_name_and_size = response_b_soup.find("span", {"class": "uc-name-size"}).text
                http_response_two = await session.get(warning_page_url, allow_redirects=False)
                if "location" in http_response_two.headers:
                    file_url = http_response_two.headers["location"]
                    if "accounts.google.com" in file_url:
                        dl_url = {
                            "err": "Private Google Drive URL"
                        }
                    else:
                        dl_url = {
                            "url": file_url,
                            "name": file_name_and_size
                        }
                else:
                    dl_url = {
                        "err": "Unsupported Google Drive URL"
                    }
    else:
        dl_url = {
            "err": "Unsupported URL. Try @transload"
        }
    return dl_url 
Example #12
Source File: config_flow.py    From unifiprotect with MIT License 4 votes vote down vote up
def async_step_user(self, user_input=None):
        """Handle a flow initiated by the user."""
        if user_input is None:
            return await self._show_setup_form(user_input)

        errors = {}

        session = async_create_clientsession(
            self.hass, cookie_jar=CookieJar(unsafe=True)
        )

        unifiprotect = UpvServer(
            session,
            user_input[CONF_HOST],
            user_input[CONF_PORT],
            user_input[CONF_USERNAME],
            user_input[CONF_PASSWORD],
        )

        try:
            unique_id = await unifiprotect.unique_id()
        except NotAuthorized:
            errors["base"] = "connection_error"
            return await self._show_setup_form(errors)
        except NvrError:
            errors["base"] = "nvr_error"
            return await self._show_setup_form(errors)

        entries = self._async_current_entries()
        for entry in entries:
            if entry.data[CONF_ID] == unique_id:
                return self.async_abort(reason="server_exists")

        return self.async_create_entry(
            title=unique_id,
            data={
                CONF_ID: unique_id,
                CONF_HOST: user_input[CONF_HOST],
                CONF_PORT: user_input[CONF_PORT],
                CONF_USERNAME: user_input.get(CONF_USERNAME),
                CONF_PASSWORD: user_input.get(CONF_PASSWORD),
                CONF_SCAN_INTERVAL: user_input.get(CONF_SCAN_INTERVAL),
                CONF_SNAPSHOT_DIRECT: user_input.get(CONF_SNAPSHOT_DIRECT),
                CONF_IR_ON: user_input.get(CONF_IR_ON),
                CONF_IR_OFF: user_input.get(CONF_IR_OFF),
            },
        )