【发布时间】:2021-09-02 17:29:05
【问题描述】:
我需要帮助来连接在一条路线下添加和删除路线。这个想法是将数据保存在 JSON 文件中。稍后,如果我在 JSON 文件中输入 相同的数据,应用程序会将其识别为已在 JSON 文件中并询问我要保留还是删除它 .该应用程序已设置为将数据添加到从下拉框中选择的某些 JSON 文件。但我也希望能够从这些 JSON 文件中删除/删除某些数据。我在单独的@app.routes 下有添加和删除代码。我不知道如何将它们组合在一个@app.route 下并提示要求保留或删除。我的代码如下。我对这一切都很陌生,并通过在线观看一些教程来创建它。绝对欢迎专家帮助。感谢您的宝贵时间。
烧瓶应用程序.py
#!/usr/bin/env python
# coding: utf-8
from flask import Flask, request, render_template, abort, jsonify, Response
import os
from os.path import abspath, join, isfile
import logging
import json
os.environ['FLASK_APP'] = 'PermissionsHashes'
os.environ['FLASK_ENV'] = 'development'
log = logging.getLogger('hashhost')
log.setLevel(logging.CRITICAL)
password = "password"
dataFolder = join(abspath(os.getcwd()), "Data")
app = Flask("PermissionsHashHost")
app.template_folder = join(abspath(os.getcwd()), "Templates")
@app.route('/')
def home():
return render_template("add_new.html", perms=[x for x in os.listdir(dataFolder) if x.endswith(".json")])
@app.route('/<string:requested_file>', methods=['GET', 'POST'])
def base(requested_file):
f = join(dataFolder, requested_file)
print "requested: ", f, "method: ", request.method
if not isfile(f):
if isfile(f + ".json"):
f += ".json"
else:
abort(404)
if request.method == 'GET':
with open(f, "r") as q:
return jsonify([x.encode("utf-8") if isinstance(x, unicode) else x for x in json.loads(q.read())])
elif request.method == 'POST':
if isinstance(request.form['text'], basestring):
if str(request.form['pass']) == password:
v = request.form['text']
if isinstance(v, unicode):
v = v.encode("utf-8")
print "Adding provided client: ", v, " to list "
with open(f, "r") as q:
data = [x.encode("utf-8") if isinstance(x, unicode) else x for x in json.loads(q.read())]
if v in data:
r = "Provided client is already in the list"
print r
return r
else:
data.append(v)
with open(f, "w") as q:
q.write(json.dumps(data, encoding="utf-8"))
r = "Provided client is added to the list"
print r
return r
else:
r = Response(response="Wrong Password Provided", status=401)
print r
return r
else:
r = Response(response="Input Must Be A Valid String", status=400)
print r
return r
@app.route('/<string:requested_file>/remove', methods=['POST'])
def remove(requested_file):
f = join(dataFolder, requested_file)
print "requested: ", f, "method: ", request.method
if not isfile(f):
if isfile(f + ".json"):
f += ".json"
else:
abort(404)
if isinstance(request.form['text'], basestring):
if str(request.form['pass']) == password:
v = request.form['text']
if isinstance(v, unicode):
v = v.encode("utf-8")
print "Removing provided client: ", v, " from list "
with open(f, "r") as q:
data = [x.encode("utf-8") if isinstance(x, unicode) else x for x in json.loads(q.read())]
if v not in data:
r = "Provided client is not in the list"
print r
return r
else:
data.remove(v)
with open(f, "w") as q:
q.write(json.dumps(data, encoding="utf-8"))
r = "Provided client is removed from the list"
print r
return r
else:
r = 'Wrong Password Provided'
print r
return r
else:
r = 'Input Must Be A Valid String'
print r
return r
"""@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html', title='404'), 404"""
if __name__ == '__main__':
app.run("0.0.0.0", 5000)
add_new.html 模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add new player permission</title>
<script type="text/javascript">
function OnFormSubmit() {
let permission = document.getElementById("perm").value;
let text = document.getElementById("client_str").value;
console.log(permission);
console.log(text);
}
function OnPermsChange() {
document.getElementById("form").action = "/" + document.getElementById("perm").value;
}
</script>
</head>
<body onload="OnPermsChange()">
<h1>Hello World</h1>
<h3>Submit the following form with the data.</h3>
<form method="post" id="form" onload="OnPermsChange()">
<label for="client_str">Client String (without quotes):</label><input type="text" name="text" id="client_str"><br>
<label for="password">Your password:</label><input type="password" name="pass" id="password"><br>
<label for="perm">Choose a permission:</label>
<select name="perm" id="perm" onchange="OnPermsChange()">
{% for p in perms %}
<option value="{{ p }}">{{ p[:-5] }}</option>
{% endfor %}
</select><br>
<input type="submit" onload="OnPermsChange()">
</form>
</body>
</html>
【问题讨论】:
标签: javascript python html json flask