How to use FastAPI lifetime?

Here’s a bullet point list to explain my situation:

  • I am working with FastAPI
  • I have written a FastAPI webserver code which has a number of defined get/post endpoints
  • The logic for what this webserver does started to become complex, so I moved all of the business logic into a new class called Webserver
  • The file containing the code which is related to defining a FastAPI webserver now simply handles conversions of types and forwards requests to an instance of Webserver

Here is an example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@app.post('/api/send_order')
def send_order(
fastapi_order_insert_message: FastAPI_OrderInsertMessage,
request: Request,
response: Response,
):
debug_print_pid() ####################################### <- print some debugging
timestamp = now() # information
ip = request.client.host #
#
log.info(f'POST /api/send_order ({ip}, {timestamp})') ###
try:
return webserver.send_order(fastapi_order_insert_message) # <- the forwarded
# request
except Exception as error:
response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR ### <- some logic to
return FastAPI_ReturnStatus( # avoid exposing
status='error', # implementation
message='internal server error', # details to api
) ############################################################## users
</code>
<code>@app.post('/api/send_order') def send_order( fastapi_order_insert_message: FastAPI_OrderInsertMessage, request: Request, response: Response, ): debug_print_pid() ####################################### <- print some debugging timestamp = now() # information ip = request.client.host # # log.info(f'POST /api/send_order ({ip}, {timestamp})') ### try: return webserver.send_order(fastapi_order_insert_message) # <- the forwarded # request except Exception as error: response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR ### <- some logic to return FastAPI_ReturnStatus( # avoid exposing status='error', # implementation message='internal server error', # details to api ) ############################################################## users </code>
@app.post('/api/send_order')
def send_order(
    fastapi_order_insert_message: FastAPI_OrderInsertMessage,
    request: Request,
    response: Response,
):
    debug_print_pid() ####################################### <- print some debugging
    timestamp = now()                                       #    information
    ip = request.client.host                                # 
                                                            #
    log.info(f'POST /api/send_order ({ip}, {timestamp})') ###

    try:
        return webserver.send_order(fastapi_order_insert_message) # <- the forwarded
                                                                  #    request

    except Exception as error:
        response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR ### <- some logic to
        return FastAPI_ReturnStatus(                                   #    avoid exposing
            status='error',                                            #    implementation
            message='internal server error',                           #    details to api
        ) ##############################################################    users

If you were wondering, FastAPI_OrderInsertMessage and FastAPI_ReturnStatus are just some pydantic types which I defined.

  • The application logic contained inside of Webserver became more complex and started interacting with files
  • I realized that I needed a way to call a cleanup function webserver.shutdown() which would flush and close these files
  • Webserver.__init__ opens some files, so these need to be closed again

My understanding is that there is only one way to do this, and it is facilitated by the FastAPI “lifespan” concept.

Here’s my implementation of that.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>webserver = None
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
global webserver
webserver = Webserver()
yield
webserver.shutdown()
</code>
<code>webserver = None from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): global webserver webserver = Webserver() yield webserver.shutdown() </code>
webserver = None

from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    global webserver
    webserver = Webserver()
    yield
    webserver.shutdown()

This seems to work. Some logging information shows that an instance of Webserver is created when the application runs, and is also torn down when the application is interrupted with a CTRL + C interrupt signal.

You can see that I have resorted to using a global variable webserver such that the endpoints, for example send_order, can access the object webserver. However, this seems like a bit of a code smell.

Have I used the the right approach here, or did I misunderstand something about how the lifespan concept is intended to be used?

Additional comment: I considered using the dynamic nature of Python to attach a new attribute webserver to app, which is an argument to the lifespan function, and also a global variable. However this potentially risks masking some existing attribute, so again I am unsure if this is advisable.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật