當前位置: 首頁>>代碼示例>>Python>>正文


Python aiohttp.request方法代碼示例

本文整理匯總了Python中aiohttp.request方法的典型用法代碼示例。如果您正苦於以下問題:Python aiohttp.request方法的具體用法?Python aiohttp.request怎麽用?Python aiohttp.request使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在aiohttp的用法示例。


在下文中一共展示了aiohttp.request方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: make_request

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def make_request(self):
        retries = 0
        while retries < self.max_retries:
            try:
                resp = yield from aiohttp.request(self.method, self.url,
                                                  **self.request_kwargs)
                return (yield from self._handle_response(resp))
            except Exception as exc:
                retries += 1
                error = dict(
                    url=self.url,
                    params=self.request_kwargs.get('params'),
                    message='Request failed, retrying.',
                    retries_left=self.max_retries-retries,
                )
                if self.debug:
                    error['callback'] = repr(self.callback)
                    error['exception'] = repr(exc)
                    error['traceback'] = traceback.format_exc()
                    sys.stderr.write('{}\n'.format(json.dumps(error)))
            yield from asyncio.sleep(1)
        else:
            error['message'] = 'Maximum retries exceeded for url, giving up.'
            sys.stderr.write('{}\n'.format(json.dumps(error)))
            return 
開發者ID:jjjake,項目名稱:iamine,代碼行數:27,代碼來源:requests.py

示例2: _handle_request

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def _handle_request(self, method, request, requested_url):
        """Handle proxy requests."""
        requested_url = requested_url or "/"
        headers = request.headers.copy()
        headers["Host"] = request.host
        headers["X-Real-Ip"] = request.remote
        headers["X-Forwarded-For"] = request.remote
        headers["X-Forwarded-Proto"] = request.scheme
        post_data = await request.read()
        async with aiohttp.request(
            method,
            self.proxy_url + requested_url,
            params=request.query,
            data=post_data,
            headers=headers,
        ) as resp:
            content = await resp.read()
            headers = resp.headers.copy()
            return aiohttp.web.Response(
                body=content, status=resp.status, headers=headers
            ) 
開發者ID:doudz,項目名稱:homeassistant-zigate,代碼行數:23,代碼來源:adminpanel.py

示例3: _send_to_external_chat

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def _send_to_external_chat(self, bot, event, config):
        if event.from_bot:
            # don't send my own messages
            return

        event_timestamp = event.timestamp

        conversation_id = event.conv_id
        conversation_text = event.text

        user_full_name = event.user.full_name
        user_id = event.user_id

        url = config["HUBOT_URL"] + conversation_id
        payload = {"from" : str(user_id.chat_id), "message" : conversation_text}
        headers = {'content-type': 'application/json'}

        connector = aiohttp.TCPConnector(verify_ssl=False)
        asyncio.ensure_future(
            aiohttp.request('post', url, data = json.dumps(payload), headers = headers, connector=connector)
        ).add_done_callback(lambda future: future.result()) 
開發者ID:hangoutsbot,項目名稱:hangoutsbot,代碼行數:23,代碼來源:hubot.py

示例4: _search_comic

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def _search_comic(bot, event, terms):
    request = yield from aiohttp.request('get', "https://relevantxkcd.appspot.com/process?%s" % urllib.parse.urlencode({
        "action": "xkcd",
        "query": " ".join(terms),
    }))
    raw = yield from request.read()
    values = [row.strip().split(" ")[0] for row in raw.decode().strip().split("\n")]
    
    weight = float(values.pop(0))
    values.pop(0) # selection - ignore?
    comics = [int(i) for i in values]
    num = comics.pop(0)
    
    msg = 'Most relevant xkcd: #%d (relevance: %.2f%%)\nOther relevant comics: %s' % (num, weight*100, ", ".join("#%d" % i for i in comics))
    
    # get info and upload image if necessary
    yield from _get_comic(bot, num)
    
    yield from bot.coro_send_message(event.conv.id_, msg)
    yield from _print_comic(bot, event, num) 
