【发布时间】:2020-08-27 23:36:50
【问题描述】:
- 我每分钟加载多个提要网址
- 我想发送一个 http get 请求,如果数据自上次加载后发生变化,则获取 200 状态码和完整数据
- 如果自上次加载数据以来数据没有更改,我想要 http 状态代码 304 并且没有响应正文
- 如果我使用 Python feedparser 的库发送 GET 请求,Python feedparser 会提供 HERE 这个功能
- 如何使用 aiohttp 库来做到这一点
-
如何在 GET 请求中发送 etag 和最后修改
async with session.get(url) as response: text = await response.text() print(response.headers.get('etag'), response.headers.get('Last-Modified'))
如何发送 etag 和 last modified 并模拟类似于上述库的行为?
更新 1
这里有一些详细的代码
import asyncio
import aiohttp
async def load_feed(session, url):
# Keep this an empty string for the first request
etag = 'fd31d1100c6390bd8a1f16d2703d56c0'
# Keep this an empty string for the first request
last_modified='Mon, 11 May 2020 22:27:44 GMT'
try:
async with session.get(url, headers={'etag': etag, 'Last-Modified': last_modified}) as response:
t = await response.text()
print(response.headers.get('etag'), response.headers.get('Last-Modified'), response.status, len(t), response.headers)
except Exception as e:
print(e)
async def load_feeds():
try:
async with aiohttp.ClientSession() as session:
tasks = []
for url in ['https://news.bitcoin.com/feed/']:
task = asyncio.ensure_future(load_feed(session, url))
tasks.append(task)
await asyncio.gather(*tasks, return_exceptions=True)
except:
pass
asyncio.get_event_loop().run_until_complete(load_feeds())
预期:
- 第一次发送没有标头的请求
- 获取带有 etag 和 Last-modified 和完整响应的响应代码 200
- 使用 etag 和 Last-modified 再次发送请求
- 获取没有响应正文的响应代码 304
发生了什么 - 我每次都收到状态码 200 和完整的响应正文
- 也尝试了其他一些网址,例如https://coindesk.com/feed
【问题讨论】:
-
您能补充一点细节吗?我不确定你要做什么,但它还不起作用
-
我想用带有 etag 和 last-modified 的 aiohttp 发送一个请求,如果数据没有改变,它应该发送一个没有实际响应的 304 响应代码,否则它会发送 200 响应代码数据
-
我不认为 aiohttp 自己支持这个;但是,您可以在首次发出请求(将返回 200)时存储标头(
ETag和Last-Modified)并将它们重用于后续请求(应返回 304)。当然,当您收到新的 200 响应时,您需要更新存储的标头。
标签: python-3.x python-asyncio aiohttp etag last-modified