优化@app.route('/api/modify_fonts/add', methods=['POST']) def modify_fonts(): # 弹幕 data = get_data() chgfont = data.get('chgfont') modifont = data.get('modifont') if not chgfont: message = {"status": "failure", "content": "请输入要修改的字段"} print(f"异常返回{message}") return jsonify(message) if not modifont: message = {"status": "failure", "content": "请输入修改后的字段"} print(f"异常返回{message}") return jsonify(message) try: mydb = dbUtil() mycursor = mydb.cursor() query = "INSERT INTO ai_modify_fonts(createtime,chgfont,modifont,status) VALUES (now(), %s,%s,1)" values = (chgfont, modifont) mycursor.execute(query, values) mydb.commit() except Exception as e: print("发生错误:", e) message = {"status": "succeed", "content": "添加成功"} print(f"添加返回{message}") return jsonify(message)
时间: 2024-03-17 18:40:47 浏览: 55
Modify DevTools Fonts-crx插件
可以考虑以下优化:
1. 使用参数校验库,如 Flask-WTF 或 Cerberus 等,来对请求参数进行验证,避免输入不合法参数导致的异常。
2. 使用数据库连接池,如 SQLAlchemy 或 Peewee 等,来管理数据库连接,提高数据库访问性能和可靠性。
下面是优化后的代码:
```
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class ModifyFontsForm(FlaskForm):
chgfont = StringField('chgfont', validators=[DataRequired()])
modifont = StringField('modifont', validators=[DataRequired()])
@app.route('/api/modify_fonts/add', methods=['POST'])
def modify_fonts():
form = ModifyFontsForm()
if not form.validate_on_submit():
message = {"status": "failure", "content": "请求参数不合法"}
print(f"异常返回{message}")
return jsonify(message)
chgfont = form.chgfont.data
modifont = form.modifont.data
try:
with dbUtil() as mydb:
mycursor = mydb.cursor()
query = "INSERT INTO ai_modify_fonts(createtime,chgfont,modifont,status) VALUES (now(), %s,%s,1)"
values = (chgfont, modifont)
mycursor.execute(query, values)
mydb.commit()
except Exception as e:
print("发生错误:", e)
message = {"status": "failure", "content": "添加失败"}
print(f"异常返回{message}")
return jsonify(message)
message = {"status": "succeed", "content": "添加成功"}
print(f"添加返回{message}")
return jsonify(message)
```
阅读全文