aiohttp.ClientSession

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

85 Examples 7

Page 1 Selected Page 2

Example 1

Project: aiohttp
License: View license
Source File: test_resp.py
async def test_iter_any(test_server, loop):

    data = b'0123456789' * 1024

    async def handler(request):
        buf = []
        async for raw in request.content.iter_any():
            buf.append(raw)
        assert b''.join(buf) == data
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_route('POST', '/', handler)
    server = await test_server(app)

    with aiohttp.ClientSession(loop=loop) as session:
        async with await session.post(server.make_url('/'), data=data) as resp:
            assert resp.status == 200

Example 2

Project: NotSoBot
License: View license
Source File: Utils.py
async def download(link:str, path:str):
  with aiohttp.ClientSession() as session:
    async with session.get(link) as resp:
      data = await resp.read()
      with open(path,"wb") as f:
        f.write(data)

Example 3

Project: mee6
License: View license
Source File: search.py
    async def imgur(self, message, args):
        search = args[0]
        url = "https://api.imgur.com/3/gallery/search/viral"
        headers = {"Authorization": "Client-ID " + IMGUR_ID}
        with aiohttp.ClientSession() as session:
            async with session.get(url,
                                   params={"q": search},
                                   headers=headers) as resp:
                data = await resp.json()

        if data["data"]:
            result = data["data"][0]
            response = result["link"]
        else:
            response = NOT_FOUND

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

Example 4

Project: aiohttp
License: View license
Source File: crawl.py
    def __init__(self, rooturl, loop, maxtasks=100):
        self.rooturl = rooturl
        self.loop = loop
        self.todo = set()
        self.busy = set()
        self.done = {}
        self.tasks = set()
        self.sem = asyncio.Semaphore(maxtasks, loop=loop)

        # connector stores cookies between requests and uses connection pool
        self.session = aiohttp.ClientSession(loop=loop)

Example 5

Project: aioreactive
License: View license
Source File: autocomplete.py
async def search_wikipedia(term):
    """Search Wikipedia for a given term"""
    url = 'http://en.wikipedia.org/w/api.php'

    params = {
        "action": 'opensearch',
        "search": term,
        "format": 'json'
    }

    async with aiohttp.ClientSession() as session:
        async with session.get(url, params=params) as resp:
            return Producer.unit(await resp.text())

Example 6

Project: fishroom
License: View license
Source File: gitter.py
    def listen_message_stream(self, id_blacklist=None):
        id_blacklist = set(id_blacklist or [self.me, ])

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        with aiohttp.ClientSession(loop=loop) as session:
            self.aioclient_session = session

            tasks = [
                asyncio.ensure_future(self.fetch(session, room, id_blacklist))
                for room in self.rooms
            ]
            done, _ = loop.run_until_complete(
                asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
            )
            for d in done:
                if d.exception():
                    raise d.exception()

Example 7

Project: motor
License: View license
Source File: test_aiohttp_gridfs.py
    @asyncio.coroutine
    def request(self, method, path, if_modified_since=None, headers=None):
        headers = headers or {}
        if if_modified_since:
            headers['If-Modified-Since'] = format_date(if_modified_since)

        session = aiohttp.ClientSession()

        try:
            method = getattr(session, method)

            resp = yield from method('http://localhost:8088%s' % path,
                                     headers=headers)
            yield from resp.read()
            return resp
        finally:
            yield from session.close()

Example 8

Project: Red-DiscordBot
License: View license
Source File: owner.py
    def __init__(self, bot):
        self.bot = bot
        self.setowner_lock = False
        self.file_path = "data/red/disabled_commands.json"
        self.disabled_commands = dataIO.load_json(self.file_path)
        self.session = aiohttp.ClientSession(loop=self.bot.loop)

Example 9

Project: asphalt
License: View license
Source File: detector.py
    async def run(self):
        with aiohttp.ClientSession() as session:
            last_modified, old_lines = None, None
            while True:
                logger.debug('Fetching contents of %s', self.url)
                headers = {'if-modified-since': last_modified} if last_modified else {}
                async with session.get(self.url, headers=headers) as resp:
                    logger.debug('Response status: %d', resp.status)
                    if resp.status == 200:
                        last_modified = resp.headers['date']
                        new_lines = (await resp.text()).split('\n')
                        if old_lines is not None and old_lines != new_lines:
                            self.changed.dispatch(old_lines, new_lines)

                        old_lines = new_lines

                await asyncio.sleep(self.delay)

Example 10

Project: feedy
License: View license
Source File: social_share.py
async def _get_pocket_info(url):
    base_url = 'http://widgets.getpocket.com/v1/button?'
    params = [
        ('v', '1'),
        ('count', 'horizontal'),
        ('url', url),
    ]
    async with aiohttp.ClientSession() as session:
        async with session.get(base_url + parse.urlencode(params)) as response:
            html = await response.text()
            soup = BeautifulSoup(html, "html.parser")
            count = int(soup.find('em', {'id': 'cnt'}).text)
            return {
                'pocket_count': count
            }

Example 11

Project: home-assistant
License: View license
Source File: core.py
    @property
    def websession(self):
        """Return an aiohttp session to make web requests."""
        if self._websession is None:
            self._websession = aiohttp.ClientSession(loop=self.loop)

        return self._websession

Example 12

Project: sakia
License: View license
Source File: network.py
    @classmethod
    def from_json(cls, currency, json_data, file_version):
        """
        Load a network from a configured community

        :param str currency: The currency name of a community
        :param dict json_data: A json_data view of a network
        :param NormalizedVersion file_version: the version of the json file
        """
        session = aiohttp.ClientSession()
        nodes = []
        for data in json_data:
            try:
                node = Node.from_json(currency, data, file_version, session)
                nodes.append(node)
            except MalformedDocuementError:
                logging.debug("Could not load node {0}".format(data))
        network = cls(currency, nodes, session)
        return network

Example 13

Project: sanic
License: View license
Source File: utils.py
async def local_request(method, uri, cookies=None, *args, **kwargs):
    url = 'http://{host}:{port}{uri}'.format(host=HOST, port=PORT, uri=uri)
    log.info(url)
    async with aiohttp.ClientSession(cookies=cookies) as session:
        async with getattr(session, method)(url, *args, **kwargs) as response:
            response.text = await response.text()
            response.body = await response.read()
            return response

Example 14

Project: aiohttp
License: View license
Source File: test_client.py
async def test_close_resp_on_error_async_with_session(loop, test_server):
    async def handler(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    server = await test_server(app)

    async with aiohttp.ClientSession(loop=loop) as session:
        with pytest.raises(RuntimeError):
            async with session.get(server.make_url('/')) as resp:
                resp.content.set_exception(RuntimeError())
                await resp.read()

        assert len(session._connector._conns) == 0

Example 15

Project: mee6
License: View license
Source File: stats.py
    async def carbon_stats(self):
        carbon_key = os.getenv('CARBONITEX_KEY')
        if not carbon_key:
            return

        url = 'https://www.carbonitex.net/discord/data/botdata.php?id={}'.format(
            self.mee6.user.id
        )
        with aiohttp.ClientSession() as session:
            payload = {
                'key': carbon_key,
                'servercount': len(self.mee6.servers)
            }
            headers = {'content-type': 'application/json'}
            async with session.post(url, headers=headers,
                                    data=json.dumps(payload)) as resp:
                pass

Example 16

Project: aiolearn
License: View license
Source File: User.py
    async def login(self):
        data = dict(
            userid=self.username,
            userpass=self.password,
        )
        self.session = aiohttp.ClientSession(loop=loop)
        r = await self.session.post(_URL_LOGIN, data=data)
        content = await r.text()
        if len(content) > 120:
            raise RuntimeError(r)

Example 17

Project: mee6
License: View license
Source File: search.py
    async def urban(self, message, args):
        search = args[0]
        url = "http://api.urbandictionary.com/v0/define"
        with aiohttp.ClientSession() as session:
            async with session.get(url, params={"term": search}) as resp:
                data = await resp.json()

        if data["list"]:
            entry = data["list"][0]
            response = "\n **{e[word]}** ```\n{e[definition]}``` \n "\
                       "**example:** {e[example]} \n"\
                       "<{e[permalink]}>".format(e=entry)
        else:
            response = NOT_FOUND
        await self.mee6.send_message(message.channel, response)

Example 18

Project: aiosocks
License: View license
Source File: test_functional.py
    def test_fingerprint_fail(self):
        with fake_socks4_srv(self.loop) as proxy_port:
            addr = aiosocks.Socks4Addr('127.0.0.1', proxy_port)
            fp = (b's\x93\xfd:\xed\x08\x1do\xa9\xaeq9'
                  b'\x1a\xe3\xc5\x7f\x89\xe7l\x10')

            conn = SocksConnector(proxy=addr, proxy_auth=None, loop=self.loop,
                                  remote_resolve=False, verify_ssl=False,
                                  fingerprint=fp)

            with http_srv(self.loop, use_ssl=True) as url:
                with aiohttp.ClientSession(connector=conn,
                                           loop=self.loop) as ses:
                    @asyncio.coroutine
                    def make_req():
                        return (yield from ses.request('get', url=url))

                    with self.assertRaises(aiohttp.FingerprintMismatch):
                        self.loop.run_until_complete(make_req())

Example 19

Project: NotSoBot
License: View license
Source File: Logs.py
async def download(url:str, path:str):
	with aiohttp.ClientSession() as session:
		async with session.get(url) as resp:
			data = await resp.read()
			with open(path, "wb") as f:
				f.write(data)
				f.close()

Example 20

Project: opbeat_python
License: View license
Source File: asyncio.py
    def __init__(self, parsed_url):
        self.check_scheme(parsed_url)

        self._parsed_url = parsed_url
        self._url = parsed_url.geturl()
        loop = asyncio.get_event_loop()
        self.client = aiohttp.ClientSession(loop=loop)

Example 21

Project: peerme
License: View license
Source File: euroix_json.py
    async def _get_via_http(self, url):
        ''' async JSON fetching coro '''
        try:
            async with aiohttp.ClientSession(loop=self.loop) as session:
                with async_timeout.timeout(self.HTTP_TIMEOUT):
                    async with session.get(url) as response:
                        data = await response.text()
        except Exception as e:
            logging.error("{} unable to be fetched: {}".format(
                url, str(e)), exc_info=True,
            )
            data = None

        return url, data

Example 22

Project: peerme
License: View license
Source File: peeringdb_api.py
    async def execute_query(self, endpoint, query):
        '''
            Connect using aiohttp to Rest endpoints

            If we don't get a valid response fire a RestAPIException
        '''
        url = '{}{}'.format(self.PEERINGDB_API, endpoint)
        async with aiohttp.ClientSession() as session:
            async with session.get(url, params=query) as resp:
                if resp.status == 200:
                    result = await resp.json()
                    return result.get('data')
                else:
                    raise peeringdb.RestAPIException(url, query, resp.status)

Example 23

Project: Red-DiscordBot
License: View license
Source File: streams.py
    async def twitch_online(self, stream):
        session = aiohttp.ClientSession()
        url = "https://api.twitch.tv/kraken/streams/" + stream
        header = {'Client-ID': self.settings.get("TWITCH_TOKEN", "")}
        try:
            async with session.get(url, headers=header) as r:
                data = await r.json()
            await session.close()
            if r.status == 400:
                return 400
            elif r.status == 404:
                return 404
            elif data["stream"] is None:
                return False
            elif data["stream"]:
                return True
        except:
            return "error"
        return "error"

Example 24

Project: aiohttp_admin
License: View license
Source File: rest_fixtures.py
    def __init__(self, url, *, admin_prefix=None, headers=None, loop):
        self._loop = loop
        self._url = URL(url)
        self._admin_prefix = admin_prefix or 'admin'
        self._session = aiohttp.ClientSession(loop=loop)
        self._headers = headers or {}

Example 25

Project: feedy
License: View license
Source File: social_share.py
async def _get_hatena_info(url):
    base_url = 'http://b.hatena.ne.jp/entry/json/?'
    params = [
        ('url', url),
    ]
    async with aiohttp.ClientSession() as session:
        async with session.get(base_url + parse.urlencode(params)) as response:
            res = await response.json()
            return {
                'hatebu_count': res.get('count') if res else None,
                'hatebu_related': res.get('related') if res else None,
                'hatebu_bookmarks': res.get('bookmarks') if res else None,
                'hatebu_screenshot': res.get('screenshot') if res else None,
            }

Example 26

Project: hacking-tools
License: View license
Source File: child.py
    def __init__(self,id,url):
        self.id = id+"-"+REQ_KEY
        # print(self.id)
        # self.connection = redis.Connection()
        self.url = url
        self.loop = asyncio.get_event_loop()
        self.client = aiohttp.ClientSession(loop=self.loop)
        self.count = 0 # total request/s

Example 27

Project: sakia
License: View license
Source File: node_manager.py
    async def open_home_page(self):
        try:
            with aiohttp.ClientSession() as session:
                response = await session.get("http://127.0.0.1:9220")
                if response.status == 200:
                    self.ui.web_view.load(QUrl("http://127.0.0.1:9220"))
                    self.ui.web_view.show()
                    self.widget.show()
                else:
                    await QAsyncMessageBox.critical(self.widget, "Local node manager",
                                            "Could not access to local node ui.")
        except aiohttp.ClientError:
            await QAsyncMessageBox.critical(self.widget, "Local node manager",
                                      "Could not connect to node. Please make sure it's running.")

Example 28

Project: sanic
License: View license
Source File: aiohttp_example.py
async def test(request):
    """
    Download and serve example JSON
    """
    url = "https://api.github.com/repos/channelcat/sanic"

    async with aiohttp.ClientSession(loop=loop) as session:
        response = await fetch(session, url)
        return json(response)

Example 29

Project: aiohttp
License: View license
Source File: curl.py
def curl(url):
    session = aiohttp.ClientSession()
    response = yield from session.request('GET', url)
    print(repr(response))

    chunk = yield from response.content.read()
    print('Downloaded: %s' % len(chunk))

    response.close()
    yield from session.close()

Example 30

Project: telegram-uz-bot
License: View license
Source File: scanner.py
    def __init__(self, success_cb, delay=60):
        self.success_cb = success_cb

        self.loop = asyncio.get_event_loop()
        self.delay = delay
        self.session = aiohttp.ClientSession()
        self.client = UZClient(self.session)
        self.__state = dict()
        self.__running = False

Example 31

Project: aiohttp
License: View license
Source File: test_client_session.py
@asyncio.coroutine
def test_request_ctx_manager_props(loop):
    yield from asyncio.sleep(0, loop=loop)  # to make it a task
    with aiohttp.ClientSession(loop=loop) as client:
        ctx_mgr = client.get('http://example.com')

        next(ctx_mgr)
        assert isinstance(ctx_mgr.gi_frame, types.FrameType)
        assert not ctx_mgr.gi_running
        assert isinstance(ctx_mgr.gi_code, types.CodeType)

Example 32

Project: ProxyBroker
License: View license
Source File: proxy_server.py
async def fetch_page(url, conn):
    resp = None
    try:
        with aiohttp.ClientSession(connector=conn) as session:
            async with session.get(url) as response:
                logger.info('url: %s; status: %d' % (url, response.status))
                resp = await response.read()
    except (aiohttp.errors.ClientOSError, aiohttp.errors.ClientResponseError,
            aiohttp.errors.ServerDisconnectedError) as e:
        logger.error('url: %s; error: %r' % (url, e))
    finally:
        return (url, resp)

Example 33

Project: aiohttp
License: View license
Source File: test_client.py
async def test_release_resp_on_normal_exit_from_cm(loop, test_server):
    async def handler(request):
        return web.Response()

    app = web.Application(loop=loop)
    app.router.add_get('/', handler)
    server = await test_server(app)

    async with aiohttp.ClientSession(loop=loop) as session:
        async with session.get(server.make_url('/')) as resp:
            await resp.read()

        assert len(session._connector._conns) == 1

Example 34

Project: NotSoBot
License: View license
Source File: Utils.py
async def bytes_download(link:str):
  with aiohttp.ClientSession() as session:
    async with session.get(link) as resp:
      data = await resp.read()
      b = BytesIO(data)
      b.seek(0)
      return b

Example 35

Project: aiohttp
License: View license
Source File: test_test_utils.py
def test_test_server_context_manager(loop):
    app = _create_example_app(loop)
    with _TestServer(app) as server:
        @asyncio.coroutine
        def go():
            client = aiohttp.ClientSession(loop=loop)
            resp = yield from client.head(server.make_url('/'))
            assert resp.status == 200
            resp.close()
            yield from client.close()

        loop.run_until_complete(go())

Example 36

Project: mee6
License: View license
Source File: search.py
    async def youtube(self, message, args):
        search = args[0]
        url = "https://www.googleapis.com/youtube/v3/search"
        with aiohttp.ClientSession() as session:
            async with session.get(url, params={"type": "video",
                                                "q": search,
                                                "part": "snippet",
                                                "key": GOOGLE_API_KEY}) as resp:
                data = await resp.json()
        if data["items"]:
            video = data["items"][0]
            response = "https://youtu.be/" + video["id"]["videoId"]
        else:
            response = NOT_FOUND

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

Example 37

Project: Nurevam
License: View license
Source File: core.py
    async def check_status(self,link):
        with aiohttp.ClientSession() as session:
            async with session.get(link) as resp:
                if resp.status == 200:
                    return True
                else:
                    return False

Example 38

Project: feedy
License: View license
Source File: feedy.py
async def _fetch_feed(feed_url):
    async with aiohttp.ClientSession() as session:
        async with session.get(feed_url) as response:
            body = await response.text()
            parsed = feedparser.parse(body)
            feed = parsed.feed
            feed_info = {
                'site_title': feed.title,
                'site_subtitle': feed.subtitle,
                'site_url': feed.link,
                'fetched_at': datetime.now()
            }
            entries = parsed.entries
            return feed_info, entries

Example 39

Project: tanner
License: View license
Source File: rfi.py
    @asyncio.coroutine
    def get_rfi_result(self, path):
        rfi_result = None
        yield from asyncio.sleep(1)
        file_name = yield from self.download_file(path)
        if file_name is None:
            return rfi_result
        with open(self.script_dir + file_name) as script:
            script_data = script.read()
        try:
            with aiohttp.ClientSession() as session:
                resp = yield from session.post('http://127.0.0.1:8088/', data=script_data)
                rfi_result = yield from resp.json()
        except aiohttp.ClientError as client_error:
            self.logger.error('Error during connection to php sandbox %s', client_error)
        else:
            yield from resp.release()
            yield from session.close()
        return rfi_result

Example 40

Project: mee6
License: View license
Source File: search.py
    async def twitch(self, message, args):
        search = args[0]
        url = "https://api.twitch.tv/kraken/search/channels"
        with aiohttp.ClientSession() as session:
            async with session.get(url, params={"q": search}) as resp:
                data = await resp.json()

        if data["channels"]:
            channel = data["channels"][0]
            response = "\n**" + channel["display_name"] + "**: " + channel["url"]
            response += " {0[followers]} followers & {0[views]} views".format(
                channel
            )
        else:
            response = NOT_FOUND

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

Example 41

Project: feedy
License: View license
Source File: social_share.py
async def _get_facebook_info(url):
    base_url = 'http://api.facebook.com/method/fql.query?'
    params = [
        ('query', "select total_count,like_count from link_stat where url='{url}'".format(url=url)),
    ]
    async with aiohttp.ClientSession() as session:
        async with session.get(base_url + parse.urlencode(params)) as response:
            html = await response.text()
            soup = BeautifulSoup(html, "html.parser")
            return {
                'facebook_likes': int(soup.find('like_count').text),
                'facebook_count': int(soup.find('total_count').text),
            }

Example 42

Project: OWAPI
License: View license
Source File: blizz_interface.py
async def get_page_body(ctx: HTTPRequestContext, url: str, cache_time=300, cache_404=False) -> str:
    """
    Downloads page body from PlayOverwatch and caches it.
    """
    session = aiohttp.ClientSession(headers={"User-Agent": "OWAPI Scraper/1.0.1"})

    async def _real_get_body(_, url: str):
        # Real function.
        logger.info("GET => {}".format(url))
        async with session.get(url) as req:
            assert isinstance(req, aiohttp.ClientResponse)
            logger.info("GET => {} => {}".format(url, req.status))
            if req.status != 200:
                return None
            return (await req.read()).decode()

    result = await util.with_cache(ctx, _real_get_body, url, expires=cache_time, cache_404=cache_404)
    session.close()
    return result

Example 43

Project: feedy
License: View license
Source File: image_downloader.py
async def _download_and_write_image(image_url, filepath):
    async with aiohttp.ClientSession() as session:
        async with session.get(image_url) as response:
            body = await response.read()
            with open(filepath, 'wb') as f:
                f.write(body)

Example 44

Project: aiovk
License: View license
Source File: drivers.py
    def __init__(self, adress, port, login=None, password=None, timeout=10):
        super().__init__(timeout)
        self.close()
        addr = aiosocks.Socks5Addr(adress, port)
        if login and password:
            auth = aiosocks.Socks5Auth(login, password=password)
        else:
            auth = None
        conn = SocksConnector(proxy=addr, proxy_auth=auth)
        self.session = aiohttp.ClientSession(connector=conn, response_class=CustomClientResponse)

Example 45

Project: discord.py
License: View license
Source File: http.py
    def __init__(self, connector=None, *, loop=None):
        self.loop = asyncio.get_event_loop() if loop is None else loop
        self.connector = connector
        self.session = aiohttp.ClientSession(connector=connector, loop=self.loop)
        self._locks = weakref.WeakValueDictionary()
        self.token = None
        self.bot_token = False

        user_agent = 'DiscordBot (https://github.com/Rapptz/discord.py {0}) Python/{1[0]}.{1[1]} aiohttp/{2}'
        self.user_agent = user_agent.format(__version__, sys.version_info, aiohttp.__version__)

Example 46

Project: python-steemlib
License: View license
Source File: async_monitor.py
@asyncio.coroutine
def start(steem):
    with aiohttp.ClientSession() as session:
        futures = {"time": None, "exchange_price": None, "witness_price": None, "db": None}
        last_witness_update_time, last_witness_price = yield from get_witness_price_feed(steem, account)
        r = yield from steem.db.get_dynamic_global_properties()
        last_time = read_time(r["time"])
        cur_time = last_time
        first_time = True
        steem_price = yield from get_steem_price(session)
        futures["time"] = asyncio.async(asyncio.sleep(0))
        needs_updating = False
        while True:
            ftrs = []
            for f in futures.values():
                if f:
                    ftrs.append(f)
            done, pending = yield from asyncio.wait(ftrs, return_when=asyncio.FIRST_COMPLETED)

            old_futures = {}
            for k, f in futures.items():
                old_futures[k] = futures[k]
            for k, f in old_futures.items():
                if f in done:
                    futures[k] = None
                    if k == "time":
                        futures["time"] = asyncio.async(asyncio.sleep(3))
                        if futures["db"]:
                            futures["db"].cancel()
                        futures["db"]   = yield from steem.db.get_dynamic_global_properties(future=True)
                    elif k == "exchange_price":
                        steem_price = f.result()
                        if abs(1 - last_witness_price / steem_price) > 0.03 and (cur_time - last_witness_update_time) > 60 * 60:
                            if not needs_updating:
                                needs_updating = True
                                print("Price feed needs to be updated due to change in price.")
                                print("Current witness price: {} $/STEEM   Current exchange price: {} $/STEEM".format(last_witness_price, steem_price))
                        else:
                            if needs_updating and cur_time - last_witness_update_time < 24 * 60 * 60:
                                needs_updating = False
                                print("Price feed no longer needs to be updated")

                    elif k == "witness_price":
                        new_last_witness_update_time, new_last_witness_price = f.result()
                        if new_last_witness_update_time != last_witness_update_time:
                            last_witness_update_time = new_last_witness_update_time
                            last_witness_price = new_last_witness_price
                            print("Price feed has been updated")
                            needs_updating = False
                    elif k == "db":
                        r = f.result()
                        cur_time = read_time(r["time"])
                        if first_time or cur_time - last_time > 28:  # seconds
                            first_time = False
                            print("Block number {} at time: {}".format(r["head_block_number"], r["time"]))
                            if needs_updating:
                                print("Price feed still needs updating to {} $/STEEM".format(steem_price))
                            futures["exchange_price"] = asyncio.async(get_steem_price(session))
                            futures["witness_price"] = asyncio.async(get_witness_price_feed(steem, account))
                            last_time = cur_time
                        if cur_time - last_witness_update_time >= 24 * 60 * 60:
                            if not needs_updating:
                                needs_updating = True
                                print("Price feed needs to be updated because it is too old.")
            old_futures = {}

Example 47

Project: mee6
License: View license
Source File: reddit.py
    async def get_posts(self, subreddit):
        """Gets the n last posts of a subreddit

        Args:
            subreddit: Subbredit name
            n: The number of posts you want

        Returns:
            A list of posts
        """

        url = "https://www.reddit.com/r/{}/new.json".format(subreddit)
        posts = []

        try:
            with aiohttp.ClientSession() as session:
                async with session.get(url) as resp:
                    if resp.status == 200:
                        json = await resp.json()
                        posts = json['data']['children']
                        posts = list(map(lambda p: p['data'], posts))
        except Exception as e:
            log.info("Cannot get posts from {}".format(subreddit))
            log.info(e)
            return []

        return posts[:2]

Example 48

Project: discord.py
License: View license
Source File: http.py
    def recreate(self):
        self.session = aiohttp.ClientSession(connector=self.connector, loop=self.loop)

Example 49

Project: feedy
License: View license
Source File: feedy.py
async def _fetch_body(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

Example 50

Project: telegram-uz-bot
License: View license
Source File: client.py
    def __enter__(self):
        self._session = aiohttp.ClientSession()
        return self
See More Examples - Go to Next Page
Page 1 Selected Page 2