我有一个flask应用程序,该应用程序具有很多重复零件的功能。为了简化代码,我想调用一个辅助函数,而不是重复代码,包括变量定义。
@app.route('/update_report', methods=["POST"])
def update_report():
m_log_no = request.form.get('log_no')
m_ip_address = request.form.get('ip_address')
m_report_reason = request.form.get('report_reason')
m_status_code = request.form.get('status_code')
...
@app.route('/delete_report', methods=["POST"])
def delete_report():
m_log_no = request.form.get('log_no')
m_user_id= request.form.get('user_id')
...
我有数百个这样的功能。我想通过使用一个辅助函数来定义实例变量来简化它:
def helper_function(*args)
for arg in args:
# Work some magic of sorts:
# super.m_arg = request.form.get(arg)
@app.route('/update_report', methods=["POST"])
def update_report():
parameter_list = ('log_no', 'ip_address', 'report_reason', 'status_code')
helper_function(*parameter_list)
可以采取这种行动吗?
答案 0 :(得分:0)
只要满足您的需要,您就可以在上述几行中做一些事情。
class FormData(object):
# Using __init__ as per bruno's comment
def __init__(self, parameters_list, data_object, *args, **kwargs):
for form_key_item in parameters_list:
setattr(self, "m_{key_name}".format(key_name=form_key_item), data_object.get(form_key_item))
# Custom method
def set_args(self, parameters_list, data_object):
for form_key_item in parameters_list:
setattr(self, "m_{key_name}".format(key_name=form_key_item), data_object.get(form_key_item))
并像使用它
def some_method():
# While using the custom method for setting values
# Create your data instance
your_data_object = FormData()
# Set the value for the attributes on instance
your_data_object.set_args(parameters_list, request.form)
# While using the __init__ method
your_data_object = FormData(parameters_list, request.form)
# Use it like
print(your_data_object.m_log_no)
P.S:这是草稿,您可以使用。
答案 1 :(得分:0)
一种方法是将request
发送到辅助函数。从帮助函数返回一个包含参数和表单值的字典。
以下是此概念的演示:
app.py
:
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
def helper_function(flask_request, args):
data = {}
for arg in args:
data[arg] = flask_request.form.get(arg)
return data
@app.route('/update_report', methods=["POST"])
def update_report():
parameter_list = ('log_no', 'ip_address')
data = helper_function(request, parameter_list)
return jsonify(data)
@app.route('/delete_report', methods=["POST"])
def delete_report():
parameter_list = ('log_no', 'user_id')
data = helper_function(request, parameter_list)
return jsonify(data)
@app.route('/', methods=["GET"])
def view_reports():
return render_template("form.html")
if __name__ == '__main__':
app.run(debug=True)
form.html
:
<html>
<head>
<title>Form</title>
</head>
<body>
<h3>Update report</h3>
<form action="/update_report" method="post">
Log No: <input name="log_no" /> <br>
IP Address: <input name="ip_address" /> <br>
<input type="submit" value="Update" />
</form>
<hr>
<h3>Delete report</h3>
<form action="/delete_report" method="post">
Log No: <input name="log_no" /> <br>
User ID: <input name="user_id" /> <br>
<input type="submit" value="Delete" />
</form>
</body>
</html>
输出: