1,801
การแก้ไข
| บรรทัดที่ 781: | บรรทัดที่ 781: | ||
== Useful Server-side Patterns == | == Useful Server-side Patterns == | ||
=== Non-redirecting Submission Route === | === Non-redirecting Submission Route === | ||
Below | Below are 2 examples for Flask routes that handle non-redirecting form submission requests. For any form that appears on multiple pages, it makes sense to write a single submit route to which all instances of the form point to. | ||
==== General Format ==== | |||
<syntaxhighlight lang='python' line=1> | |||
@<blueprint>.route("<submit_path>", methods=["POST"]) | |||
def <function_name>(*args): | |||
# CuneiForm block | |||
form = <CuneiForm_class>.init_form(...) | |||
if form.validate_on_submit(): | |||
data_dict = {} | |||
# Do something | |||
return jsonify(data_dict) | |||
else: | |||
return jsonify(dict(err=form.errors)) | |||
</syntaxhighlight> | |||
For {{code|data_dict}}, see notes under [[#Non-redirecting Form]] sub-section. | |||
==== With Database Commit ==== | |||
<syntaxhighlight lang='python' line=1> | |||
@<blueprint>.route("<submit_path>", methods=["POST"]) | |||
def <function_name>(*args): | |||
# CuneiForm block | |||
form = <CuneiForm_class>.init_form(...) | |||
db_mod_code, new_entry, resp_dict = gen_dbcommit_resp(...) | |||
if resp_dict == 403: | |||
abort(403) | |||
else: | |||
# Do something. | |||
return jsonify(resp_dict) | |||
</syntaxhighlight> | |||
The key player of this pattern is the function '''{{code|gen_dbcommit_resp}}''' that handles the most repeated routines related to form validation and database commit. | |||
<syntaxhighlight lang='python'> | |||
gen_dbcommit_resp(dbtype, tbname, model, form, perm_bit=None, allowed_action=None, | |||
suppress_success_msg=False, lock_on_add=True, head_id_col="id", | |||
get_dict=None, skip_validation=False, month=None) | |||
</syntaxhighlight> | |||
{| style="margin-left:20px;" | |||
|- style="vertical-align:top;" | |||
| style="width:120px;" | '''Parameters''' || '''DO NOT''' rely on argument order beyond ''perm_bit''. | |||
* '''form_name''' ''(str)'': The '''id''' attribute of the {{code|form_obj}}. | |||
* '''fname''' ''(str)'': The field name to be bound to the proxy. | |||
* '''proxy_ele''' ''(HTML element)'': The proxy element. | |||
* '''proxy_func''' ''(JavaScript function)'': The function to run when the form is triggered (a usual routine on a [[Multi-component Page]]). This function should accept ''1 boolean argument and returns nothing''. | |||
|} | |||
=== Data Fetching Route === | === Data Fetching Route === | ||