'FastAPI: How to use POST data as variable to trigger another script?

I have written an API on FastAPI with filename api.py:

from fastapi import FastAPI
from pydantic import BaseModel

 
app = FastAPI()
 
 
class Username(BaseModel):
    Username:str
         
         
     
@app.post('/Username')
def Username(Username : Username):
    username=Username
    import metrics
    metrics.get_user_data(str(username))
    metrics.clear()
    metrics.main()
    metrics.sum_fun()
    return {"likes": metrics.likes, "reply": metrics.reply}

The username received via the API is called to run functions from metrics.py file:

import api
get_user_data(api.username)
clear()
main()
sum_fun()

I can't seem to run this code and gets an error saying:

AttributeError: partially initialized module 'api' has no attribute 'username' (most likely due to a circular import)

How can I fix this? I understand that my code hasn't been written in the best of ways so suggestions on how to modify it are also welcomed.



Solution 1:[1]

Importing api.py into metrics.py is a huge problem, and doing that is creating your circular dependency. You typically can and should only have imports going one way. Instead, Username should be defined in metrics, and imported into api.py. All of the functions in metrics should accept Username if the metrics.py functions are referencing the Username.

On a side note, You have too many variables with the same name. Your class, function and instance have the same name, with the same spelling... There are many ways to change the names. make the function "def get_username(username:Username):" and remove "username=Username"

Also, it's probably better to import metrics at the beginning with the other imports.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Justin W King