def check_rate_limit(request: Request, action_name: str) -> RateLimitResult: """Check the rate limit for a particular action on a request.""" action = None # check for a custom rate-limit for the user if request.user: user_limit = ( request.query(UserRateLimit) .filter( UserRateLimit.user == request.user, UserRateLimit.action == action_name ) .one_or_none() ) if user_limit: action = RateLimitedAction( action_name, user_limit.period, user_limit.limit, by_user=True, by_ip=False, ) # if a custom rate-limit wasn't found, use the default, global rate-limit if not action: try: action = RATE_LIMITED_ACTIONS[action_name] except KeyError as exc: raise ValueError("Invalid action name: %s" % action_name) from exc action.redis = request.redis results = [] if action.is_global: results.append(action.check_global()) if action.by_user and request.user: results.append(action.check_for_user_id(request.user.user_id)) if action.by_ip and request.remote_addr: results.append(action.check_for_ip(request.remote_addr)) # no checks were done, return the "not limited" result if not results: return RateLimitResult.unlimited_result() return RateLimitResult.merged_result(results)
def check_rate_limit(request: Request, action_name: str) -> RateLimitResult: """Check the rate limit for a particular action on a request.""" try: action = RATE_LIMITED_ACTIONS[action_name] except KeyError: raise ValueError('Invalid action name: %s' % action_name) action.redis = request.redis results = [] if action.by_user and request.user: results.append(action.check_for_user_id(request.user.user_id)) if action.by_ip and request.remote_addr: results.append(action.check_for_ip(request.remote_addr)) # no checks were done, return the "not limited" result if not results: return RateLimitResult.unlimited_result() return RateLimitResult.merged_result(results)