python - mypy 说 request.json 返回 Optional[Any],我该如何解决?
问题描述
我试图更好地理解 mypy 。对于以下代码行:
request_body: dict = {}
request_body = request.get_json()
mypy 返回错误:
error: Incompatible types in assignment (expression has type "Optional[Any]", variable has type "Dict[Any, Any]")
对此的正确解决方法是什么?
解决方案
正如您在以下代码中看到的那样,从 /wekzeug/wrappers/request.py 中获取,该函数get_json
并不总是返回字典。我建议从变量中删除类型提示,因为它可以是 None 或字典。
def get_json(
self, force: bool = False, silent: bool = False, cache: bool = True
) -> t.Optional[t.Any]:
"""Parse :attr:`data` as JSON.
If the mimetype does not indicate JSON
(:mimetype:`application/json`, see :meth:`is_json`), this
returns ``None``.
If parsing fails, :meth:`on_json_loading_failed` is called and
its return value is used as the return value.
:param force: Ignore the mimetype and always try to parse JSON.
:param silent: Silence parsing errors and return ``None``
instead.
:param cache: Store the parsed JSON to return for subsequent
calls.
"""
if cache and self._cached_json[silent] is not Ellipsis:
return self._cached_json[silent]
if not (force or self.is_json):
return None
data = self.get_data(cache=cache)
try:
rv = self.json_module.loads(data)
except ValueError as e:
if silent:
rv = None
if cache:
normal_rv, _ = self._cached_json
self._cached_json = (normal_rv, rv)
else:
rv = self.on_json_loading_failed(e)
if cache:
_, silent_rv = self._cached_json
self._cached_json = (rv, silent_rv)
else:
if cache:
self._cached_json = (rv, rv)
return rv
此行特别导致该方法返回 None:
except ValueError as e:
if silent:
rv = None```
推荐阅读
- wordpress - 在 Vue 中解析 v-html 内容
- events - 更新文档时未触发 Couchbase Webhook url
- swift - 限制在 iphoneX 缺口上方的屏幕顶部
- python - Docker 和 PermissionError:[Errno 13] 权限被拒绝:'output.svg'
- java - 如何制作 TriangleWithException 对象?
- angular - 无法在 Angular 9 中设置背景图像(带渐变)
- environment - 设置环境,以便用户可以协作进行代码编辑
- bash - Jenkins管道内的bash脚本内的变量分配
- python - 无法在临时目录 Python 中创建文件
- javascript - 有没有更好的方法来检测用户的在线状态,而不是使用 setInterval 继续向服务器发送 AJAX 请求?