• notice
  • Congratulations on the launch of the Sought Tech site

Class variables in depends in FastAPI cause problems passing data across request sessions

    In a python server project built using FastAPI, depends is used in the route request processing method to determine the user's login status. Encountered a problem with class variables in depends causing data to be passed across request sessions.

    Dependency is an easy-to-use, powerful dependency injection system provided by FastAPI. It allows developers to easily integrate components into FastAPI. Dependency injection is very suitable for scenarios such as sharing business logic, sharing database connections, implementing security, authentication, role permissions, etc. These scenarios can reuse the same code logic, and use dependency injection to minimize code duplication. A dependency can be a function or a class. An official example of using a class as depends is as follows:

from fastapi import Depends , FastAPI app = FastAPI () fake_items_db = [{ "item_name" : "Foo" }, { "item_name" : "Bar" }, { "item_name" : "Baz" }]         class CommonQueryParams : def __init__ ( self , q : str | None = None , skip : int = 0 , limit : int = 100 ):
       self . q = q
       
       self . skip = skip
       self . limit = [email protected] . get ( "/items/" ) async def read_items ( commons : CommonQueryParams = Depends ( CommonQueryParams )):
   response = {} if commons . q :
       response . update ({ "q" : commons . q })
   items = fake_items_db [ commons . skip : commons . skip +    
   commons . limit ]
   response . update ({ "items" : items }) return response

  In previous projects, I used functions as depends, but there were some shortcomings. This time I used classes. In the above example FastAPI calls the CommonQueryParams class. This will create an "instance" of the class which will be passed to your function as parameter commons. Here I use depends in the route request processing method to determine the user's login status, as shown in some codes as follows:

# Interface function @router . post ( "/userinfo" , summary = "User Information Interface" ) async def userinfo (
auto_login : AutoLogin = Depends ( AutoLogin ) )   # AutoLogin class code shows class AutoLogin :
user = {} def __init__ ( self , x_token : Optional [ str ] = Header ( None ), request : Request = None ):  
         

# Determine the validity of the x_token in the header, # If it is valid, extract and save the user dictionary and save it to the user of AutoLogin. AutoLogin.user = user _ _

    AutoLogin is a depends class, which will judge the validity of the x_token in the header, and if it is valid, extract and save the user dictionary and related token dictionary to the class variables user and token of AutoLogin. In the application, it is found that the API returns the user's token data when the user's request does not have an x_token. Debugging and investigation found that this situation exists. The user had a request with an x_token last time, but it did not in the next request. On the premise of having x_token, the API interface obtains the last submitted x_token, which leads to data transfer across requests and sessions. Because of the use of class variables in the above AutoLogin class, class variables are common to the entire instantiated object. Class variables are defined in the class and outside the function body. They are somewhat similar to static attributes, but the execution logic of various languages will have different results. In some languages, although they are static attributes, they will only be used in a certain request. Shared in, and such variables in python can be shared across requests, causing problems.


    Therefore, when encountering such a problem, do not define class variables in the AutoLogin class, but use self. class name in class methods to create instance variables.


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+