python - 在Python中,如果auth_user_id不为None,匹配None失败?

标签 python nonetype

当变量为 None 时,如何停止执行我的代码?我尝试了很多东西。这是我目前的化身:

post_body = request.POST
auth_user_id = post_body.get("auth_user_id", None)

if auth_user_id is not None:
    print(auth_user_id)
    search_user = SearchUser.objects.get(user_id=auth_user_id)

现在这段代码死于最后一行并出现此错误:

ValueError: invalid literal for int() with base 10: 'None'

还有这个:

        print(auth_user_id)

显示“无”。

那么这是怎么回事呢?如何在 None 上停止代码?

最佳答案

显然,您在这里得到的是文字字符串 'None' , 而不是 None object - 注意错误消息在传递时有何不同 None你得到一个TypeError , 当通过 'None'你得到一个 ValueError:

# py2.7

>>> int(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'NoneType'
>>> int('None')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'None'


# py3
>>> int(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
>>> int('None')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'None'

您的问题来自包含文字字符串 'None' 的 HTTP 请求正文(因为它是 POST)对于“auth_user_id”键。请注意,使用经过适当验证的 Django 表单可以避免该问题。

关于python - 在Python中,如果auth_user_id不为None,匹配None失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48658117/

相关文章:

python - 方法上不支持的操作数类型

python - "How to think like a computer scientist 3"练习没有值(value)

python - 无内存位置

python - 当函数返回 None 或抛出异常时使用默认值的 Pythonic 方式是什么?

python - python中的前缀匹配

python - 除了 EOF 之外,Python 的 read() 是否总是返回请求的大小?

python - 如何向 request.POST 添加信息?

python - 在 Django 时区感知设置上查询每小时的点击次数

python - Python语法错误

python - “NoneType”对象不可下标-数据生成器