I have a FastAPI app that worked fine until now. Here is the main router:
@router.get('/{inst_name}')
def chart(request: Request, inst_name: str):
# Initializing an instance of class 'LiveData'
lv = tse.LiveData(inst_name, 1)
data = lv.get_data_for_charts('1min')
return templates.TemplateResponse('chart.html',
{
'request': request,
'title': inst_name,
'data': data
})
Today I changed Javascript code that renders chart.html and tried to re-run the app. No matter how much I refreshed the page, I could not see the changes made. So, I decided to do a hard reload on the page, but I got a strange result. The router function was run twice ; the first one did everything as I expected, and the second one failed on the assertion check in the class initialization. Here is the __init__ method of the class:
def __init__(self, inst, avg_volume: int):
print('inst name:', inst)
self._inst_name = inst
inst_id = AllInstCodes().get_inst_id_by_name(inst)
assert inst_id is not None, 'Invalid instrument name.'
I put a print statement inside above method to see what causes the assertion to fail. The inst parameter in the second initialization of the class is favicon.ico !!!
Why the router method runs twice and where does favicon.ico come from?
>Solution :
The GET /favicon.ico request is a request your browser makes to retrieve the site’s icon that gets shown on the tab in your browser (or in your bookmarks, etc.)
You can ignore this error; it’s a request your browser makes in the background and unless you do something very specific with it (i.e. change internal state, etc.) it shouldn’t affect anything. You can create an explicit endpoint for it if you want to handle it properly and return a 404 error instead.
The reason why the endpoint runs twice is that there are two requests – your own and the browser’s request for favicon.ico.
Most common REST API designs uses the resource group name as the initial part of the path to avoid conflicts with other groups that gets added later, so you’d have:
@router.get('/instruments/{inst_name}')
instead. This will automagically give a 404 error when anyone attempts to request an undefined path.