Django make dataframe available in view but read it just ONCE

Question:

I’m trying to accomplish the following. I’ve a simple view, something like the following

def view(request):
    df = pd.read_csv('t.csv')
    """
    Some code to parse parameters from request
    """
    y = parse_some_parameters(request)


    """ 
    Do something with df.
    """
    if request.method=="POST":
        x = do_something(df, y)
    return(JsonResponse(x))

With the current implementation, every call to the view involves reading the file. I want to avoid this. I would like to read the df once when I start the server and make it available in the view.
I tried reading the df in the settings.py file but its not visible within the view.
How would I accomplish this? Is it possible at all?

Asked By: broccoli

||

Answers:

Can’t you simply set a variable outside of the view function, loading it if not set already?

df = None

def view(request):
    global df
    if df is None:
        df = pd.read_csv('t.csv')

    """
    Some code to parse parameters from request
    """
    y = parse_some_parameters(request)


    """ 
    Do something with df.
    """
    if request.method=="POST":
        x = do_something(df, y)
    return(JsonResponse(x))
Answered By: mcsqrd
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.