我正在开发一个需要用户登录的应用程序。它是一个终端浏览器,用于导航和使用流行的电子邮件客户端。
我正在努力实际记录用户的逻辑流程,而不会让事情变得混乱。我将尝试解释我在psedueo代码中尝试实现的内容,然后演示我目前所做的事情。
username = 'joe@example.com'
password = 'itsasecret'
# User has logged in before using our application. Instead of
# logging in via HTTP, just inject the cookies into the session.
if userExistsInDatabase:
session.addCookies(db.getCookies(username))
# Check the session is still valid. Just because we load
# the cookie from the database doesn't mean it's valid as
# the account could be blocked, or session could have expired
if session.checkIfSessionIsValid():
print 'Logged In'
else:
# Login failed, now we need to do a HTTP request
# incase the session has died
if session.login(username, password):
# Login success
else:
# Login Failed
else:
# No session exists in DB, try to log in and add user to db
if session.login(username, password):
# Login success
else:
# Login Failed
我希望代码能够比言语更好地解释它。但是,我遇到的问题是一切都变得混乱和快速,每当我需要使用它时,必须重复这段代码是一件痛苦的事。
这是我在很多项目中经常做的事情,因为大多数HTTP站点,至少是大型站点,都有类似的登录流程。
有什么建议吗?如果您需要更多信息,请询问。
答案 0 :(得分:1)
假设支持代码正确使用了异常,您可以通过减少代码重复来解决这个问题:
class Session():
def reconnect(self, username):
try:
cookie = db.getCookies(username)
except LookupError:
raise UserDoesNotExist
else:
self.addCookies(cookie)
if not self.checkIfSessionIsValid():
raise InvalidSession
def login(self, ...):
if not do_the_login(...):
raise LoginError
try:
try:
session.reconnect(...)
except (InvalidSession, UserDoesNotExist):
session.login(...)
except LoginError:
# failed
# at this point, either an unhandled exception terminated
# this code path or we are logged in.