django的auth中间件有这段代码:
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `AnonymousUser` is returned.
"""
from .models import AnonymousUser
user = None
try:
user_id = request.session[SESSION_KEY]
backend_path = request.session[BACKEND_SESSION_KEY]
except KeyError:
pass
else: # <------ this doesnot have if-part, but how is it meant to work?
if backend_path in settings.AUTHENTICATION_BACKENDS:
# more code...
else
部分很有意思,它没有if
- 部分,这是什么?如果我不知道这个真的很酷
答案 0 :(得分:6)
else
构成try except
try:
user_id = request.session[SESSION_KEY]
backend_path = request.session[BACKEND_SESSION_KEY]
except KeyError:
pass
else:
if backend_path in settings.AUTHENTICATION_BACKENDS:
# more code...
else
子句,如果存在,则必须遵循除子句之外的所有子句。如果try子句不引发异常,则必须执行的代码很有用。
在这里,只有在代码没有引发任何KeyErrors
示例强>
考虑我们有一本词典
>>> a_dict={"key" : "value"}
我们可以使用try except
来处理KeyError
>>> try:
... print a_dict["unknown"]
... except KeyError:
... print "key error"
...
key error
现在,我们需要检查是否发生了密钥错误,如果没有,则else
子句执行为
>>> try:
... print a_dict["key"]
... except KeyError:
... print "key error"
... else:
... print "no errors"
...
value
no errors
如果提出任何except
条款,那么它就不会被执行。
>>> try:
... print a_dict["unkown"]
... except KeyError:
... print "key error"
... else:
... print "no errors"
...
key error