Hi, At the moment we use flask in production Kubernetes, but I would like to migrate to Fast API. Fast API awesome framework. I already developed the FAST API project template for microservices to use in production. I will be publishing the template on Github soon. I got some questions regarding the usage of Fast API.
1) What would be the best way to handle WebSocket connections and disconnections on Fast API?
2) When I use custom classes for pydantic I get an error in auto-documentation.
3) In case I want to create custom model classes and pass it to the pydantic's BaseModel class in order to get documentation but unfortunately, it throws an error on swagger UI.
For instance case below :
class User(Model):
__tablename__ = "boilerplate"
email = Column(String, index=True)
hashed_password = Column(String)
is_active = Column(BOOLEAN, default=True)
class AllUsersSchema(BaseModel):
users: List[User] = []
class Config:
orm_mode = True
arbitrary_types_allowed= True
You can see the docs on websockets here: https://fastapi.tiangolo.com/tutorial/websockets/
If that isn't what you need, it would help if you could clarify your question.
With regard to questions 2 and 3, you need to use a subclass of BaseModel as the parameter of List for the users field. So you'll want to create something similar to your User model (which I assume is a sqlalchemy ORM class), and then you have to convert between pydantic and ORM. The typical convention is calling the pydantic model something like UserInDB.
While you might find this annoying, this is actually necessary because of the differences between how sqlalchemy and pydantic work:
Sqlalchemy does a lot behind the scenes to minimize the amount of chatter between your service and the database through lazy lookups, etc., which can help ensure maximum performance for database-oriented functionality.
On the other hand, pydantic does eager input validation, which ensures that you discover validation errors immediately. This is in contrast with how things would work if you accepted a plain dict with string-valued keys -- you wouldn't get an error until you tried to access the missing key.
Typically, I write simple conversion methods on my database models: a classmethod from_model that converts a UserCreate or UserInDB pydantic model instance into a User ORM instance, and an instance method to_model that converts an ORM instance to a UserInDB record. (The UserCreate model is a superclass of UserInDB with only the attributes that you'd know when you want to create an instance; typically, for example, the primary key isn't present on UserCreate, but is present on UserInDB.)
Hopefully this is helpful!
@dmontagu thank you for your response.
Thanks for the help here @dmontagu ! :cake: :bowing_man:
Thanks @Turall for reporting back and closing the issue :+1:
Most helpful comment
Thanks for the help here @dmontagu ! :cake: :bowing_man:
Thanks @Turall for reporting back and closing the issue :+1: