我的代码命中变量的端点,然后创建日志文件(UUID.log),这些日志文件对于每次命中都是唯一的。在每个日志文件中都有一个json(process_name,Process_id),其中端点名称作为process_name登录。
在创建新文件之前,如果条件条件检查日志文件中是否有重复的process_name,以确保没有登录具有重复的process_name的日志文件。
from flask import Flask, jsonify
import json
import uuid
import os
import test1
app = Flask(__name__)
@app.route('/<string:name>')
def get_stats(name):
proceuudi = uuid.uuid4()
stat = [
{
'process_id': str(proceuudi),
'process_name': name
}
]
os.chdir("file_path")
files = os.listdir('file_path')
l=[]
for i in files:
with open(i) as f:
data = json.load(f)
for j in data:
l.append(j)
for j in l:
print(j)
if j['process_name'] != name:
with open(str(proceuudi) + '.log', 'w+') as f: # writing JSON object
json.dump(stat, f)
return jsonify({'stats':stat})
else:
return 'Process already running'
app.run(port = 6011)
每当我尝试解析包含process_name和process_id的列表(l = [])时。我无法解析整个列表。它仅检查起始索引。如果它在第一个索引处得到j ['process_name']!=名称,则返回它。有没有一种方法可以解析整个列表,然后如果在任何日志文件中都不存在process_name,则会创建具有该进程名称的日志文件。
答案 0 :(得分:0)
process_name
,因为这样可以避免扫描整个列表。app = Flask(__name__)
# use set as membership (in operator) check is O(1)
l = set()
running = False
@app.route('/<string:name>')
def get_stats(name):
global l, running
proceuudi = uuid.uuid4()
# why list as from the code it is clear that one file will have only one entry
stat = [
{
'process_id': str(proceuudi),
'process_name': name
}
]
# take all name at the start of server
if not running:
# better to write new function for this stuff
files = os.listdir('./file_path')
print files
for i in files:
with open("./file_path/"+i) as f:
data = json.load(f)
for j in data:
l.add(j["process_name"])
running = True
if name in l:
# use jsonfy here too
return jsonify("proces running")
else:
# add new process_name to in momery variable
l.add(stat[0]["process_name"])
with open("./file_path/"+str(proceuudi) + '.log', 'w+') as f: # writing JSON object
json.dump(stat, f)
return jsonify({'stats':stat})
app.run(port = 6011)
注意:W3schools reference on date methods用于此类问题。