This code writes a file named vip.json. Currently, it is overwriting the same file each time i submit the form. But, I want - Each time i click on submit in my form (which is built in flask) I want new files created for each submission. Something like - vip1.json, vip2.json, vip3.json and so on each time the form is submitted.
from flask import Flask, render_template, url_for, flash, redirect, request,
jsonify, json
from forms import RequestForm
@app.route("/home", methods=['POST'])
def home():
form = RequestForm()
employee_id = form.employee_id.data
email = form.email.data
network = form.network.data
app_name = form.app_name.data
vip_name = form.vip_name.data
pool_name = form.pool_name.data
pool_monitor = form.pool_monitor.data
pool_member = form.pool_member.data
load_balance = form.load_balance.data
ssl = form.ssl.data
data={}
data = {
'Employee ID': employee_id,
'Email': email,
'Network': network,
'App Name': app_name,
'VIP Name': vip_name,
'Pool name': pool_name,
'Pool Monitor': pool_monitor,
'Pool Member': pool_member,
'Load Balancing Method': load_balance,
'SSL': ssl
}
if form.validate_on_submit():
with open("C:\\pytest\\vip.json",'w') as j:
json.dump(data, j)
return render_template ('home.html', title='Home', data=data, form=form, employee_id=employee_id, email=email, network=network, app_name=app_name, vip_name=vip_name, pool_name=pool_name, pool_monitor=pool_monitor, pool_member=pool_member, load_balance=load_balance, ssl=ssl)
else:
return render_template('request.html', form=form)
I had a look online but i could not get anything useful. What will be the best way to do this?
You could use
glob
to scan your directory and get a list of all your json files, get the file with the latest version, then iterate it by one for the new file's name:You may need additional error checking, like if
num
is really a number or if there are no existing files then to defaultnum
to1
, but I'll leave that to you.