通过Flask REST API创建JSON文件



我想在我创建的ID文件夹中创建一个JSON文件,其中包含请求的项目名称、客户名称、客户地址和项目描述参数。

我是Python的新手,不知道怎么做。我试着找了很多,但什么也找不到。一切运行良好,直到json.dump,即最后第8行

import os
import numpy as np
from flask import Flask,jsonify,request
import json
PROJECTS_DIR_NAME       = "Projects"
ID_DIR_NAME = 'ID_variable.npy'
SCRIPT_PATH = os.path.dirname(__file__)
PR_DIR          = os.path.join(SCRIPT_PATH,PROJECTS_DIR_NAME)
ID_DIR = os.path.join(PR_DIR,ID_DIR_NAME)
app = Flask(__name__)
@app.route('/initiate',methods =['POST'])
def initiate():
path = PR_DIR
f= ID_DIR
try:
ID_variable = np.load(ID_DIR)
ID_variable = int(ID_variable)
ID_variable =ID_variable+ 1
np.save(f,ID_variable)
except FileNotFoundError:
np.save(f, 1)
ID_variable=1


os.chdir(PR_DIR)
NewProjectID= 'ID'+ str(ID_variable)
os.makedirs(NewProjectID)
path2= path+'\'+NewProjectID
os.chdir(path2)
projectname = request.args.get('projectname')
customername = request.args.get('customername')
customeraddress = request.args.get('customeraddress')
projectdescription = request.args.get('projectdescription')
json.dump({"Project Name": projectname} {"Customer Name": customername} {"Customer Address": customeraddress} {"Project Description" : projectdescription},path2)
return jsonify({'ID': ID_variable})

if __name__ == '__main__':
app.run(debug=True)

代码没有写入正确的json,您需要json.dump的文件指针

您拥有的json是一个json列表。

with open("your_file_name.json", "w") as f:
json.dump([{"Project Name": projectname}, {"Customer Name": customername},{"Customer Address": customeraddress},{"Project Description" : projectdescription}],f)

相关内容

  • 没有找到相关文章

最新更新