0

I am trying to make one variables.py (reusbale module that can be used by other py files in the app) in my django project which should be set only once when the runserver command is executed.

ex. reading a csv file using pd.read_csv once at the startup of the project so that every time an API call is made, variable should not load csv file instead it should already have the dataframe value already in the variable.

How can this be achieved?

Python version - 3.6 Django - 2.1

  • 1
    take a look here https://stackoverflow.com/questions/54229592/django-run-a-script-right-after-runserver – Rafi Aug 18 '20 at 18:34

1 Answers1

2

You can set your variables in your script (`variables.py) like:

Goes in variable.py

SOME_RANDOM_VARIABLE = 'Some random data`

And then import it to the beginning of your project's settings.py file:

from your_varibles_path.variables import *

And finally when you need it anywhere in your project just do following:

from django.conf import settings

RANDOM_VARIABLE = settings.SOME_RANDOM_VARIABLE

print(RANDOM_VARIABLE)  # which will print your desired variable in your variable.py
Roham
  • 1,970
  • 2
  • 6
  • 16
  • I forgot to mention that variables.py should have a function that will be called - ex. def set_variables(): some_var = some_values There will be no loose code or variables – Saksham Tulsyan Aug 19 '20 at 07:52
  • Ok, then you can add something like `some_var = def set_variables()` to your `variables.py` and in that function you should return your variables or if your function returns multiple variables you can simply do `var_a, var_b, ... var_n = def set_variables()` . – Roham Aug 19 '20 at 08:27