rate_limit: Make retry-after data machine-readable.

Fixes #4831.
This commit is contained in:
Lukasz Prasol 2017-05-22 20:12:59 +02:00 committed by Tim Abbott
parent 01f7d9d651
commit 5eaccc550a
2 changed files with 7 additions and 4 deletions

View File

@ -334,8 +334,11 @@ class RateLimitMiddleware(object):
def process_exception(self, request, exception): def process_exception(self, request, exception):
# type: (HttpRequest, Exception) -> HttpResponse # type: (HttpRequest, Exception) -> HttpResponse
if isinstance(exception, RateLimited): if isinstance(exception, RateLimited):
resp = json_error(_("API usage exceeded rate limit, try again in %s secs") % ( resp = json_error(
request._ratelimit_secs_to_freedom,), status=429) _("API usage exceeded rate limit"),
data={'retry-after': request._ratelimit_secs_to_freedom},
status=429
)
resp['Retry-After'] = request._ratelimit_secs_to_freedom resp['Retry-After'] = request._ratelimit_secs_to_freedom
return resp return resp

View File

@ -112,9 +112,9 @@ class RateLimitTests(ZulipTestCase):
self.assertEqual(result.status_code, 429) self.assertEqual(result.status_code, 429)
json = ujson.loads(result.content) json = ujson.loads(result.content)
self.assertEqual(json.get("result"), "error") self.assertEqual(json.get("result"), "error")
self.assertIn("API usage exceeded rate limit, try again in", json.get("msg")) self.assertIn("API usage exceeded rate limit", json.get("msg"))
self.assertEqual(json.get('retry-after'), 0.5)
self.assertTrue('Retry-After' in result) self.assertTrue('Retry-After' in result)
self.assertIn(result['Retry-After'], json.get("msg"))
self.assertEqual(result['Retry-After'], '0.5') self.assertEqual(result['Retry-After'], '0.5')
# We actually wait a second here, rather than force-clearing our history, # We actually wait a second here, rather than force-clearing our history,