josiahcarlson / redis-in-action

Example code from the book

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

lock usage in Chapter 8 example

opened this issue · comments

In Chapter 8 Twitter clone example, I think after acquiring the lock, if something goes wrong, the lock should be released before function returning.

For example, in listing 8.1, if conn.hget('users:', llogin), the lock should be released before return None. What do you think about it?
Perhaps it's better to use a With Statement context manager so it's not necessary to explicitly release the lock in multiple places.

def create_user(conn, login, name):
    llogin = login.lower()
    lock = acquire_lock_with_timeout(conn, 'user:' + llogin, 1) #A
    if not lock:                            #B
        return None                         #B

    if conn.hget('users:', llogin):         #C
        return None                         #C

    id = conn.incr('user:id:')              #D
    .......

Yes, this is a bug. Thank you for the report and pull request.

In practice it is definitely better to use a with statement and context manager, or even just a try/finally. I didn't use either of these in the book as a general rule primarily because I wanted the code to be more approachable to a non-Python audience. I will accept your PR and close this bug when I've got the errata ready to send to the publisher.

Yeah, it's much easier for people not familiar with Python to understand in this way. Thanks for merging the PR.