Can you improve this code?

@app.route("/api/jobs", methods=["POST"])
def create\_request():
 args = dict(request.form)
 op\_name = args["op\_name"]
 del args["op\_name"]
 requester\_id = args["requester\_id"]
 del args["requester\_id"]

 filenames = [os.path.join("/app/tasks", op\_name + ".py")]
 if op\_name == "opt\_cameras":
 filenames.append("/app/tasks/opt\_cameras.cpp")
 if op\_name in ("opt\_camera\_tracks",):
 filenames.append("/app/tasks/task\_ext.cpp")
 hash\_data = []
 for filename in filenames:
 with open(filename, "rb") as f:
 hash\_data.append(f.read())
 hash\_data = b"".join(hash\_data)
 h = hashlib.md5(hash\_data).hexdigest()

 sorted\_input\_keys = sorted(args.keys())
 input\_str = "&".join([f"{k}={args[k]}" for k in sorted\_input\_keys])

 request\_id = str(uuid4())

 heartbeat = datetime.now().isoformat()
 status = "AWAITING\_CREATION"

 with open(f"interfaces/{op\_name}.json", "r") as f:
 interface = json.load(f)

 flags = []
 inputs = []
 outputs\_names = []
 outputs = {}
 for d in interface:
 if d["direction"] == "input" and args[d["name"]] == "":
 raise Exception(f"{d['name']} not specified")

 flags.append(
 f"--{d['direction']}-{d['name'].replace('\_', '-')}-{d['data\_type']}"
 )
 if d["direction"] == "output":
 dest = str(uuid4())
 if d["data\_type"] != "directory":
 dest = f"{dest}.{d['data\_type']}"
 outputs[d["name"]] = f"ref:{dest}"
 path = os.path.join("/scratch/vdp/output", dest)
 outputs\_names.append(path)
 flags.append(path)
 else:
 if d["data\_type"] in ("directory", "glb", "mp4", "txt", "npz", "bin"):
 if "ref:" in args[d["name"]]:
 path = os.path.join(
 "/scratch/vdp/output", args[d["name"]].replace("ref:", "")
 )
 else:
 path = args[d["name"]]
 inputs.append(path)
 flags.append(path)
 elif d["data\_type"] in ("string", "int", "float"):
 flags.append(args[d["name"]])
 elif d["data\_type"] == "bool":
 flags.append("1" if args[d["name"]] == "true" else "0")

 sorted\_output\_keys = sorted(outputs.keys())
 output\_str = "&".join([f"{k}={outputs[k]}" for k in sorted\_output\_keys])

 logging.info(
 "Inserting job: %s %s %s %s %s %s %s",
 request\_id,
 op\_name,
 input\_str,
 output\_str,
 heartbeat,
 status,
 h,
 )
 job = Job(
 request\_id=request\_id,
 op\_name=op\_name,
 inputs=input\_str,
 outputs=output\_str,
 pid="",
 heartbeat=heartbeat,
 status=status,
 script\_hash=h,
 dead="",
 requester\_id=requester\_id,
 )
 db.session.add(job)
 try:
 db.session.commit()
 except Exception as exc:
 logging.warning("Failed to insert job: %s, %s", request\_id, exc)
 db.session.rollback()

 job = Job.query.filter\_by(
 inputs=input\_str, op\_name=op\_name, script\_hash=h, dead=""
 ).one\_or\_none()
 assert job is not None
 assert job.dead == ""
 assert job.status != ("PENDING", "REVOKED", "FAILURE")
 if job.request\_id != request\_id:
 request\_id = job.request\_id
 logging.info("reusing job %s %s", request\_id, job.status)
 return jsonify({"request\_id": request\_id})

 progress\_file = os.path.join("/scratch/vdp/progress", request\_id)
 with open(progress\_file, "w") as f:
 json.dump({"progress": 0, "seconds": 0}, f)

 cmd = ["python", f"tasks/{op\_name}.py", "--progress-file", progress\_file] + flags
 logging.info("cmd: %s", " ".join(cmd))
 pid = run\_process.delay(cmd, request\_id, inputs, outputs\_names)
 logging.info("New task %s has status %s", pid.id, pid.status)

 logging.info("Updating job to %s: %s %s", pid.status, request\_id, pid.id)
 job.status = pid.status
 job.pid = pid.id
 job.dead = request\_id if pid.status in ("FAILURE", "REVOKED", "PENDING") else ""
 db.session.add(job)
 try:
 db.session.commit()
 except Exception as exc:
 logging.error("Failed to update job: %s", exc)
 db.session.rollback()

 return jsonify({"request\_id": request\_id})
