|
| 1 | +"""Copyright 2024 PythonistaGuild |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. |
| 14 | +""" |
| 15 | + |
| 16 | +import asyncio |
| 17 | + |
| 18 | +import uvicorn |
| 19 | +from starlette.middleware import Middleware |
| 20 | +from starlette.requests import Request |
| 21 | +from starlette.responses import Response |
| 22 | + |
| 23 | +import starlette_plus |
| 24 | + |
| 25 | + |
| 26 | +class App(starlette_plus.Application): |
| 27 | + def __init__(self) -> None: |
| 28 | + # Add the ratelimiter middleware to the application |
| 29 | + # This allows global and per-route rate limiting |
| 30 | + # You can use this with Redis or in-memory storage |
| 31 | + ratelimiter = Middleware(starlette_plus.middleware.RatelimitMiddleware) |
| 32 | + |
| 33 | + # We set a prefix which means all routes will be prefixed with /v1 |
| 34 | + super().__init__(prefix="/v1", middleware=[ratelimiter], access_log=True) |
| 35 | + |
| 36 | + @starlette_plus.route("/", methods=["GET"]) |
| 37 | + # This route is limited to 1 request per 60 seconds |
| 38 | + # Decorator order with starlette_plus shouldn't matter |
| 39 | + # You can put the limit decorator on-top or below the route decorator |
| 40 | + @starlette_plus.limit(1, 60) |
| 41 | + async def home(self, request: Request) -> Response: |
| 42 | + # Visit http://localhost:8000/v1/ to see this route... |
| 43 | + |
| 44 | + return starlette_plus.JSONResponse({"message": "Hello, World!"}) |
| 45 | + |
| 46 | + |
| 47 | +async def main() -> None: |
| 48 | + # This is completely optional |
| 49 | + # This is a helper function to setup logging |
| 50 | + starlette_plus.setup_logging(level=20, root=True) |
| 51 | + app: App = App() |
| 52 | + |
| 53 | + # This is the uvicorn configuration |
| 54 | + # You can change the host and port to whatever you want |
| 55 | + # We set access_log to False to disable uvicorn access logging, since we set this on our Application |
| 56 | + config: uvicorn.Config = uvicorn.Config(app=app, host="localhost", port=8000, access_log=False) |
| 57 | + server: uvicorn.Server = uvicorn.Server(config) |
| 58 | + |
| 59 | + await server.serve() |
| 60 | + |
| 61 | + |
| 62 | +asyncio.run(main()) |
0 commit comments