'How do I update Python variables in txt in real time?

I have the code below who does the work, it writes to my txt file but it will take only the last http request. The counter seems not to work, but when I use global variables it works. I tried different methods, even with dictionary. Can anyone point what I'm doing wrong?

@app.route('/request-counter', methods=['GET', 'POST', 'DELETE', 'PUT'])
def write_to_request_counts_txt():
   file = open("request_counts.txt", "w")
   counter_GET = 0
   counter_POST = 0
   counter_DELETE = 0
   counter_PUT = 0
   if request.method == 'GET':
      counter_GET += 1
   if request.method == 'POST':
      counter_POST += 1
   if request.method == 'DELETE':
      counter_DELETE += 1
   if request.method == 'PUT':
      counter_PUT += 1
   file.write(f'GET: {counter_GET} POST: {counter_POST} DELETE: {counter_DELETE} PUT: 
   {counter_PUT}')
   file.close()
   return render_template('index.html')


Solution 1:[1]

As stated by Barmar you should read the file.

Something like the code below:

@app.route('/request-counter', methods=['GET', 'POST', 'DELETE', 'PUT'])
def write_to_request_counts_txt():
    with open("request_counts.txt", "r") as r:
       line = r.read()

    line_list = line.split(';')
    counter_GET = int(line_list[0].split(":")[1].strip(" "))
    counter_POST = int(line_list[1].split(":")[1].strip(" "))
    counter_DELETE = int(line_list[2].split(":")[1].strip(" "))
    counter_PUT = int(line_list[3].split(":")[1].strip(" "))
    if request.method == 'GET':
      counter_GET += 1
    if request.method == 'POST':
      counter_POST += 1
    if request.method == 'DELETE':
      counter_DELETE += 1
    if request.method == 'PUT':
      counter_PUT += 1

    with open("request_counts.txt", "w") as w:
        w.write(f'GET: {counter_GET} ;POST: {counter_POST} ;DELETE: {counter_DELETE} ;PUT: {counter_PUT}')

    return render_template('index.html')

I did not test the code.

I chose to use csv-like string approach. But you can achieve the same result using regex. And you wouldn't need to change you file content format.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1