aiohttp.BasicAuth

Here are the examples of the python api aiohttp.BasicAuth taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

16 Examples 7

Example 1

Project: home-assistant
License: View license
Source File: mjpeg.py
Function: init
    def __init__(self, hass, device_info):
        """Initialize a MJPEG camera."""
        super().__init__()
        self._name = device_info.get(CONF_NAME)
        self._authentication = device_info.get(CONF_AUTHENTICATION)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._mjpeg_url = device_info[CONF_MJPEG_URL]

        self._auth = None
        if self._username and self._password:
            if self._authentication == HTTP_BASIC_AUTHENTICATION:
                self._auth = aiohttp.BasicAuth(
                    self._username, password=self._password
                )

Example 2

Project: waterbutler
License: View license
Source File: provider.py
Function: init
    def __init__(self, auth, credentials, settings):
        super().__init__(auth, credentials, settings)

        self.folder = settings['folder']
        self.verify_ssl = settings['verify_ssl']
        self.url = credentials['host']
        self._auth = aiohttp.BasicAuth(credentials['username'], credentials['password'])

Example 3

Project: mee6
License: View license
Source File: animu.py
Function: get_xml
    async def get_xml(self, nature, name):
        auth = aiohttp.BasicAuth(login = MAL_USERNAME, password = MAL_PASSWORD)
        url = 'http://myanimelist.net/api/{}/search.xml'.format(nature)
        params = {
            'q': name
        }
        with aiohttp.ClientSession(auth=auth) as session:
            async with session.get(url, params=params) as response:
                data = await response.text()
                return data

Example 4

def test_auth_is_set_correctly():
    connection = AIOHttpConnection(http_auth=('user', 'secret'))
    assert connection.session._default_auth == aiohttp.BasicAuth('user', 'secret')

    connection = AIOHttpConnection(http_auth='user:secret')
    assert connection.session._default_auth == aiohttp.BasicAuth('user', 'secret')

Example 5

Project: aiohttp
License: View license
Source File: test_client_request.py
def test_basic_auth_from_url_overriden(make_request):
    req = make_request('get', 'http://[email protected]',
                       auth=aiohttp.BasicAuth('nkim', '1234'))
    assert 'AUTHORIZATION' in req.headers
    assert 'Basic bmtpbToxMjM0' == req.headers['AUTHORIZATION']
    assert 'python.org' == req.host

Example 6

Project: aioauth-client
License: View license
Source File: aioauth_client.py
    def request(self, method, url, params=None, headers=None, timeout=10, loop=None, **aio_kwargs):
        """Request OAuth2 resource."""
        url = self._get_url(url)
        if self.access_token:
            headers = headers or {'Accept': 'application/json'}
            headers['Authorization'] = "Bearer {}".format(self.access_token)
            auth = None
        else:
            auth = BasicAuth(self.client_id, self.client_secret)
            headers = headers or {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            }
        # noinspection PyArgumentList
        return asyncio.wait_for(
            aiorequest(
                method, url, params=params, headers=headers, auth=auth, loop=loop, **aio_kwargs
            ), timeout, loop=loop)

Example 7

Project: Jumper-Cogs
License: View license
Source File: animelist.py
Function: anime
    async def anime(self, ctx, *, name):
        """Fetches info about an anime title!"""
        username = self.credentials["Username"]
        password = self.credentials["Password"]
        anime = name.replace(" ", "_")
        params = {
            'q': anime
                }
        try:
            auth = aiohttp.BasicAuth(login=username, password=password)
            url = 'http://myanimelist.net/api/anime/search.xml?q=' + anime
            with aiohttp.ClientSession(auth=auth) as session:
                async with session.get(url, params=params) as response:
                    data = await response.text()
                    if data == '':
                        await self.bot.say('I didn\'t found anything :cry: ...')
                        return
                    root = ElementTree.fromstring(data)
                    if len(root) == 0:
                        await self.bot.say('Sorry, I found nothing :cry:.')
                    elif len(root) == 1:
                        entry = root[0]
                    else:
                        msg = "**Please choose one by giving its number.**\n"
                        msg += "\n".join(['{} - {}'.format(n+1, entry[1].text) for n, entry in enumerate(root) if n < 10])

                        await self.bot.say(msg)  # Change to await response

                        check = lambda m: m.content in map(str, range(1, len(root)+1))
                        resp = await self.bot.wait_for_message(timeout=15, check=check)
                        if resp is None:
                            return

                        entry = root[int(resp.content)-1]

                    switcher = [
                        'english',
                        'score',
                        'type',
                        'episodes',
                        'volumes',
                        'chapters',
                        'status',
                        'start_date',
                        'end_date',
                        'synopsis'
                        ]

                    msg = '\n**{}**\n\n'.format(entry.find('title').text)
                    for k in switcher:
                        spec = entry.find(k)
                        if spec is not None and spec.text is not None:
                            msg += '**{}** {}\n'.format(k.capitalize()+':', html.unescape(spec.text.replace('<br />', '')))
                    msg += 'http://myanimelist.net/anime/{}'.format(entry.find('id').text)

                    await self.bot.say(msg)
        except:
            await self.bot.say("Your username or password is not correct." + "\n" +
                               "You need to create an account on myanimelist.net ." +
                               "\n" + "If you have an account use **<p>animeset** to set your credentials")

Example 8

Project: Jumper-Cogs
License: View license
Source File: animelist.py
Function: manga
    async def manga(self, ctx, *, name):
        """Fetches info about an manga title!"""
        username = self.credentials["Username"]
        password = self.credentials["Password"]
        manga = name.replace(" ", "_")
        params = {
            'q': manga
                }
        try:
            auth = aiohttp.BasicAuth(login=username, password=password)
            url = 'http://myanimelist.net/api/manga/search.xml?q=' + manga
            with aiohttp.ClientSession(auth=auth) as session:
                async with session.get(url, params=params) as response:
                    data = await response.text()
                    if data == '':
                        await self.bot.say('I didn\'t found anything :cry: ...')
                        return
                    root = ElementTree.fromstring(data)
                    if len(root) == 0:
                        await self.bot.say('Sorry, I found nothing :cry:.')
                    elif len(root) == 1:
                        entry = root[0]
                    else:
                        msg = "**Please choose one by giving its number.**\n"
                        msg += "\n".join(['{} - {}'.format(n+1, entry[1].text) for n, entry in enumerate(root) if n < 10])

                        await self.bot.say(msg)  # Change to await response

                        check = lambda m: m.content in map(str, range(1, len(root)+1))
                        resp = await self.bot.wait_for_message(timeout=15, check=check)
                        if resp is None:
                            return

                        entry = root[int(resp.content)-1]

                    switcher = [
                        'english',
                        'score',
                        'type',
                        'episodes',
                        'volumes',
                        'chapters',
                        'status',
                        'start_date',
                        'end_date',
                        'synopsis'
                        ]

                    msg = '\n**{}**\n\n'.format(entry.find('title').text)
                    for k in switcher:
                        spec = entry.find(k)
                        if spec is not None and spec.text is not None:
                            msg += '**{}** {}\n'.format(k.capitalize()+':', html.unescape(spec.text.replace('<br />', '')))
                    msg += 'http://myanimelist.net/manga/{}'.format(entry.find('id').text)

                    await self.bot.say(msg)
        except:
            await self.bot.say("Your username or password is not correct." + "\n" +
                               "You need to create an account on myanimelist.net ." +
                               "\n" + "If you have an account use **<p>animeset** to set your credentials")

Example 9

Project: mee6
License: View license
Source File: search.py
Function: manga
    async def manga(self, message, args):
        search = args[0]
        auth = aiohttp.BasicAuth(login=MAL_USERNAME, password=MAL_PASSWORD)
        url = 'http://myanimelist.net/api/manga/search.xml'
        params = {'q': search}
        with aiohttp.ClientSession(auth=auth) as session:
            async with session.get(url, params=params) as response:
                data = await response.text()

        if data == "":
            await self.mee6.send_message(message.channel,
                                         "I didn't find anything :cry:...")
            return

        root = ElementTree.fromstring(data)
        if len(root) == 0:
            await self.mee6.send_message(message.channel,
                                         "Sorry, I didn't find anything :cry:"
                                         "...")
        elif len(root) == 1:
            entry = root[0]
        else:
            msg = "**Please choose one by giving its number**\n"
            msg += "\n".join(['{} - {}'.format(n+1, entry[1].text)
                              for n, entry in enumerate(root) if n < 10])

            await self.mee6.send_message(message.channel, msg)

            def check(m): return m.content in map(str, range(1, len(root)+1))
            resp = await self.mee6.wait_for_message(author=message.author,
                                                    check=check,
                                                    timeout=20)
            if resp is None:
                return

            entry = root[int(resp.content)-1]

        switcher = [
            'english',
            'score',
            'type',
            'episodes',
            'volumes',
            'chapters',
            'status',
            'start_date',
            'end_date',
            'synopsis'
            ]

        msg = '\n**{}**\n\n'.format(entry.find('title').text)
        for k in switcher:
            spec = entry.find(k)
            if spec is not None and spec.text is not None:
                msg += '**{}** {}\n'.format(k.capitalize()+':',
                                            html.unescape(spec.text.replace(
                                                '<br />',
                                                ''
                                            )))
        msg += 'http://myanimelist.net/manga/{}'.format(entry.find('id').text)

        await self.mee6.send_message(message.channel,
                                     msg)

Example 10

Project: mee6
License: View license
Source File: search.py
Function: anime
    async def anime(self, message, args):
        search = args[0]
        auth = aiohttp.BasicAuth(login=MAL_USERNAME, password=MAL_PASSWORD)
        url = 'http://myanimelist.net/api/anime/search.xml'
        params = {'q': search}
        with aiohttp.ClientSession(auth=auth) as session:
            async with session.get(url, params=params) as response:
                data = await response.text()

        if data == "":
            await self.mee6.send_message(message.channel,
                                         "I didn't find anything :cry:...")
            return

        root = ElementTree.fromstring(data)
        if len(root) == 0:
            await self.mee6.send_message(message.channel,
                                         "Sorry, I didn't find anything :cry:"
                                         "...")
        elif len(root) == 1:
            entry = root[0]
        else:
            msg = "**Please choose one by giving its number**\n"
            msg += "\n".join(['{} - {}'.format(n+1, entry[1].text)
                              for n, entry in enumerate(root) if n < 10])

            await self.mee6.send_message(message.channel, msg)

            def check(m): return m.content in map(str, range(1, len(root)+1))
            resp = await self.mee6.wait_for_message(author=message.author,
                                                    check=check,
                                                    timeout=20)
            if resp is None:
                return

            entry = root[int(resp.content)-1]

        switcher = [
            'english',
            'score',
            'type',
            'episodes',
            'volumes',
            'chapters',
            'status',
            'start_date',
            'end_date',
            'synopsis'
            ]

        msg = '\n**{}**\n\n'.format(entry.find('title').text)
        for k in switcher:
            spec = entry.find(k)
            if spec is not None and spec.text is not None:
                msg += '**{}** {}\n'.format(k.capitalize()+':',
                                            html.unescape(spec.text.replace(
                                                '<br />',
                                                ''
                                            )))
        msg += 'http://myanimelist.net/anime/{}'.format(entry.find('id').text)

        await self.mee6.send_message(message.channel,
                                     msg)

Example 11

Project: elasticsearch-py-async
License: View license
Source File: connection.py
Function: init
    def __init__(self, host='localhost', port=9200, http_auth=None,
            use_ssl=False, verify_certs=False, ca_certs=None, client_cert=None,
            client_key=None, loop=None, **kwargs):
        super().__init__(host=host, port=port, **kwargs)

        self.loop = asyncio.get_event_loop() if loop is None else loop

        if http_auth is not None:
            if isinstance(http_auth, str):
                http_auth = tuple(http_auth.split(':', 1))

            if isinstance(http_auth, (tuple, list)):
                http_auth = aiohttp.BasicAuth(*http_auth)

        self.session = aiohttp.ClientSession(
            auth=http_auth,
            connector=aiohttp.TCPConnector(
                loop=self.loop,
                verify_ssl=verify_certs,
                conn_timeout=self.timeout,

            )
        )

        self.base_url = 'http%s://%s:%d%s' % (
            's' if use_ssl else '',
            host, port, self.url_prefix
        )

Example 12

Project: home-assistant
License: View license
Source File: generic.py
    def __init__(self, hass, device_info):
        """Initialize a generic camera."""
        super().__init__()
        self.hass = hass
        self._authentication = device_info.get(CONF_AUTHENTICATION)
        self._name = device_info.get(CONF_NAME)
        self._still_image_url = device_info[CONF_STILL_IMAGE_URL]
        self._still_image_url.hass = hass
        self._limit_refetch = device_info[CONF_LIMIT_REFETCH_TO_URL_CHANGE]

        username = device_info.get(CONF_USERNAME)
        password = device_info.get(CONF_PASSWORD)

        if username and password:
            if self._authentication == HTTP_DIGEST_AUTHENTICATION:
                self._auth = HTTPDigestAuth(username, password)
            else:
                self._auth = aiohttp.BasicAuth(username, password=password)
        else:
            self._auth = None

        self._last_url = None
        self._last_image = None

Example 13

Project: aiohttp
License: View license
Source File: client_auth.py
Function: go
async def go(loop):
    async with aiohttp.ClientSession(
            auth=aiohttp.BasicAuth('andrew', 'password'),
            loop=loop) as session:
        await fetch(session)

Example 14

Project: Nurevam
License: View license
Source File: myanimelist.py
Function: get_data
    async def get_data(self, category, name):
        with aiohttp.ClientSession(auth=aiohttp.BasicAuth(login=utils.secret["MAL_USERNAME"],
                                                          password=utils.secret["MAL_PASSWORD"])) as session:
            async with session.get('http://myanimelist.net/api/{}/search.xml?q={}'.format(category, name)) as resp:
                return (await resp.read())

Example 15

Project: balrog
License: View license
Source File: cmd.py
Function: run_agent
async def run_agent(loop, balrog_api_root, balrog_username, balrog_password, telemetry_api_root, sleeptime=30,
                    once=False, raise_exceptions=False):
    auth = aiohttp.BasicAuth(balrog_username, balrog_password)

    while True:
        try:
            logging.debug("Looking for active scheduled changes...")
            resp = await client.request(balrog_api_root, "/scheduled_changes/rules", auth=auth, loop=loop)
            sc = (await resp.json())["scheduled_changes"]
            resp.close()
            logging.debug("Found %s", len(sc))
            for change in sc:
                logging.debug("Processing change %s", change["sc_id"])
                ready = False

                # Figure out if the change is ready, which is type-specific.
                if change["telemetry_uptake"]:
                    # TODO: maybe replace this with a simple client.request()...
                    current_uptake = await get_telemetry_uptake(change["telemetry_product"], change["telemetry_channel"], loop=loop)
                    ready = telemetry_is_ready(change, current_uptake)
                elif change["when"]:
                    # "when" is to-the-millisecond timestamp that gets stored as an int.
                    # It needs to be converted back to a float before it can be compared
                    # against other timestamps.
                    ready = time_is_ready(change, time.time())
                else:
                    logging.debug("Unknown change type!")

                # If it *is* ready, enact it!
                if ready:
                    logging.debug("Change %s is ready, enacting", change["sc_id"])
                    endpoint = "/scheduled_changes/rules/{}/enact".format(change["sc_id"])
                    resp = await client.request(balrog_api_root, endpoint, method="POST", auth=auth, loop=loop)
                    resp.close()
                else:
                    logging.debug("Change %s is not ready", change["sc_id"])

        except:
            logging.error("Encountered exception:", exc_info=True)
            if raise_exceptions:
                raise
        finally:
            if not once:
                await asyncio.sleep(sleeptime)

        if once:
            return

Example 16

Project: colorcore
License: View license
Source File: providers.py
Function: init
    def __init__(self, base_url, api_key, api_secret, fallback_provider, loop):
        self._base_url = base_url
        self._auth = aiohttp.BasicAuth(api_key, api_secret)
        self._fallback_provider = fallback_provider
        self._loop = loop