Code

Fastapi - Ratelimiting

Fastapi & Rate Limiting

Let’s test a simple Rate Limiting Function found on the Net …

main.py

Main App with Rate Limiting Function

# main.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from Token_bucket import TokenBucket

app = FastAPI()

class RateLimiterMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, bucket: TokenBucket):
        super().__init__(app)
        self.bucket = bucket

    async def dispatch(self, request: Request, call_next):
        if self.bucket.take_token():
            return await call_next(request)

        # Return a JSON response for rate limit exceeded
        return JSONResponse(status_code=429, content={"detail": "Rate limit exceeded"})

# Token bucket with a capacity of 3 and refill rate of 1 token per second
bucket = TokenBucket(capacity=3, refill_rate=3)

# Apply the rate limiter middleware
app.add_middleware(RateLimiterMiddleware, bucket=bucket)

@app.get("/")
async def read_root():
    return {"message": "Hello World"}

Token_bucket.py

# Token_bucket.py
import time

class TokenBucket:
    def __init__(self, capacity, refill_rate):
        self.capacity = capacity
        self.refill_rate = refill_rate
        self.tokens = capacity
        self.last_refill = time.time()

    def add_tokens(self):
        now = time.time()
        if self.tokens < self.capacity:
            tokens_to_add = (now - self.last_refill) * self.refill_rate
            self.tokens = min (self.capacity, self.tokens + tokens_to_add)
        self.last_refill=now

    def take_token(self):
        self.add_tokens()
        if self.tokens >= 1:
            self.tokens -=1
            return True
        return False

Test Script

Let’s produce some requests …

HTML - Center Div

3 Ways to Center a < div >

Credits to https://twitter.com/BilliCodes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Centering a Div - Three Methods</title>
    <style>
        .container {
            height: 100vh; /* Full height */
            position: relative; /* Required for absolute positioning */
            background-color: #f0f0f0;
        }

        /* (1) Flexbox Method */
        .flexbox {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh; /* Full viewport height */
        }

        /* (2) Grid Method */
        .grid {
            display: grid;
            place-items: center; /* Center using grid */
            height: 100vh; /* Full viewport height */
        }

        /* (3) Absolute Positioning Method */
        .absolute {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%); /* Offset to center */
        }      
    </style>
</head>

<body>
    <div class="container">
        <!-- Flexbox Method -->
        <div class="centered flexbox">Centered with Flexbox</div>

        <!-- Grid Method -->
        <div class="centered grid">Centered with CSS Grid</div>
        
        <!-- Absolute Positioning Method -->
        <div class="centered absolute">Centered with Absolute Positioning</div>
    </div>
</body>

</html>

Any Comments ?

sha256: 85678db9aeded3bf6ba6bce5bf56014023c834cdd99b62f0d8427f3c12a65360

Fastapi

FastAPI - Dependencies and Custom Headers

Source

Code

from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()


async def verify_token(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


async def verify_key(x_key: str = Header()):
    if x_key != "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key


@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
    return [{"item": "Foo"}, {"item": "Bar"}]

Test’s

Failed

no Custom Header

curl -s http://localhost/api/items/ |jq
{
  "detail": [
    {
      "loc": [
        "header",
        "x-token"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "header",
        "x-key"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

adding “x-token”

Ruby on Rails

https://github.com/Bratela/openbsd

Install Ruby

Install Ruby and set Symlinks

doas su -
pkg_add ruby-3.1.2
ln -sf /usr/local/bin/ruby31 /usr/local/bin/ruby
ln -sf /usr/local/bin/bundle31 /usr/local/bin/bundle
ln -sf /usr/local/bin/bundler31 /usr/local/bin/bundler
ln -sf /usr/local/bin/erb31 /usr/local/bin/erb
ln -sf /usr/local/bin/gem31 /usr/local/bin/gem
ln -sf /usr/local/bin/irb31 /usr/local/bin/irb
ln -sf /usr/local/bin/rdoc31 /usr/local/bin/racc
ln -sf /usr/local/bin/rake31 /usr/local/bin/rake
ln -sf /usr/local/bin/rdoc31 /usr/local/bin/rbs
ln -sf /usr/local/bin/rdoc31 /usr/local/bin/rdbg
ln -sf /usr/local/bin/rdoc31 /usr/local/bin/rdoc
ln -sf /usr/local/bin/ri31 /usr/local/bin/ri
ln -sf /usr/local/bin/typeprof31 /usr/local/bin/typeprof

Install Nokogiri

pkg_add ruby31-nokogiri-1.13.1p0

Install Rails

pkg_add ruby-3.1.2

Install Rails

gem install --user-install rails

Any Comments ?

sha256: 8fe9d1423773886605a4b9cddc3e9e14a274f9431f7839274f5a2b6d7370f9f8

Go CrossCompile

Crosscompile under GoLang

Python is cool and everybody like it, but i also like the Concept of writing some Code, compile it for different Platforms and run it everywhere. Google’s Go Language got the possiblity to compile it for multiple Architectures and Operating Systems at the same time. Why not give a try … ?

Little Hello World

package main

import (
    "fmt"
    "os"
)

func main() {
    s := "world"

    if len(os.Args) > 1 {
        s = os.Args[1]
    }

    fmt.Printf("Hello, %v!", s)
    fmt.Println("")

    if s == "fail" {
        os.Exit(30)
    }
}

go.mod

module example.com/test

go 1.18

Compile and run under macOS

go build

./test
Hello, world!

CrossCompile Script

#!/usr/bin/env bash

archs=(amd64 arm64)
os=(darwin freebsd linux openbsd windows)
name="hello"

for arch in ${archs[@]}; do
  for os in ${os[@]}; do
        env GOOS=${os} GOARCH=${arch} go build -o ${name}_${os}-${arch}
  done
done

Compile it

execute it …

Little Mail Validator in Python

wrote a little Mail Adresse Validator in Python. use it, modify it, like it … best practice for python is to use a virtual env like Poetry (or virtualenv) and add the “email-validator” module like this:

poetry add email-validator

Code

few lines of code …

#!/usr/bin/env python3

from email_validator import validate_email, EmailNotValidError

ok=[]
nok=[]

emails = [
        "[email protected]", "[email protected]", "[email protected]",
        "[email protected]", "asf.asdf", "[email protected]", "[email protected]"
        ]

print ("\nMy Little Mail Validator\n")

for email in emails:

    try:
        # Validate.
        valid = validate_email(email)

        # Update with the n
        email = valid.email

        # Append to List
        ok.append(email)

    except EmailNotValidError as e:

        # email is not valid, exception message is human-readable
        nok.append(str(e))


print ("*** Mail ok ***")
for item in ok:
    print("ok: ", item)

print ("\n*** Mail NOT ok ***")
for item in nok:
    print("NOK:", item,"!")

print()

Run

just run and enjoy …