Skip to content

Instantly share code, notes, and snippets.

@iguanaonmystack
Last active June 22, 2017 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iguanaonmystack/5cf4fde37f7b066fb6c7a77cb7416883 to your computer and use it in GitHub Desktop.
Save iguanaonmystack/5cf4fde37f7b066fb6c7a77cb7416883 to your computer and use it in GitHub Desktop.
"""Simplest example to show json.load()/LimitedStream issue.
Steps to reproduce:
* $ FLASK_APP=test.py flask run
* $ echo '{"test": "data"}' | curl -X PUT -d @- -H Content-Type:application/json http://localhost:5000/get_json # works
* $ echo '{"test": "data"}' | curl -X PUT -d @- -H Content-Type:application/json http://localhost:5000/ # errors out:
Traceback:
[...]
File "[...]/venv/lib/python3.5/site-packages/flask/json.py", line 37, in _wrap_reader_for_text
fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)
AttributeError: 'LimitedStream' object has no attribute 'readable'
request.get_json() doesn't use json.load; instead uses json.loads() with the
fetched request data as a string.
request.stream wraps the raw input (request.input_stream/
request.environ['wsgi.input']) with LimitedStream to avoid hanging at the end
of the file. However LimitedStream doesn't implement everything required for
io.BufferedReader, which is an intermediate step in json.load()
"""
from flask import Flask, request
from flask import json
app = Flask(__name__)
@app.route("/", methods=['GET', 'PUT'])
def errors():
if request.method == 'PUT':
data = json.load(request.stream)
print('data received:', data)
return 'OK\n'
@app.route("/get_json", methods=['GET', 'PUT'])
def works():
if request.method == 'PUT':
data = request.get_json()
print('json received:', data)
return 'OK\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment