0

I am working on a project in FastAPI, there is a problem in importing packages. My project structure is like this.

enter image description here

My main.py file is this:

from fastapi import FastAPI
import uvicorn
import asyncio



#imports 

from .routers import fileupload
from .startup import startup_function




app = FastAPI()


@app.on_event("startup")
def on_start_up():
    startup_function()

#fileupload router
app.include_router(fileupload.router)

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=5000, reload=True)

and my fileupload.py file is like this:

from fastapi import APIRouter, HTTPException
import asyncio
from ..posts.utils import get_file_upload, pipeline
from ..posts.schemas import FileUpload
from ..startup import db



router = APIRouter()

@router.post("/fileupload")
async def file_upload(file_upload: FileUpload):
    print("in file upload")
    # return {"message": "File uploaded successfully"}
    # Convert the base64-encoded audio data to a WAV file
    asyncio.create_task(get_file_upload(file_upload))

    asyncio.create_task(pipeline(file_upload))

    result = await db.insert_one(file_upload.dict(exclude={"Datei"}))
    if not result.acknowledged:
        raise HTTPException(status_code=500, detail="Failed to upload file")
    
    #return aa response asynchronously
    if result.acknowledged:
        return {"message": "File uploaded successfully"}
    else:
        #return failed message with error code and details
        return {"message": "Failed to upload file"}

It is giving me errors on every import, I couldn't understand from the documentation, I have tried different ways, removing . from the imports, but it does not work. Any help would be appreciated. Thanks.

Traceback (most recent call last):
  File "/home/Fast-api/src/main.py", line 9, in <module>
    from .routers import fileupload
ImportError: attempted relative import with no known parent package

This is the error to start with, I don't know how to resolve this error

Chris
  • 18,724
  • 6
  • 46
  • 80
Aheed Butt
  • 19
  • 1
  • there is no code in __init__.py files – Aheed Butt Feb 16 '23 at 20:12
  • Please take a look at related answers [here](https://stackoverflow.com/a/71342222/17865804), as well as [here](https://stackoverflow.com/a/73647164/17865804) and [here](https://stackoverflow.com/a/71080756/17865804) – Chris Feb 17 '23 at 06:17

1 Answers1

0

Put a new main.py into a higher folder level and has the same parent folder with /src folder, like:

/src
 /posts
 /routers
 main.py
main.py # a new main.py
...

and in the new main.py:

import uvicorn

if __name__ == "__main__":
    uvicorn.run("src.main:app", host="127.0.0.1", port=8000)

then just run the new main.py

python main.py
liviaerxin
  • 579
  • 6
  • 13