How to use the aiohttp.ClientSession function in aiohttp

To help you get started, we’ve selected a few aiohttp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github instana / python-sensor / tests / frameworks / test_aiohttp.py View on Github external
async def test():
            with async_tracer.start_active_span('test'):
                async with aiohttp.ClientSession() as session:
                    return await self.fetch(session, testenv["wsgi_server"] + "/500")
github foglamp / FogLAMP / python / foglamp / services / core / interest_registry / change_callback.py View on Github external
return

    category_value = await cfg_mgr.get_category_all_items(category_name)
    payload = {"category" : category_name, "items" : category_value}
    headers = {'content-type': 'application/json'}

    # for each microservice interested in category_name, notify change
    for i in interest_records:
        # get microservice management server info of microservice through service registry
        try: 
            service_record = ServiceRegistry.get(idx=i._microservice_uuid)[0]
        except service_registry_exceptions.DoesNotExist:
            _LOGGER.exception("Unable to notify microservice with uuid %s as it is not found in the service registry", i._microservice_uuid)
            continue
        url = "{}://{}:{}/foglamp/change".format(service_record._protocol, service_record._address, service_record._management_port)
        async with aiohttp.ClientSession() as session:
            try:
                async with session.post(url, data=json.dumps(payload, sort_keys=True), headers=headers) as resp:
                    result = await resp.text()
                    status_code = resp.status
                    if status_code in range(400, 500):
                        _LOGGER.error("Bad request error code: %d, reason: %s", status_code, resp.reason)
                    if status_code in range(500, 600):
                        _LOGGER.error("Server error code: %d, reason: %s", status_code, resp.reason)
            except Exception as ex:
                _LOGGER.exception("Unable to notify microservice with uuid %s due to exception: %s", i._microservice_uuid, str(ex))
                continue
github Godavaru / Godavaru / main.py View on Github external
+ "===============\n" \
                          + 'Logged in as:\n' \
                          + str(self.user) + '\n' \
                          + '===============\n' \
                          + 'Ready for use.\n' \
                          + f'Servers: `{len(self.guilds)}`\n' \
                          + f'Users: `{len(self.users)}`\n' \
                          + '===============\n' \
                          + f'Loaded up `{len(self.commands)}` commands in `{len(self.cogs)}` cogs in `{(datetime.datetime.now() - self.start_time).total_seconds()}` seconds.\n' \
                          + '==============='
        print(startup_message.replace('`', ''))
        self.webhook.send(startup_message)
        if not hasattr(self, 'uptime'):
            self.uptime = datetime.datetime.utcnow()
        self.weeb_types = await self.weeb.get_types()
        self.session = aiohttp.ClientSession()
github lu-ci / apex-sigma-core / sigma / modules / utilities / misc / other / event / spooktober / sweets.py View on Github external
disc_img = canv.text_image(f'#{target.discriminator}', 34)
    full_nam = Image.new(
        'RGBA',
        (
            name_img.width + disc_img.width,
            max([name_img.height, disc_img.height])
        ),
        (0, 0, 0, 0)
    )
    full_nam.paste(name_img, (0, 0))
    full_nam.paste(disc_img, (name_img.width, 0))
    full_nam = ImageCompositor.resize(full_nam, width=152)
    canv.stick(cmd.resource('img/user/name.png'), (378, 247))
    canv.stick(full_nam, (402, 246 + int((42 - full_nam.height) / 2.125)))

    async with aiohttp.ClientSession() as session:
        async with session.get(str(target.avatar_url_as(format='png', size=128))) as data:
            avatar_raw = await data.read()

    avatar_img = Image.open(io.BytesIO(avatar_raw))
    avatar_img = ImageCompositor.resize(avatar_img, 95, 95)
    canv.stick(avatar_img, (431, 137), cmd.resource('img/user/av_mask.png'))
    canv.stick(cmd.resource('img/user/av_rim.png'), (431, 137))

    response = discord.Embed(color=0x361683)
    response.set_author(name=f'{target.display_name}\'s Jar of Sweets', icon_url=user_avatar(target))
    file_name = f'sweets_{pld.msg.id}.png'
    file = discord.File(canv.to_bytes(), file_name)
    response.set_image(url=f'attachment://{file_name}')
    await pld.msg.channel.send(embed=response, file=file)
github RasaHQ / rasa / rasa / core / channels / console.py View on Github external
async def send_message_receive_block(server_url, auth_token, sender_id, message):
    payload = {"sender": sender_id, "message": message}

    url = "{}/webhooks/rest/webhook?token={}".format(server_url, auth_token)
    async with aiohttp.ClientSession() as session:
        async with session.post(url, json=payload, raise_for_status=True) as resp:
            return await resp.json()
github hivesolutions / netius / examples / http / http_players.py View on Github external
async def get_player(player_id, player_name):
    endpoint = "/commonplayerinfo"
    params = dict(playerid = player_id)
    url = BASE_URL + endpoint

    print("Getting player %s" % player_name)

    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers = HEADERS, params = params) as resp:
            data = await resp.text()
            print(data)

    async with aiofiles.open(
            "players/%s.json" % player_name.replace(" ", "_"), "w"
        ) as file:
        await file.write(data)
github hail-is / hail / batch / batch / worker.py View on Github external
async def post_job_complete_1(self, job, run_duration):
        body = {
            'status': await job.status()
        }

        start_time = time_msecs()
        delay_secs = 0.1
        while True:
            try:
                async with aiohttp.ClientSession(
                        raise_for_status=True, timeout=aiohttp.ClientTimeout(total=60)) as session:
                    await session.post(
                        deploy_config.url('batch-driver', '/api/v1alpha/instances/job_complete'),
                        json=body, headers=self.headers)
                    return
            except asyncio.CancelledError:  # pylint: disable=try-except-raise
                raise
            except Exception as e:
                if isinstance(e, aiohttp.ClientResponseError) and e.status == 404:   # pylint: disable=no-member
                    raise
                log.exception(f'failed to mark {job} complete, retrying')

            # unlist job after 3m or half the run duration
            now = time_msecs()
            elapsed = now - start_time
            if (job.id in self.jobs and
github rocketgram / rocketgram / rocketgram / connectors / aiohttpconnector.py View on Github external
def __init__(self, *, timeout: int = 35, api_url: str = API_URL):
        self._api_url = api_url
        self._session = aiohttp.ClientSession(loop=asyncio.get_event_loop())
        self._timeout = timeout
github fssqawj / QAServer / parser / htmlfetch.py View on Github external
async def downloader(loop, url, time_out=100):
    with async_timeout.timeout(time_out):
        async with aiohttp.ClientSession(loop=loop) as session:
            async with session.get(url, headers=header) as response:
                content = await response.content.read()
                return content
github Uzbek-Developers / uzdevsbot / aiotg / bot.py View on Github external
def session(self):
        if not self._session:
            self._session = aiohttp.ClientSession()
        return self._session