本文整理匯總了Python中aiohttp.Timeout方法的典型用法代碼示例。如果您正苦於以下問題:Python aiohttp.Timeout方法的具體用法?Python aiohttp.Timeout怎麽用?Python aiohttp.Timeout使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類aiohttp
的用法示例。
在下文中一共展示了aiohttp.Timeout方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: fetch_image
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def fetch_image(self, session, relative, image_url):
fname = self.file_api.get_file_name(image_url)
p = os.path.join(relative, fname)
fetched = False
try:
with aiohttp.Timeout(self.timeout):
async with session.get(image_url) as r:
if r.status == 200 and self.file_api.get_file_name(r.url) == fname:
c = await r.read()
if c:
with open(self.file_api.to_abs(p), "wb") as f:
f.write(c)
fetched = True
except FileNotFoundError as ex:
self.logger.error("{0} is not found.".format(p))
except concurrent.futures._base.TimeoutError as tx:
self.logger.warning("{0} is timeouted.".format(image_url))
except Exception as ex:
self.logger.warning("fetch image is failed. url: {0}, cause: {1}".format(image_url, str(ex)))
return fetched
示例2: _must_post
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def _must_post(self, api, data=None, json=None, timeout=10, **kwargs):
if data is not None:
kwargs['data'] = data
elif json is not None:
kwargs['json'] = json
else:
kwargs['data'] = {}
kwargs['timeout'] = timeout
try:
r = requests.post(api, **kwargs)
return r
except requests.exceptions.Timeout:
logger.error("Timeout requesting Gitter")
except KeyboardInterrupt:
raise
except:
logger.exception("Unknown error requesting Gitter")
return None
示例3: fetch
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def fetch(self, session, room, id_blacklist):
url = self._stream_api.format(room=room)
while True:
# print("polling on url %s" % url)
try:
with aiohttp.Timeout(300):
async with session.get(url, headers=self.headers) as resp:
while True:
line = await resp.content.readline()
line = bytes.decode(line, 'utf-8').strip()
if not line:
continue
msg = self.parse_jmsg(room, json.loads(line))
if msg.sender in id_blacklist:
continue
self.send_to_bus(msg)
except asyncio.TimeoutError:
pass
except:
raise
示例4: fetch
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def fetch(url, retry=0):
proxy = 'http://{}'.format(Proxy.get_random()['address'])
headers = {'user-agent': get_user_agent()}
conn = aiohttp.ProxyConnector(proxy=proxy)
js_url = gen_js_url(url)
try:
with aiohttp.ClientSession(connector=conn) as session:
with aiohttp.Timeout(TIMEOUT):
async with session.get(url, headers=headers) as resp:
html_text = await resp.text()
async with session.get(js_url, headers=headers) as resp:
js_data = await resp.json()
except:
retry += 1
if retry > 5:
raise CrawlerError()
await asyncio.sleep(1)
return await fetch(url, retry=retry)
return html_text, js_data
示例5: fetch
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def fetch(retry=0):
proxy = 'http://{}'.format(Proxy.get_random()['address'])
headers = {'user-agent': get_user_agent()}
conn = aiohttp.ProxyConnector(proxy=proxy)
url = 'http://httpbin.org/ip'
try:
with aiohttp.ClientSession(connector=conn) as session:
with aiohttp.Timeout(TIMEOUT):
async with session.get(url, headers=headers) as resp:
return await resp.json()
except (ProxyConnectionError, TimeoutError):
try:
p = Proxy.objects.get(address=proxy)
if p:
p.delete()
except DoesNotExist:
pass
retry += 1
if retry > 5:
raise TimeoutError()
await asyncio.sleep(1)
return await fetch(retry=retry)
示例6: get_glitter_text
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def get_glitter_text(gif_text):
"""
Screen scrape glitter text
"""
with aiohttp.Timeout(10):
async with aiohttp.ClientSession() as session:
async with session.get(GLITTER_TEXT_URL % urllib.parse.quote(gif_text.replace("'", ""))) as page_response:
html = await page_response.text()
soup = BeautifulSoup(html, "html.parser")
box = soup.find("textarea", {"id": "dLink"})
gif_text_area = str(box)
gif_url = gif_text_area.replace(
'<textarea class="field" cols="12" id="dLink" onclick="this.focus();this.select()" readonly="">',
"",
1).replace('</textarea>', "", 1)
return await util.download_file(gif_url)
示例7: queue_message
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def queue_message(self, channel_id:str, msg):
embed = '0'
if type(msg) == discord.Embed:
embed = '1'
msg = jsonpickle.encode(msg)
else:
msg = str(msg)
message_id = random.randint(0, 1000000)
payload = {'key': 'verysecretkey', 'id': message_id, 'channel_id': channel_id, 'message': msg, 'embed': embed}
try:
with aiohttp.Timeout(15):
async with self.session.post('http://ip:port/queue', data=payload) as r:
return True
except (asyncio.TimeoutError, aiohttp.errors.ClientConnectionError, aiohttp.errors.ClientError):
await asyncio.sleep(5)
return
except Exception as e:
print('queue error: '+str(e))
示例8: get_queue
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def get_queue():
payload = {'key': ''}
try:
with aiohttp.ClientSession() as session:
with aiohttp.Timeout(15):
async with session.post('http://ip:port/queued', data=payload) as resp:
load = await resp.json()
queue = {}
for s in load:
queue[s] = int(load[s][2])
q = {}
for key in sorted(queue, key=lambda k: queue[k], reverse=False):
q[key] = load[key]
return q
except Exception as e:
print(e)
return {}
示例9: call
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def call(self, endpoint, method='POST', raw=False, *args, **kwargs):
if 'headers' not in kwargs:
kwargs['headers'] = await self.get_headers()
uri = self.uri(endpoint)
logger.debug('Fetching: %s', uri)
logger.debug('Headers: %s', kwargs['headers'])
logger.debug('Cookies: %s', self.session.cookies)
with aiohttp.Timeout(self.request_timeout):
async with self.session.request(
method, uri, *args, **kwargs) as response:
body = await response.read()
if not response.status == 200:
try:
json = await response.json()
except Exception: # TODO: narrow exception
json = None
ex = BadRequest if response.status == 400 else HTTPError
raise ex(response.status, body, kwargs.get('data'), json)
if raw:
return body
json = await response.json()
if json.get('error'):
raise ResponseError(response.status, body, kwargs.get('data'), json)
return json
示例10: setavatar
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def setavatar(ctx, *, url:str=None):
"""Changes the bot's avatar"""
if ctx.message.attachments:
url = ctx.message.attachments[0].url
elif url is None:
await ctx.send("Please specify an avatar url if you did not attach a file")
return
try:
with aiohttp.Timeout(10):
async with aiosession.get(url.strip("<>")) as image:
await bot.user.edit(avatar=await image.read())
except Exception as e:
await ctx.send("Unable to change avatar: {}".format(e))
return
await ctx.send(":eyes:")
示例11: _get_feed
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def _get_feed(self, url):
text = None
try:
with aiohttp.ClientSession() as session:
with aiohttp.Timeout(3):
async with session.get(url) as r:
text = await r.text()
except:
pass
return text
示例12: fetch
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def fetch(url, proxy=None):
conn = aiohttp.ProxyConnector(proxy=proxy)
headers = {'user-agent': get_user_agent()}
with aiohttp.ClientSession(connector=conn) as session:
with aiohttp.Timeout(TIMEOUT):
async with session.get('http://python.org', headers) as resp:
return resp.json()
示例13: url_image
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def url_image(url):
# Checks headers only
try:
with aiohttp.Timeout(3):
async with aiohttp.ClientSession() as session:
async with session.head(url=url, allow_redirects=True) as response:
return "Content-Type" in response.headers and \
response.headers["Content-Type"].lower().startswith("image")
except Exception as exception:
util.logger.error("Got %s while checking image url.", exception)
# Do not care about any of the network errors that could occur.
pass
return False
示例14: make_transaction
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def make_transaction(sender_id, amount, to):
transaction_data = {
"user": sender_id,
"amount": amount,
"exchangeTo": to
}
with aiohttp.Timeout(10):
async with aiohttp.ClientSession() as session:
async with session.post(DISCOIN + TRANSACTION,
data=json.dumps(transaction_data), headers=headers) as response:
return await response.json()
示例15: reverse_transaction
# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import Timeout [as 別名]
def reverse_transaction(receipt):
reverse_data = {"receipt": receipt}
with aiohttp.Timeout(10):
async with aiohttp.ClientSession() as session:
async with session.post(DISCOIN + REVERSE,
data=json.dumps(reverse_data), headers=headers) as response:
return await response.json()