You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask应用本地正常,PythonAnywhere报JSONDecoder 'encoding'参数错误

问题:Flask应用在PythonAnywhere运行时出现JSONDecoder参数错误

本地Python 3.10.5运行Flask应用完全正常,但在PythonAnywhere的Python 3.10环境下运行相同代码时触发以下错误:

Traceback (most recent call last): 
File "/home/speedclub/mysite/speedclub.py", line 90, in task1play sp = client.challenges.create(username = myclient.get_profile()['username'], rated = False, clock_limit = 60, color='black', position='8/8/8/3k4/8/8/1K6/Q7 w - - 0 1', clock_increment=0, variant='standard') 
File "/home/speedclub/.local/lib/python3.10/site-packages/berserk/clients.py", line 709, in create return self._r.post(path, json=payload) File "/home/speedclub/.local/lib/python3.10/site-packages/berserk/session.py", line 262, in post return self.request( 
File "/home/speedclub/.local/lib/python3.10/site-packages/berserk/session.py", line 102, in request return fmt.handle(response, is_stream=stream, converter=converter) File "/home/speedclub/.local/lib/python3.10/site-packages/berserk/formats.py", line 44, in handle return converter(self.parse(response)) File "/home/speedclub/.local/lib/python3.10/site-packages/berserk/formats.py", line 87, in parse return response.json(cls=self.decoder) 
File "/home/speedclub/.local/lib/python3.10/site-packages/requests/models.py", line 971, in json return complexjson.loads(self.text, **kwargs) 
File "/usr/local/lib/python3.10/site-packages/simplejson/__init__.py", line 542, in loads return cls(encoding=encoding, **kw).decode(s) TypeError: JSONDecoder.__init__() got an unexpected keyword argument 'encoding'

已确认本地与PythonAnywhere的依赖版本完全一致:ndjson=0.3.1,berserk=0.12.4,requests=2.31.0。出错的代码片段如下:

sp = client.challenges.create(username = myclient.get_profile()['username'], rated = False, clock_limit = 60, color='black', position='8/8/8/3k4/8/8/1K6/Q7 w - - 0 1', clock_increment=0, variant='standard')

解决方案

这个错误的核心原因是PythonAnywhere环境中simplejson库版本与本地不一致,新版本simplejson移除了JSONDecoder的encoding参数,而requests库调用时仍传入该参数导致冲突。

  • 强制使用标准库json模块
    让requests放弃使用simplejson,改用Python标准库的json模块。可以在代码开头添加:

    import os
    os.environ['REQUESTS_JSON_MODULE'] = 'json'
    

    或者在PythonAnywhere的WSGI配置文件中设置环境变量。

  • 对齐simplejson版本
    查看本地环境的simplejson版本(执行pip show simplejson获取),然后在PythonAnywhere安装相同版本:

    pip install simplejson==<你的本地版本号> --user
    
  • 临时修改berserk库代码
    找到berserk/formats.py文件的第87行,将response.json(cls=self.decoder)修改为:

    return response.json(cls=self.decoder, encoding=None)
    

    注意:这种修改会被后续库更新覆盖,仅作为临时应急方案。

内容的提问来源于stack exchange,提问作者Sloth Bear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 02:25:34