Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
Matrix
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Code
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Container Registry
Model registry
Operate
Environments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Terms and privacy
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
TeDomum
Matrix
Commits
3077cb29
Commit
3077cb29
authored
10 years ago
by
Erik Johnston
Browse files
Options
Downloads
Patches
Plain Diff
Use contextlib.contextmanager instead of a custom class
parent
9d9b2305
No related branches found
Branches containing commit
No related tags found
Tags containing commit
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
synapse/util/ratelimitutils.py
+12
-22
12 additions, 22 deletions
synapse/util/ratelimitutils.py
with
12 additions
and
22 deletions
synapse/util/ratelimitutils.py
+
12
−
22
View file @
3077cb29
...
...
@@ -20,6 +20,7 @@ from synapse.api.errors import LimitExceededError
from
synapse.util.async
import
sleep
import
collections
import
contextlib
import
logging
...
...
@@ -112,16 +113,19 @@ class _PerHostRatelimiter(object):
or
self
.
request_times
)
@contextlib.contextmanager
def
ratelimit
(
self
):
request_id
=
object
()
def
on_enter
():
return
self
.
_on_enter
(
request_id
)
def
on_exit
(
exc_type
,
exc_val
,
exc_tb
):
return
self
.
_on_exit
(
request_id
)
# `contextlib.contextmanager` takes a generator and turns it into a
# context manager. The generator should only yield once with a value
# to be returned by manager.
# Exceptions will be reraised at the yield.
return
ContextManagerFunction
(
on_enter
,
on_exit
)
request_id
=
object
()
ret
=
self
.
_on_enter
(
request_id
)
try
:
yield
ret
finally
:
self
.
_on_exit
(
request_id
)
def
_on_enter
(
self
,
request_id
):
time_now
=
self
.
clock
.
time_msec
()
...
...
@@ -210,17 +214,3 @@ class _PerHostRatelimiter(object):
deferred
.
callback
(
None
)
except
KeyError
:
pass
class
ContextManagerFunction
(
object
):
def
__init__
(
self
,
on_enter
,
on_exit
):
self
.
on_enter
=
on_enter
self
.
on_exit
=
on_exit
def
__enter__
(
self
):
if
self
.
on_enter
:
return
self
.
on_enter
()
def
__exit__
(
self
,
exc_type
,
exc_val
,
exc_tb
):
if
self
.
on_exit
:
return
self
.
on_exit
(
exc_type
,
exc_val
,
exc_tb
)
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment