What is a Decorators in Python, Django and FastAPI

, , ,

🔹 Decorators in Python, Django and FastAPI in details with examples

In Python, a decorator is a function that wraps another function or class to modify or extend its behavior without changing its code directly.

Think of it like:

“A decorator takes a function/class as input → adds some extra functionality → and returns a new function/class.”


🔹 Example 1 – Simple function decorator

def my_decorator(func):
    def wrapper():
        print("Before function runs")
        func()
        print("After function runs")
    return wrapper

@my_decorator   # same as: hello = my_decorator(hello)
def hello():
    print("Hello, World!")

hello()

Output:

Before function runs
Hello, World!
After function runs

Here:

  • @my_decorator wraps the hello() function.
  • When you call hello(), actually wrapper() runs.

🔹 Example 2 – Decorator with arguments

def repeat(n):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(n):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)   # repeat hello 3 times
def hello(name):
    print(f"Hello {name}!")

hello("Atif")

Output:

Hello Atif!
Hello Atif!
Hello Atif!

🔹 Example 3 – Django decorator

In Django, you’ve seen things like:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...

Here @login_required ensures that only logged-in users can access that view.


🔹 Example 4 – Class decorator (Django admin)

In your admin file, you saw:

@admin.register(Payment)
class PaymentAdmin(admin.ModelAdmin):
    ...

This is a class decorator. It tells Django: “Register the Payment model in the admin, using this custom admin class.”

Equivalent without decorator:

class PaymentAdmin(admin.ModelAdmin):
    ...

admin.site.register(Payment, PaymentAdmin)

🔹 Example 5 – FastAPI decorator

In FastAPI, routes are defined with decorators:

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def say_hello():
    return {"msg": "Hello World"}

Here @app.get("/hello") is a decorator that says: “When someone sends a GET request to /hello, call this function.”


###✅ Summary for decorators:

  • Decorators = wrappers that extend/modify behavior of functions/classes.
  • They’re widely used in Django (admin, views, permissions) and FastAPI (routes, middlewares).

##how to write your own decorator step by step

Let’s build your own decorators step by step. We’ll start from very basic → then add arguments → then apply in Django-like use cases.


🛠 Step 1: Basic decorator

def simple_decorator(func):
    def wrapper():
        print("👉 Before the function")
        func()
        print("👉 After the function")
    return wrapper

@simple_decorator
def say_hello():
    print("Hello Atif!")

say_hello()

Output:

👉 Before the function
Hello Atif!
👉 After the function

📌 Here:

  • @simple_decorator is applied to say_hello.
  • When you call say_hello(), Python actually runs wrapper().

🛠 Step 2: Decorator for any function with arguments

def log_args(func):
    def wrapper(*args, **kwargs):
        print(f"Function {func.__name__} called with args={args}, kwargs={kwargs}")
        return func(*args, **kwargs)   # run the real function
    return wrapper

@log_args
def add(a, b):
    return a + b

print(add(3, 5))

Output:

Function add called with args=(3, 5), kwargs={}
8

🛠 Step 3: Decorator with arguments

Sometimes you want to pass options to your decorator itself.

def repeat(n):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for i in range(n):
                print(f"Run {i+1} of {n}")
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)   # repeat the function 3 times
def greet(name):
    print(f"Hello {name}")

greet("Atif")

Output:

Run 1 of 3
Hello Atif
Run 2 of 3
Hello Atif
Run 3 of 3
Hello Atif

Decorator in Django

🛠 A Django-like decorator

Let’s make our own login_required style decorator:

def my_login_required(func):
    def wrapper(request, *args, **kwargs):
        if not getattr(request, "user", None):   # check if request has a user
            return "❌ User not logged in!"
        return func(request, *args, **kwargs)
    return wrapper

# fake request objects
class Request:
    def __init__(self, user=None):
        self.user = user

@my_login_required
def dashboard(request):
    return f"Welcome {request.user}!"

print(dashboard(Request()))        # no user
print(dashboard(Request("Atif")))  # with user

Output:

❌ User not logged in!
Welcome Atif!

🛠 Using class decorator (like Django Admin)

def register_model(model_name):
    def decorator(admin_class):
        print(f"✅ Registered {model_name} with admin class {admin_class.__name__}")
        return admin_class
    return decorator

@register_model("Payment")
class PaymentAdmin:
    pass

Output:

✅ Registered Payment with admin class PaymentAdmin

📌 This is exactly how @admin.register(Model) works internally.


###✅ Summary for Django Decorators:

  • A decorator is a function that wraps another function/class.
  • @decorator_name is just shorthand for function = decorator_name(function).
  • They’re useful for authentication checks, logging, caching, registering routes/admins, etc.

##decorators in FastAPI. They work the same as Python decorators, but in FastAPI they’re often used for middleware-like behavior (before/after running your endpoint).


🛠 Example 1: Simple logging decorator

from fastapi import FastAPI

app = FastAPI()

# Custom decorator
def log_request(func):
    async def wrapper(*args, **kwargs):
        print(f"👉 Calling endpoint: {func.__name__}")
        result = await func(*args, **kwargs)
        print(f"✅ Finished endpoint: {func.__name__}")
        return result
    return wrapper

@app.get("/hello")
@log_request
async def say_hello():
    return {"message": "Hello Atif!"}

When you visit /hello:

👉 Calling endpoint: say_hello
✅ Finished endpoint: say_hello

🛠 Example 2: Decorator to check API Key

from fastapi import FastAPI, Request, HTTPException

app = FastAPI()

def require_api_key(func):
    async def wrapper(request: Request, *args, **kwargs):
        api_key = request.headers.get("X-API-Key")
        if api_key != "secret123":
            raise HTTPException(status_code=403, detail="Invalid API Key")
        return await func(request, *args, **kwargs)
    return wrapper

@app.get("/secure")
@require_api_key
async def secure_endpoint(request: Request):
    return {"message": "You are authorized!"}

🔑 If you call /secure without X-API-Key: secret123, you’ll get:

{"detail": "Invalid API Key"}

🛠 Example 3: Decorator with arguments (rate limiter style)

import time
from fastapi import FastAPI, HTTPException

app = FastAPI()

def rate_limit(seconds: int):
    last_called = {}

    def decorator(func):
        async def wrapper(*args, **kwargs):
            now = time.time()
            if func.__name__ in last_called and now - last_called[func.__name__] < seconds:
                raise HTTPException(status_code=429, detail="Too many requests")
            last_called[func.__name__] = now
            return await func(*args, **kwargs)
        return wrapper
    return decorator

@app.get("/ping")
@rate_limit(5)   # limit calls to every 5 seconds
async def ping():
    return {"message": "pong!"}
  • First request works ✅
  • Second request within 5s → 429 Too Many Requests

🛠 Example 4: Class decorator for routes (like Django’s @admin.register)

def tag_routes(tag: str):
    def decorator(func):
        func._tag = tag  # attach metadata
        return func
    return decorator

app = FastAPI()

@app.get("/items")
@tag_routes("inventory")
async def get_items():
    return {"items": ["apple", "banana"]}

# Later you could inspect `get_items._tag` == "inventory"

##✅ Summary for FastAPI decorators

  • Work same as Python decorators

  • Useful for:

    • Logging
    • Auth / API keys
    • Rate limiting
    • Attaching metadata
  • You can mix them with FastAPI’s built-in dependencies, but decorators give more fine-grained control.

Comments

29 responses to “What is a Decorators in Python, Django and FastAPI”

  1. Istanbul heritage tour Avatar

    Istanbul heritage tour Friendly staff and comfortable transportation. https://murtistour.com/istanbul-culture-and-history-tours.html

  2. Analiz_kiKi Avatar

    Оценка посещаемости веб-сайтов в Москве стал актуальной темой для многих компаний. С увеличением числа посетителей интернет-ресурсов так же растет и интерес к анализу их поведения. Этот процесс позволяет бизнесу лучше понять свою аудиторию .
    Анализ посещения сайтов в Москве позволяет получить ценные данные о поведении пользователей и их предпочтениях в интернете.
    Посещение сайтов в Москве отличается своими особенностями . К примеру, в Москве наблюдается значительное количество мобильного трафика . Это объясняется высокой популярностью мобильных гаджетов среди пользователей.

  3. internetNuddy Avatar

    дешевый интернет екатеринбург
    inernetvkvartiru-ekaterinburg006.ru
    интернет по адресу

  4. su sızıntısı tespiti Avatar

    su sızıntısı tespiti Çatalca su kaçağı tespiti: Çatalca’da su kaçakları için güvenilir çözüm. https://www.proathletediscuss.com/read-blog/8346

  5. Blue Mosque tour Avatar

    Blue Mosque tour Enjoyed sampling local food along the way. https://kamaleyeoptics.com/?p=3446

  6. internetNuddy Avatar

    провайдер по адресу
    inernetvkvartiru-msk006.ru
    провайдеры интернета в москве по адресу

  7. proekt pereplanirovki kvartiri_ohmr Avatar

    проект перепланировки для согласования http://www.proekt-pereplanirovki-kvartiry9.ru .

  8. Barış su kaçak tespiti Avatar

    Barış su kaçak tespiti Profesyonel Raporlama: Sorunun kaynağını detaylı bir şekilde raporladılar. Çok profesyoneller. http://www.faceya.com/read-blog/7491

  9. generic valtrex without dr prescription Avatar

    Medication prescribing information. Cautions.
    generic valtrex without dr prescription
    All news about drug. Read here.

  10. RafaelVeilk Avatar
    RafaelVeilk

    Вывод из запоя в Ростове-на-Дону является востребованной медицинской услугой, направленной на восстановление физического состояния пациента и снижение рисков осложнений. Длительное употребление алкоголя вызывает тяжелые нарушения в работе организма, и самостоятельное прекращение приёма спиртных напитков часто приводит к абстинентному синдрому. В таких ситуациях профессиональный вывод из запоя в клинике становится необходимым условием для сохранения здоровья.
    Разобраться лучше – вывод из запоя клиника ростов-на-дону

  11. switching to generic finasteride Avatar

    Drug prescribing information. What side effects?
    switching to generic finasteride
    All trends of pills. Read now.

  12. get cheap phenytoin without rx Avatar

    Drugs prescribing information. What side effects?
    get cheap phenytoin without rx
    All what you want to know about medicament. Get information here.

  13. Dizaynersk_uoot Avatar

    Дизайнерская мебель премиум класса — это воплощение изысканного стиля и безукоризненного качества.
    Элитная мебель от дизайнеров — это не просто предметы интерьера, а настоящие произведения искусства. Каждая деталь такой мебели продумана до мелочей и отражает уникальный стиль создателя. Все больше людей выбирают мебель премиум класса для своих домов.

  14. soglasovanie pereplanirovki kvartiri moskva _hiOr Avatar
    soglasovanie pereplanirovki kvartiri moskva _hiOr

    согласование перепланировки квартиры цена согласование перепланировки квартиры цена .

  15. how many calories does metformin burn Avatar

    Meds information for patients. Drug Class.
    how many calories does metformin burn
    All news about medicament. Read now.

  16. mind vault Avatar

    **mind vault**

    mind vault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking

  17. prostadine Avatar

    **prostadine**

    prostadine is a next-generation prostate support formula designed to help maintain, restore, and enhance optimal male prostate performance.

  18. glpro Avatar

    **glpro**

    glpro is a natural dietary supplement designed to promote balanced blood sugar levels and curb sugar cravings.

  19. breathe Avatar

    **breathe**

    breathe is a plant-powered tincture crafted to promote lung performance and enhance your breathing quality.

  20. tlover tonet Avatar

    I do love the way you have presented this specific difficulty and it does indeed present me some fodder for consideration. Nevertheless, through what precisely I have observed, I just hope as the actual feed-back pack on that individuals continue to be on issue and not start on a soap box of the news of the day. Still, thank you for this excellent piece and even though I do not concur with it in totality, I value your perspective.

  21. gullybet promo codes Avatar

    My brother suggested I might like this website. He was entirely right. This submit truly made my day. You cann’t believe just how a lot time I had spent for this info! Thanks!

  22. live npb streaming Avatar

    Hi there, simply changed into aware of your blog thru Google, and found that it is truly informative. I’m gonna be careful for brussels. I’ll appreciate when you proceed this in future. A lot of folks will likely be benefited out of your writing. Cheers!

  23. 888slot login apk Avatar
    888slot login apk

    Đội ngũ hỗ trợ khách hàng của slot365 hoạt động 24/7 thông qua nhiều kênh liên lạc như live chat, email, và hotline. Điểm nổi bật là thời gian phản hồi trung bình chỉ 30 giây cho live chat và 2 giờ cho email – thuộc top đầu trong ngành.

  24. the brain song Avatar

    What i don’t realize is in truth how you’re now not really a lot more smartly-liked than you might be now. You are so intelligent. You recognize therefore significantly in relation to this topic, produced me for my part believe it from so many varied angles. Its like men and women are not involved except it is one thing to do with Girl gaga! Your personal stuffs outstanding. All the time deal with it up!

  25. ph33m Avatar

    Stumbled across ph33m the other day, and it seems… interesting. I didn’t spend too much time on it, but it might be worth checking out if you’re bored. Here’s the link: ph33m.

  26. gelatin trick Avatar

    I’m now not positive the place you’re getting your information, however great topic. I needs to spend some time learning more or understanding more. Thanks for magnificent information I was looking for this info for my mission.

  27. Ethical hacking career opportunities Avatar

    You made some respectable factors there. I looked on the web for the issue and located most individuals will associate with with your website.

Leave a Reply to glpro Cancel reply

Your email address will not be published. Required fields are marked *