gpt4 book ai didi

python - 尝试在 pythonanywhere 上使用 praw 提交图像时出现 WebSocketProxyException 403

转载 作者:行者123 更新时间:2023-12-01 00:43:56 30 4
gpt4 key购买 nike

我正在尝试在 pythonanywhere 上使用 praw 将图像本地上传到 reddit。

praw.models.Subreddit.submit_image(title, image_path)

这在我的计算机上运行良好,但在 pythonanywhere 上它会抛出 403 错误。 (尽管如此,图像仍然会上传。)

我明白了on pythonanywhere's website 403 错误是由于他们的代理白名单造成的,但 reddit 是白名单网站之一,praw 使用 requests,pythonanywhere 说这是一个兼容的库。常规的submit也可以正常工作。

File "/home/ibid/.local/lib/python3.7/site-packages/praw/models/reddit/subreddit.py", line 780, in submit_image
return self._submit_media(data, timeout)
File "/home/ibid/.local/lib/python3.7/site-packages/praw/models/reddit/subreddit.py", line 494, in _submit_media
response["json"]["data"]["websocket_url"], timeout=timeout
File "/home/ibid/.local/lib/python3.7/site-packages/websocket/_core.py", line 514, in create_connection
websock.connect(url, **options)
File "/home/ibid/.local/lib/python3.7/site-packages/websocket/_core.py", line 223, in connect
options.pop('socket', None))
File "/home/ibid/.local/lib/python3.7/site-packages/websocket/_http.py", line 122, in connect
sock = _tunnel(sock, hostname, port, auth)
File "/home/ibid/.local/lib/python3.7/site-packages/websocket/_http.py", line 293, in _tunnel
"failed CONNECT via proxy status: %r" % status)
websocket._exceptions.WebSocketProxyException: failed CONNECT via proxy status: 403

最佳答案

我在 PRAW 中编写了图像提交功能。正如 the documentation 中所述,Reddit API 在通过 API 提交图像或视频时使用 websockets。这与 API 对于文本或链接提交的工作方式不同,后者直接返回所创建帖子的 URL。当涉及到图像和视频时,响应类似于

{'json': {'data': {'user_submitted_page': 'https://www.reddit.com/user/username/submitted/',
'websocket_url': 'wss://ws-05ba9e4989f78959d.wss.redditmedia.com/rte_images/z4a98g21vsb31?m=AQAAHFs1XR-NRjAq9D4PPYA6SuDvFIMUGGv2Vpv5ePM2bLV6wf5o'},
'errors': []}}

然后我们必须监听 websocket URL 以最终获取创建的帖子的 URL。有兴趣的话,相关代码是 here .

<小时/>

正如您所发现的,websocket URL(至少在回答此问题时)往往是 *.wss.redditmedia.com 的子域。 redditmedia.com 不在 the PythonAnywhere whitelist 上(尽管 reddit.com 本身就是),所以连接失败。

我为您找到了一些解决方案,首先给出我认为最理想的解决方案:

  1. 获取Giles Thomas (留下评论)或 PythonAnywhere 的其他人将 wss.redditmedia.com 的子域列入白名单。
  2. 在 PRAW >=6.5.0 中,传递参数 without_websockets=True 以禁用 Websockets。如 the documentation of submit_image 中所述,将其设置为 True 意味着您根本不会获得返回值。
  3. 在 PRAW <6.5.0 中,在每次使用 submit_image 时使用 try- except block 。正如您所发现的,帖子仍然会被创建。但是,您不会收到 Submission 对象作为返回值,因为 websocket 将失败。
  4. 付费升级到非白名单版本的 PythonAnywhere。

关于python - 尝试在 pythonanywhere 上使用 praw 提交图像时出现 WebSocketProxyException 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57134898/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com