老师,我的代码和您的不太一样,您看这样写有问题吗
来源:12-12 桩服务模型开发之更新数据
cloudonthesun
2021-07-09
handle_json.py:
import os
import sys
basePath = os.getcwd()
sys.path.append(basePath)
import json
class JsonsOperator:
def readJsons(self,filePath=None):
'''
读取filePath路径下json文件的所有信息
'''
location = None
if filePath == None:
location = basePath + "/chapter7/mock/csdn_mock.json"
else:
location = basePath + filePath
print("readJsons方法将要打开读的location是-------------》",location)
with open(location, "rb") as f:
###########json.load()用于从json文件中读取数据,返回dict类型
res = json.load(f)
# print("读取文件获得的res类型和值是:",type(res),"|",res)
return res
def getValue(self,key,filePath=None):
'''
读取指定配置json文件里,key对应的value
'''
dict = self.readJsons(filePath)
value = dict.get(key)
return value
def writeValue(self,data,path=None):
'''
向json文件写入数据(全部覆盖写入),比如写入cookie
'''
if path == None:
path = "/chapter7/config/cookie.json"
data = json.dumps(data,ensure_ascii=False)
print("(((((((((((((",data)
with open(basePath+path, "w",encoding="UTF-8") as f:
f.write(data)
def updateValue(self,key,data,path=None):
'''增加或者更新json文件key-value'''
'''要求传入的key是字符串类型,data是dict类型'''
print("updateValue方法传入的path是-------------》",path)
if path == None:
path = "/chapter7/mock/csdn_mock.json"
initialMocks = jsonsOperator.readJsons(path)
# #data需要转换为dict类型
# data = json.loads(data)
initialMocks[key] = data
jsonsOperator.writeValue(initialMocks,path)
jsonsOperator = JsonsOperator()
if(__name__ == "__main__"):
data = {
"lll":"hhhh"
}
jsonsOperator.writeValue(data)
import os
import sys
import json
#解决无法导入包的问题
basePath = os.getcwd()
sys.path.append(basePath)
from flask import Flask
from flask import request
import json
from chapter7.util.handle_json import jsonsOperator
app = Flask(__name__)
@app.route('/mock',methods=['POST'])
def mock():
request_method = request.method
if request_method == 'POST':
'''初始化返回数据'''
returnData = {
"message":None
}
json_data = {}
try:
json_data = json.loads(request.get_data())
except Exception:
print("传入data参数不是json格式")
returnData["message"] = "传入data参数不是json格式"
return returnData
url = json_data.get("url")
data = json_data.get("data")
try:
jsonsOperator.updateValue(url,data,"/chapter7/mock/csdn_mock.json")
except Exception:
returnData["message"] = "写入数据失败"
return returnData
returnData["message"] = "写入数据成功"
return returnData
# return data
else:
data = json.dumps({
'code' : 1,
'meaasge' : '请求类型应为POST'
},ensure_ascii=False)
return data
if(__name__ == '__main__'):
app.run()
我测试了运行结果正常
写回答
1回答
-
额。你觉得哪里有问题呢?我看没问题
012021-07-10
相似问题