Conditions | 6 |
Total Lines | 52 |
Code Lines | 18 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | #!/usr/bin/env python3 |
||
94 | @contextmanager |
||
95 | def redis_lock(lock_id, blocking=False, expire=True): |
||
96 | """ |
||
97 | This function get a lock relying on a lock name and other status. You |
||
98 | can describe more process using the same lock name and give exclusive |
||
99 | access to one of them. |
||
100 | |||
101 | Args: |
||
102 | lock_id (str): the name of the lock to take |
||
103 | blocking (bool): if True, we wait until we have the block, if False |
||
104 | we returns immediately False |
||
105 | expire (bool): if True, lock will expire after LOCK_EXPIRE timeout, |
||
106 | if False, it will persist until lock is released |
||
107 | |||
108 | Returns: |
||
109 | bool: True if lock acquired, False otherwise |
||
110 | """ |
||
111 | |||
112 | # read parameters from settings |
||
113 | REDIS_CLIENT = redis.StrictRedis( |
||
114 | host=settings.REDIS_HOST, |
||
115 | port=settings.REDIS_PORT, |
||
116 | db=settings.REDIS_DB) |
||
117 | |||
118 | # this will be the redis lock |
||
119 | lock = None |
||
120 | |||
121 | # timeout for the lock (if expire condition) |
||
122 | timeout_at = monotonic() + LOCK_EXPIRE - 3 |
||
123 | |||
124 | if expire: |
||
125 | lock = REDIS_CLIENT.lock(lock_id, timeout=LOCK_EXPIRE) |
||
126 | |||
127 | else: |
||
128 | lock = REDIS_CLIENT.lock(lock_id, timeout=None) |
||
129 | |||
130 | status = lock.acquire(blocking=blocking) |
||
131 | |||
132 | try: |
||
133 | logger.debug("lock %s acquired is: %s" % (lock_id, status)) |
||
134 | yield status |
||
135 | |||
136 | finally: |
||
137 | # we take advantage of using add() for atomic locking |
||
138 | # don't release the lock if we didn't acquire it |
||
139 | if status and ((monotonic() < timeout_at and expire) or not expire): |
||
140 | logger.debug("Releasing lock %s" % lock_id) |
||
141 | # don't release the lock if we exceeded the timeout |
||
142 | # to lessen the chance of releasing an expired lock |
||
143 | # owned by someone else |
||
144 | # if no timeout and lock is taken, release it |
||
145 | lock.release() |
||
146 | |||
200 |