How to create routes with FastAPI within a class

This can be done by using an APIRouter‘s add_api_route method: from fastapi import FastAPI, APIRouter class Hello: def __init__(self, name: str): self.name = name self.router = APIRouter() self.router.add_api_route(“/hello”, self.hello, methods=[“GET”]) def hello(self): return {“Hello”: self.name} app = FastAPI() hello = Hello(“World”) app.include_router(hello.router) Example: $ curl 127.0.0.1:5000/hello {“Hello”:”World”} add_api_route‘s second argument (endpoint) has type Callable[…, Any], … Read more

What is the purpose of checking self.__class__?

self.__class__ is a reference to the type of the current instance. For instances of abstract1, that’d be the abstract1 class itself, which is what you don’t want with an abstract class. Abstract classes are only meant to be subclassed, not to create instances directly: >>> abstract1() Traceback (most recent call last): File “<stdin>”, line 1, … Read more

When do you use ‘self’ in Python? [duplicate]

Adding an answer because Oskarbi’s isn’t explicit. You use self when: Defining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called. Referencing a class or instance attribute from inside an instance method. Use it … Read more

TypeError: generatecode() takes 0 positional arguments but 1 was given

When you call a method on a class (such as generatecode() in this case), Python automatically passes self as the first argument to the function. So when you call self.my_func(), it’s more like calling MyClass.my_func(self). So when Python tells you “generatecode() takes 0 positional arguments but 1 was given”, it’s telling you that your method … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)