flask ajax json,python flask with json

本文介绍了在Flask应用中优化代码的几个关键点:1) 不使用大写字母作为变量名,保留大写用于常量。2) 为避免额外重定向,POST请求的路由以'/'结尾。3) 使用同一个路由和函数处理GET和POST请求,简化代码。4) 使用request.form.get()方法获取表单数据,避免KeyError异常。同时展示了如何定义一个返回JSON响应的辅助函数,并提供了一个完整示例。
摘要由CSDN通过智能技术生成

0) Do not use uppercase for vars. Uppercase is always for constants.

1) Use routes with "/" at the end to avoid additional redirects which flask does:

@app.route('/user_input/', methods = ['POST'])

2) Use the same route and the same function to get what you need:

from flask import Flask, request, render_template, jsonify

def json_response(status_code, data):

res = jsonify(data)

res.status_code = status_code

return res

app = Flask(__name__)

@app.route('/user_input/', methods=["GET", "POST"])

def user_input():

if request.method == "GET":

return render_template('user-input.html')

else:

python_dictionary = {'bookName': request.form.get('Book_Name'),

'page': request.form.get('Page'),

'text': request.form.get('Text'),

'topic': request.form.get('Topic')}

return json_response(200, python_dictionary)

app.run()

3) And yes, you don't need to use json.dumps(pythonDictionary) before passing dictionary to jsonify

4) Consider to use request.form.get('key') rather than request.form['key'] because get() function returns None if there is no such key:value instead of raising key error exception.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值