当前位置: 首页>>代码示例>>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;未经允许,请勿转载。