WebSocketProxyException 403 尝试在 pythonanywhere 上使用 praw 提交图像



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

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

这在我的计算机上工作正常,但在 pythonanywhere 上它会抛出 403 错误。(图片仍然会上传。

我在pythonanywhere的网站上看到403错误是由于他们的代理白名单造成的,但reddit是白名单网站之一,praw使用requestspythonanywhere说这是一个兼容的库。常规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中编写了图像提交功能。如文档中所述,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。如果您有兴趣,相关代码在这里。


正如您所发现的,websocket URL(至少在本答案时)往往是*.wss.redditmedia.com的子域。redditmedia.com不在 PythonAnywhere 白名单上(尽管reddit.com本身就是),因此连接失败。

我看到一些适合您的解决方案,这里首先给出我认为最理想的解决方案:

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

最新更新