A tool to monitoring the number of request of an/multiple api_key
Project description
requests-counter
A tool to monitoring the number of requests from an or multiple api_key.
Use cases
Scenario: A Company that sell a Service that is limited by a max amount of requests.
- As a Company, I would set a request limit for an api_key.
- As a Company, I would update/destroy/inspect the status of subscription via api.
Installation
Requirement
Install redis or run a docker container as below
$> docker run --name test-redis -p6379:6379 -ti redis redis-server --appendonly yes
Package Installation
$> pip install git+https://github.com/Arfius/requests-counter
Usage
As request counter for fastapi
from fastapi import Depends, FastAPI, HTTPException
#1. Import the library
from requests_counter.reqcounter import ReqCounter
import asyncio
app = FastAPI()
#2. Create an ReqCounter object with the url to redis instance as parameter
cl = ReqCounter("redis://localhost")
#3. populate the Object with a list of tuple (key, max_value)
asyncio.create_task(cl.setup([("my-api-key-test",10)]))
#4. Declare a function to inject to Depends module. It will decrease the max_value for each request. It will raise a 429 HTTPException when max_value is 0.
async def check_key(key:str):
res = await cl.decrease(key)
if res == False:
raise HTTPException(429, "Too Many Requests", headers={"Retry-After": "renew subscription"})
return key
#5. Inject the check_key function to endpoint
@app.get("/consume/{key}")
async def consume_key(key: dict = Depends(check_key)):
return {"job": "done"}
As endpoint
Command below run the server to interact with your redis instance for
- Destroy a key
- Update the value (i.e. renewal)
- Get the status of all keys
$> uvicorn requests_counter.api:app --reload --port 8080
Run http://locahost:8080/dosc for documentation.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file requests_counter-0.2.0-py3-none-any.whl.
File metadata
- Download URL: requests_counter-0.2.0-py3-none-any.whl
- Upload date:
- Size: 5.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/52.0.0.post20210125 requests-toolbelt/0.9.1 tqdm/4.57.0 CPython/3.8.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
66288bd881ffa5b4bab3d1b19a1b0569879d3b55dd3d01dd328760663e089920
|
|
| MD5 |
3220f2263ca1eb1e6bd7606b38f25654
|
|
| BLAKE2b-256 |
4f07a137173bf3242c59047c70ef8fc0b6e0c392700287e9f4c84f2d977f3f74
|