5

I have a simple http client in python that send the http post request like this:

import json
import urllib2
from collections import defaultdict as dd
data = dd(str)
req = urllib2.Request('http://myendpoint/test')
data["Input"] = "Hello World!"
response = urllib2.urlopen(req, json.dumps(data))

On my server side with Flask, I can define a simple function

from flask import request
@app.route('/test', methods = ['POST'])
def test():
    output = dd()
    data = request.json

And the data on server will be the same dictionary as the data on the client side.

However, now I am moving to Klein, so the server code looks like this:

@app.route('/test', methods = ['POST'])
@inlineCallbacks
def test(request):
    output = dd()
    data = request.json <=== This doesn't work

and the request that's been used in Klein does not support the same function. I wonder is there a way to get the json in Klein in the same way I got it in Flask? Thank you for reading this question.

Dekel
  • 60,707
  • 10
  • 101
  • 129
JLTChiu
  • 983
  • 3
  • 12
  • 28

1 Answers1

8

Asaik Klein doesn't give you direct access to the json data, however you can use this code to access it:

import json

@app.route('/test', methods = ['POST'])
@inlineCallbacks
def test(request):
    output = dd()
    data = json.loads(request.content.read())  # <=== This will work
Dekel
  • 60,707
  • 10
  • 101
  • 129
  • It worked! Thanks you. I just don't know how to access the content (request.content.read()) – JLTChiu Jun 06 '16 at 20:36
  • 1
    I spend hours trying "request.args.get" which does not work as expected for some reason. Then I find this post by chance and now my problem get solved. Thank!!!!!! – chanp Aug 30 '16 at 19:24
  • @chanp, glad I could help :) – Dekel Aug 30 '16 at 20:25
  • 1
    In python3 you need seem to need to decode bytes => str, e.g. `data = json.loads(request.content.read().decode('utf-8'))` – patricksurry Feb 16 '17 at 01:18