jetforce/examples/rate_limit.py

44 lines
1.1 KiB
Python
Raw Normal View History

2020-07-26 04:57:51 +02:00
#!/usr/local/env python3
"""
2020-07-27 06:02:51 +02:00
This example shows how you can implement rate limiting on a per-endpoint basis.
2020-07-26 04:57:51 +02:00
"""
from jetforce import GeminiServer, JetforceApplication, RateLimiter, Response, Status
2020-07-27 06:09:00 +02:00
# Setup a global rate limiter that will be applied to all requests
2020-07-27 06:02:51 +02:00
global_rate_limiter = RateLimiter("100/m")
app = JetforceApplication(rate_limiter=global_rate_limiter)
# Setup some custom rate limiting for specific endpoints
short_rate_limiter = RateLimiter("5/30s")
long_rate_limiter = RateLimiter("60/5m")
2020-07-26 04:57:51 +02:00
INDEX_PAGE = """\
# Rate Limiting Demo
=>/short short rate limiter (5/30s)
=>/long long rate limiter (60/5m)
"""
@app.route("", strict_trailing_slash=False)
def index(request):
return Response(Status.SUCCESS, "text/gemini", INDEX_PAGE)
@app.route("/short")
2020-07-27 06:02:51 +02:00
@short_rate_limiter.apply
2020-07-26 04:57:51 +02:00
def short(request):
return Response(Status.SUCCESS, "text/gemini", "Request was successful")
@app.route("/long")
2020-07-27 06:02:51 +02:00
@long_rate_limiter.apply
2020-07-26 04:57:51 +02:00
def long(request):
return Response(Status.SUCCESS, "text/gemini", "Request was successful")
if __name__ == "__main__":
server = GeminiServer(app, host="127.0.0.1", hostname="localhost")
server.run()