0

I am just getting started with fastapi on python to develop simple ASGI endpoints. I notice that the handler function codes can only be run (and hence tested) when I am running the module with uvicorn. Example, take this code.

@app.post("/upload_dataset", tags=["DataFrame Loading Utilities"])
async def upload_dataset_to_server(file: UploadFile = File(...),
                                   encoding='utf-8',
                                   delimiter=',',
                                   sheets='Sheet1'):
    '''
        Upload dataset. Add some more details about the parameters
    '''

    raw = await file.read()
    try:
        """
        TODO: XLSX still has some minor issues with saving
        """

        if 'xlsx' in file.filename.split('.')[-1]:
            df = pd.read_excel(io=raw, sheet_name=sheets)
            filename = (file.filename).replace('xlsx', 'csv')
            filepath = ml.folder_path + \
                f'\\datastore\\dataset\\{filename}'

        else:
            content = str(raw, encoding=encoding)
            data = StringIO(content)
            df = pd.read_csv(filepath_or_buffer=data,
                             encoding=encoding, delimiter=delimiter)
            filepath = ml.folder_path + \
                f'\\datastore\\dataset\\{file.filename}'
            df.to_csv(path_or_buf=filepath, index_label=False)

        resp = ml.store_dataframe(df)
        return resp

    except UnicodeDecodeError as error:
        raise HTTPException(
            status_code=404,
            detail=str(error)
        )

Is there a way to run the lines inside a function one by one like in a jupyter notebook to familiarise myself with what each object represents and what interfaces they offer? To me it seems there is no way to invoke the function or actually inspect through the variables without running an uvicorn module and printing logs when the server is running.

Della
  • 1,264
  • 2
  • 15
  • 32
  • 1
    You can run uvicorn with a debugger - set a breakpoint on the first line of your code and run the code in debug mode - and you should be able to step through each line, inspect the variables and dig further into the methods you want. How you do that depends on which IDE you're using; for jupyterlab check out: https://blog.jupyter.org/a-visual-debugger-for-jupyter-914e61716559 - for pycharm, select "Debug" instead of "Run" in the menu. – MatsLindh Sep 29 '21 at 13:52
  • You can insert `import pdb; pdb.set_trace()` into your code, and pdb will be initiated on this line. You don't need any ide for this, only terminal. Pdb docs https://docs.python.org/3/library/pdb.html In short, type n for next line, p for print var, pp for pretty print your var. – Alexey Sherchenkov Oct 02 '21 at 19:48

0 Answers0