開發者ID:hangoutsbot,項目名稱:hangoutsbot,代碼行數:22,代碼來源:xkcd.py

示例5: get_flag

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def get_flag(base_url, cc):
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    resp = yield from aiohttp.request('GET', url)
    with contextlib.closing(resp):
        if resp.status == 200:
            image = yield from resp.read()
            return image
        elif resp.status == 404:
            raise web.HTTPNotFound()
        else:
            raise aiohttp.HttpProcessingError(
                code=resp.status, message=resp.reason,
                headers=resp.headers)


# BEGIN FLAGS2_ASYNCIO_EXECUTOR 
開發者ID:fluentpython,項目名稱:notebooks,代碼行數:18,代碼來源:flags2_asyncio_executor.py

示例6: http_get

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def http_get(url):
    res = yield from aiohttp.request('GET', url)
    if res.status == 200:
        ctype = res.headers.get('Content-type', '').lower()
        if 'json' in ctype or url.endswith('json'):
            data = yield from res.json()  # <1>
        else:
            data = yield from res.read()  # <2>
        return data

    elif res.status == 404:
        raise web.HTTPNotFound()
    else:
        raise aiohttp.errors.HttpProcessingError(
            code=res.status, message=res.reason,
            headers=res.headers) 
開發者ID:fluentpython,項目名稱:notebooks,代碼行數:18,代碼來源:flags3_asyncio.py

示例7: __process

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def __process(self,request):
        for i in request['d']['results']:
            url = i['Url'].encode('ascii','ignore').decode()
            self.uniq_urls.add(url)
            up = urlparse(url)
            x = up.netloc
            if not x.count(':'):
                if up.scheme == "https":
                    x+=":443"
                else:
                    x+=":80"

            self.uniq_hosts.add(x)
        if len(request['d']['results']) < self.parameters['$top']:
            return False
        else:
            return True 
開發者ID:nnewsom,項目名稱:webbies,代碼行數:19,代碼來源:Bing.py

示例8: search

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def search(self,query,page):
        params = {
            "Query":query,
            "$skip": self.parameters["$top"] * page
        }
        params.update(self.parameters)
        try:
            r = yield from aiohttp.request(
                    'get',
                    self.url,
                    params=params,
                    headers=self.headers
                    )
            results = yield from r.json()
            yield from self.__process(results)
        except aiohttp.ClientError as client_error:
            print("Error: {emsg}".format(emsg=client_error)) 
開發者ID:nnewsom,項目名稱:webbies,代碼行數:19,代碼來源:Bing.py

示例9: get_balance

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def get_balance(session, account):
        """
        Get balance.

        Args:
            session (TastyAPISession): An active and logged-in session object against which to query.
            account (TradingAccount): The account_id to get balance on.
        Returns:
            dict: account attributes
        """
        url = '{}/accounts/{}/balances'.format(
            session.API_url,
            account.account_number
        )

        async with aiohttp.request('GET', url, headers=session.get_request_headers()) as response:
            if response.status != 200:
                raise Exception('Could not get trading account balance info from Tastyworks...')
            data = (await response.json())['data']
        return data 
開發者ID:boyan-soubachov,項目名稱:tastyworks_api,代碼行數:22,代碼來源:trading_account.py

示例10: get_positions

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def get_positions(session, account):
        """
        Get Open Positions.

        Args:
            session (TastyAPISession): An active and logged-in session object against which to query.
            account (TradingAccount): The account_id to get positions on.
        Returns:
            dict: account attributes
        """
        url = '{}/accounts/{}/positions'.format(
            session.API_url,
            account.account_number
        )

        async with aiohttp.request('GET', url, headers=session.get_request_headers()) as response:
            if response.status != 200:
                raise Exception('Could not get open positions info from Tastyworks...')
            data = (await response.json())['data']['items']
        return data 
