使用aiohttp发送Tracker宣告请求失败的技术求助
使用aiohttp向BT Tracker发送宣告请求的问题
我尝试通过以下代码用aiohttp向BT种子的Tracker服务器发送宣告请求:
HEADERS = { "Accept-Encoding": "gzip", "User-Agent": settings.peer_id, "Content-Type": "application/x-www-form-urlencoded" } PARAMS = { "info_hash": torrent.info_hash, "peer_id": settings.user_agent + settings.random_id, "port": settings.port, "uploaded": torrent.uploaded, "downloaded": torrent.downloaded, "left": torrent.size - torrent.downloaded, "compact": 1, "numwant": 200, "supportcrypto": 1, "no_peer_id": 1 } if ANNOUNCE_TABLE_HTTP[event]: PARAMS["event"] = ANNOUNCE_TABLE_HTTP[event] async with aiohttp.ClientSession() as aiohttp_client: async with aiohttp_client.get(url= torrent.connection_info.announce_url, headers = HEADERS, data = PARAMS) as resp: content = await resp.read()
关键说明:info_hash为bytes类型,其余字段为整数或字符串类型。
遇到的问题
- 使用
data = PARAMS时,触发无法编码整数(如port、uploaded等字段)的错误; - 使用
json = PARAMS时,触发无法编码bytes类型(info_hash)的错误; - 尝试过
urllib.parse.urlencode、urllib.parse.quote,甚至用binascii.hexdigest和base64编码处理info_hash,均未解决问题; - 用requests.get发送请求一切正常,但aiohttp请求时服务器会立即关闭连接,推测是info_hash未被正确识别导致。
当前可行但不够优雅的方案
通过手动拼接URL的方式可以正常运行,但代码不够简洁优雅,希望找到更规范的解决方案:
HTTP_PARAMS = urllib.parse.urlencode(HTTP_PARAMS) HTTP_PARAMS = HTTP_PARAMS.replace("%25", "%") URL = torrent.announce_url + f"?{HTTP_PARAMS}" async with aiohttp_client.get(URL, headers=HTTP_HEADERS,) as resp: content = await resp.read()
恳请提供可行的优化解决方案,谢谢!
内容的提问来源于stack exchange,提问作者user13975834
相关产品推荐
相关产品推荐

