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?
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))
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?
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))