Performance: Accessing JSON data
This affects the speed of processing incoming JSON data and how quickly the server can respond to requests.
from flask import request def api(): json_data = request.get_json() # process json_data return 'OK'
from flask import request def api(): data = request.data import json json_data = json.loads(data) # process json_data return 'OK'
| Pattern | Parsing Method | Extra Steps | Server Delay | Verdict |
|---|---|---|---|---|
| Manual json.loads(request.data) | Manual decode | Extra import and decode | Higher delay due to redundant parsing | [X] Bad |
| Flask request.get_json() | Built-in parser | None | Lower delay with optimized parsing | [OK] Good |
request.get_json() to parse JSON body data safely.request.get_json() is a Python dictionary.data.get('name') safely returns the value or None if key missing, avoiding errors.from flask import Flask, request
app = Flask(__name__)
@app.route('/data', methods=['POST'])
def data():
json_data = request.get_json()
return json_data.get('age', 'No age provided'){"name": "Alice"}?json_data.get('age', 'No age provided') returns the default string when 'age' is missing.@app.route('/submit', methods=['POST'])
def submit():
data = request.get_json
return data['email']request.get_json is a method and must be called with parentheses: request.get_json().data is a method reference, not the JSON dict, causing errors on key access.request.get_json() with parentheses to get JSON data as a dict.data.get('key', default) to provide fallback values if keys are missing.Pass the test and this pattern moves unknown