開發者ID:boyan-soubachov,項目名稱:tastyworks_api,代碼行數:22,代碼來源:trading_account.py

示例11: get_history

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def get_history(session, account):
        """
        Get live Orders.

        Args:
            session (TastyAPISession): An active and logged-in session object against which to query.
            account (TradingAccount): The account_id to get history on.
        Returns:
            dict: account attributes
        """
        url = '{}/accounts/{}/transactions'.format(
            session.API_url,
            account.account_number
        )

        async with aiohttp.request('GET', url, headers=session.get_request_headers()) as response:
            if response.status != 200:
                raise Exception('Could not get history info from Tastyworks...')
            data = (await response.json())['data']
        return data 
開發者ID:boyan-soubachov,項目名稱:tastyworks_api,代碼行數:22,代碼來源:trading_account.py

示例12: load_watchlists

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def load_watchlists(self):
        request_url = '{}/public_watchlists?include_synthetic=true'.format(
            BASE_URL
        )

        async with aiohttp.request('GET', request_url) as resp:
            if resp.status != 200:
                raise Exception('Could not get public asset watchlists')
            data = await resp.json()

        data = data['public_watchlists']
        for entry in data:
            list_data = entry['entries']
            wlist = Watchlist.from_list(list_data)
            wlist.name = entry['name']
            wlist.slug = entry['slug']
            self.watchlists[wlist.slug] = wlist

        return self 
開發者ID:boyan-soubachov,項目名稱:tastyworks_api,代碼行數:21,代碼來源:watchlists.py

示例13: qks_rex

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def qks_rex(bot, ev):
    match = ev.match
    msg = f'騎空士爪巴遠點\n{qksimg}'
    res = 'http://'+match.group(0)
    async with aiohttp.TCPConnector(verify_ssl=False) as connector:
        async with aiohttp.request(
            'GET',
            url=res,
            allow_redirects=False,
            connector=connector,
        ) as resp:
            h = resp.headers
            s = resp.status
    if s == 301 or s == 302:
        if 'granbluefantasy.jp' in h['Location']:
            await bot.send(ev, msg, at_sender=True)
            await util.silence(ev, 60) 
開發者ID:Ice-Cirno,項目名稱:HoshinoBot,代碼行數:19,代碼來源:antiqks.py

示例14: test_request_hook

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def test_request_hook(app: Flask, aio: AioHTTP):
    """Test for Flask request hook"""
    @app.before_request
    def before_request():
        request.foo = []
        request.foo.append('a')

    @app.after_request
    def after_request(response):
        request.foo.append('c')
        return response

    @app.teardown_request
    def teardown_request(exc):
        request.foo.append('d')

    @app.route('/hook')
    @async
    def hook():
        request.foo.append('b')

        return ''.join(request.foo)

    with Server(app, aio) as server:
        assert 'ab' == server.get('/hook') 
開發者ID:Hardtack,項目名稱:Flask-aiohttp,代碼行數:27,代碼來源:test_aiowebsocket.py

示例15: update_nicknames

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import request [as 別名]
def update_nicknames(self):
        nickfile = os.path.join(self.setting["dirname"], "nickname3.csv")
        try:
            async with aiohttp.request('GET', self.Nicknames_csv) as resp:
                if resp.status != 200:
                    raise ServerError(
                        "bad server response. code: "+str(resp.status))
                restxt = await resp.text()
                with open(nickfile, "w", encoding="utf-8-sig") as f:
                    f.write(restxt)
        except aiohttp.ClientError as e:
            raise RuntimeError('錯誤'+str(e))
        with open(nickfile, encoding="utf-8-sig") as f:
            csv = f.read()
            for line in csv.split("\n")[1:]:
                row = line.split(",")
                for col in row:
                    self.nickname_dict[col] = (row[0], row[1]) 
開發者ID:yuudi,項目名稱:yobot,代碼行數:20,代碼來源:jjc_consult.py


注:本文中的aiohttp.request方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。