[英]How do I update Python variables in txt in real time?
我有下面的代碼誰做的工作,它寫入我的 txt 文件,但它只需要最后一個 http 請求。 計數器似乎不起作用,但是當我使用全局變量時它起作用了。 我嘗試了不同的方法,甚至使用字典。 誰能指出我做錯了什么?
@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')
正如 Barmar 所說,您應該閱讀該文件。
類似於下面的代碼:
@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')
我沒有測試代碼。
我選擇使用類似 csv 的字符串方法。 但是您可以使用正則表達式獲得相同的結果。 而且您不需要更改文件內容格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.