이 코드를 개선할 수 있나요?app.route("/api/jobs", methods=["POST"])def create\_request(): args = 딕셔너리(요청.양식) op\_name = args["op\_name"] del args["op\_name"] 요청자\_id = args["요청자\_id"] del args["요청자\_id"] filenames = [os.path.join("/app/tasks", op\_name + ".py")] op\_name == "opt\_cameras": filenames.append("/app/tasks/opt\_cameras.cpp") op\_name in ("opt\_camera\_tracks",): filenames.append("/app/tasks/task\_ext.cpp") 해시\_data = [] 파일명에서 파일명에 대해: with open(filename, "rb") as f: hash\_data.append(f.read()) hash\_data = b"".join(hash\_data) h = hashlib.md5(hash\_data).hexdigest() sorted\_input\_keys = sorted(args.keys()) input\_str = "&".join([f"{k}={args[k]}" for k in sorted\_input\_keys]) 요청\_id = str(uuid4()) heartbeat = datetime.now().isoformat() status = "AWAITING\_CREATION" 열다(f"인터페이스/{op\_name}.json", "r")를 f로 사용합니다: 인터페이스 = json.load(f) flags = [] inputs = [] 출력\_이름 = [] outputs = {} 인터페이스의 d에 대해: d["direction"] == "input" and args[d["name"]] == "": raise Exception(f"{d['name']} not specified") flags.append( f"--{d['direction']}-{d['name'].replace('\_', '-')}-{d['data\_type']}" ) d['방향'] == "출력": dest = str(uuid4()) d["data\_type"] != "directory": dest = f"{dest}.{d['data\_type']}" output[d["name"]] = f"ref:{dest}" 경로 = os.path.join("/scratch/vdp/output", dest) 출력\_이름.추가(경로) flags.append(경로) else: if d["data\_type"] in ("directory", "glb", "mp4", "txt", "npz", "bin"): if "ref:" in args[d["name"]]: path = os.path.join( "/scratch/vdp/output", args[d["name"]].replace("ref:", "") ) else: path = args[d["name"]] inputs.append(경로) flags.append(경로) elif d["데이터\_type"] in ("문자열", "인트", "플로트"): flags.append(args[d["name"]]) elif d["data\_type"] == "bool": flags.append("1" if args[d["name"]] == "true" else "0") sorted\_output\_keys = sorted(outputs.keys()) output\_str = "&".join([f"{k}={outputs[k]}" for k in sorted\_output\_keys]) logging.info( "작업 삽입 중: %s %s %s %s %s %s", 요청\_id, op\_name, input\_str, output\_str, 하트비트, 상태 h, ) job = Job( 요청\_ID=요청\_ID, op\_name=op\_name, 입력=입력\_str, 출력=출력\_str, pid="", heartbeat=심장박동, status=상태, 스크립트\_해시=h, dead="", 요청자\_id=요청자\_id, ) db.session.add(job) try: db.session.commit() 예외를 예외로 제외합니다: logging.warning("작업 삽입에 실패했습니다: %s, %s", request\_id, exc) db.session.rollback() job = Job.query.filter\_by( 입력=입력\_str, OP\_이름=OP\_이름, 스크립트\_해시=h, 데드="" ).one\_or\_none() 작업이 None이 아님 어설트 assert job.dead == "" assert job.status != ("PENDING", "REVOKED", "FAILURE") if job.request\_id != request\_id: request\_id = job.request\_id logging.info("작업 %s %s 재사용 중", request\_id, job.status) 반환 jsonify({"요청\_id": 요청\_id}) progress\_file = os.path.join("/scratch/vdp/progress", request\_id) with open(progress\_file, "w") as f: json.dump({"progress": 0, "seconds": 0}, f) cmd = ["python", f"tasks/{op\_name}.py", "--progress-file", progress\_file] + flags logging.info("cmd: %s", " ".join(cmd)") pid = run\_process.delay(cmd, 요청\_id, 입력, 출력\_names) logging.info("새 작업 %s의 상태는 %s입니다", pid.id, pid.status) logging.info("작업을 %s로 업데이트 중: %s %s", pid.status, request\_id, pid.id) job.status = pid.status job.pid = pid.id job.dead = request\_id if pid.status가 ("실패", "취소됨", "보류 중") else "" db.session.add(job) try: db.session.commit() 예외를 exc로 예외: logging.error("작업 업데이트에 실패했습니다: %s", exc) db.session.rollback() return jsonify({"request\_id": request\_id})