full-stack-fastapi-template
full-stack-fastapi-template copied to clipboard
Depends used in a class takes up memoty more than 100Mb
I have a code where Depends is used in a class to implement methods of other classes. When the application is launched, this class takes up memoty more than 100Mb Here is an example:
How to optimize such code?
` class OrderFactory:
def __init__(self,
user_access_controls_validate: ValidateCustomRole = Depends(),
security_scope_validate: ValidateSecurityScope = Depends(),
validate_security_scope: ValidateSecurityScope = Depends(),
user_access_controls_factory: UserAccessControlsFactory = Depends(),
security_factory: SecurityFactory = Depends(),
current_user=Depends(get_current_user),
order_service: OrderService = Depends(),
validator_service: ValidatorService = Depends(),
custom_validator_service: CustomValidatorService = Depends(),
organization_partnership_service: OrganizationPartnershipService = Depends(),
contract_service: ContractService = Depends(),
order_status_service: OrderStatusService = Depends(),
order_line_item_factory: OrderLineItemFactory = Depends(),
email_factory: EmailFactory = Depends(),
sales_point_service: SalesPointService = Depends(),
order_line_item_service: OrderLineItemService = Depends()):
self.user_access_controls_validate = user_access_controls_validate
self.security_scope_validate = security_scope_validate
self.validate_security_scope = validate_security_scope
self.user_access_controls_factory = user_access_controls_factory
self.security_factory = security_factory
self.current_user = current_user
self.order_service = order_service
self.validator_service = validator_service
self.custom_validator_service = custom_validator_service
self.organization_partnership_service = organization_partnership_service
self.contract_service = contract_service
self.order_status_service = order_status_service
self.order_line_item_factory = order_line_item_factory
self.email_factory = email_factory
self.sales_point_service = sales_point_service
self.order_line_item_service = order_line_item_service
` The whole project is 2 MB. After the start of the project, 800MB of memory is used
Looks like you misunderstood how Depends works: it takes a Callable which in turn provides the actual value you're depending on. For example:
def get_db():
try:
db = Database()
yield db
finally:
db.close()
Now, you'd use that like
def foo(db: Database = Depends(get_db), ...):
pass
I'm not sure if that's what's causing your memory issue, but it certainly isn't helping it.