简体   繁体   English

Python-每次用户提交表单时都写入多个JSON文件

[英]Python - Write multiple JSON files each time user submits the form

This code writes a file named vip.json. 这段代码编写了一个名为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. 每次提交表单时,类似-vip1.json,vip2.json,vip3.json等。

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? 最好的方法是什么?

This may not be the best way to do it, but you can append a UUID (Universally Unique IDentifier) if you do this: 这可能不是最佳方法,但是如果执行以下操作,则可以附加UUID(通用唯一IDentifier):

import uuid
if form.validate_on_submit():
    filename "vip-"+str(uuid.uuid4())+".json"
    with open("C:\\pytest\\"+filename,'w') as j:
        json.dump(data, j)

The probability of clashing is very low, but you can always check if the file exists and generate another one if it does. 发生冲突的可能性非常低,但是您始终可以检查文件是否存在如果存在则生成另一个文件

If you want to serialize, you can do it by: 如果要序列化,可以通过以下方法进行:

  • Storing a pickle that has your filecount 存储具有您的文件数的泡菜
  • Storing the current count in a database 将当前计数存储在数据库中
    • I do not know anything about flask or the ORM you are using (if you are), so I'll leave that up to you 我对烧瓶或您正在使用的ORM一无所知,所以我会留给您
  • Using the information in this SO post to get a list of the files and add add 1 to len(list of files) to get your count (this assumes that only these files exist in the directory) 使用此SO帖子中的信息获取文件列表,并向len(list of files)添加add 1以获取计数(假设目录中仅存在这些文件)
  • Use the same SO post to fetch the list of files, use RegEx to filter out files matching your particular pattern, then add 1 to the highest 使用相同的SO帖子获取文件列表,使用RegEx筛选出与您的特定模式匹配的文件,然后将1添加到最高

To use the pickle approach, go to the directory where your python file is, and run this once: 要使用pickle方法,请转到python文件所在的目录,然后运行一次:

import pickle
counter=1;
with open("vip_counter.pickle", "wb") as p:
    pickle.dump(p, counter)

This will store a vip_counter.pickle in your file system, where the script is run make sure that the pickle file is in the right spot 这将在运行脚本的文件系统中存储vip_counter.pickle确保pickle文件位于正确的位置

Every time before you exit, you need to update the file in the same fashion: 每次退出之前,您都需要以相同的方式更新文件:

with open("vip_counter.pickle", "rb")as p:
    counter=pickle.load()
#counter is now loaded
counter+=1 #increment your counter before the new filesave
#your code here

#save your pickle back again :)
with open("vip_counter.pickle", "wb") as p:
    pickle.dump(p, counter)

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: 您可以使用glob扫描目录,并获取所有json文件的列表,获取具有最新版本的文件,然后将其迭代一个以获取新文件的名称:

import os
import glob

# Use glob to get a list of existing vip files.
dir = "C:/pytest/"
files = glob.glob(os.path.join(dir, "vip*.json")) # Let's say it returns ["C:/pytest/vip1.json", "C:/pytest/vip2.json", "C:/pytest/vip3.json"]

# Grab the latest vip file.
latest_file = sorted(files)[-1]

# Strip the path so it's just the file's name.
file_name = os.path.splitext(os.path.basename(latest_file))[0]

# Extract the number from the file's name.
num = int(file_name.lstrip("vip"))

# Generate your new path.
new_path = os.path.join(dir, "vip{}.json".format(num + 1))
# Output of new_path: C:/pytest/vip4.json

You may need additional error checking, like if num is really a number or if there are no existing files then to default num to 1 , but I'll leave that to you. 您可能需要进行其他错误检查,例如,如果num确实是一个数字,或者如果没有现有文件,则默认将num1 ,但我将留给您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM