0

I am currently writing a flask based frontend for a university project. One of the settings an admin can change is to set a value between -1 and 12 to set the currently active repo the students can upload to.

I want the admin to be able to set this setting and then keep it persistent between server restarts. My first thought was to use the flask app config to save it as a key value. However this is not consistent between server restarts. So my next thought is to save this in a seperate configuration file or alternatively in a database, though the latter seems to be overkill for this single setting.

Is there a better way to handle this beyond a seperate configuration file that contains this value and gets imported on startup?

The_Blog
  • 31
  • 5

1 Answers1

2

You can add the repo to UPLOAD FOLDER in app.config. Add these lines to your flaskapp (at the beginning):

UPLOAD_FOLDER = 'your_path'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'jfif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

And inside route that handles the file, add this:

file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

Alternatively, you can create a txt file (let's name it 'repo.txt') and write the repo in it. Then load it in your flask (either as global variable or in specific routes, the second is recommended) with:

with open('repo.txt', 'r') as f:
    myrepo=f.read()

This way you will just have to update the txt file instead of the app itself

IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
  • First of all, thanks for the quick reply. Why is loading the file in the specific routes recommended? Wouldn't it be better performance wise to load this file once on startup, keep it as a global variable and only access it to save a new value. I imagine acessing and reading the file everytime the value is required is quite costly in terms of perfomance, is it not? – The_Blog Oct 10 '20 at 13:10
  • I added another solution, please check. Regarding txt, i think that reading a txt file of some bytes will not impact performance at all, even if it must be done thousand times during the day. You can try it first and if you see any performance reduce, you can try other options (global variable is not generally recommended, due to risks involved) – IoaTzimas Oct 10 '20 at 13:23
  • I think you have a point about the performance. However what risks about global variables are you referring to? Where would be the danger to, for example, do this: `app.config['CURRENT_REPO']=f.read()` and then just get the value when needed trough `current_app.config['CURRENT_REPO']`? – The_Blog Oct 10 '20 at 13:35
  • This would be ok, however this is not a global variable. It updates the existing file app.config that flask uses in background. Global variable means to just assign this: `my_repo='my_repo_path'` and use this inside routes by using `global my_repo` etc – IoaTzimas Oct 10 '20 at 13:37