Access json content of request to send http with Klein in python

I have a simple http client in python that sends an HTTP request as follows:

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 datathe server will have the same dictionary dataas the client side.

However, now I move on 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 query that was used in Klein does not support the same function. I wonder if there is a way to get json in Klein the same way I got it in Flask? Thanks for reading this question.

+4
source share
1 answer

Asaik Klein json, :

import json

@app.route('/test', methods = ['POST'])
@inlineCallbacks
def test(request):
    output = dd()
    data = json.loads(request.content.read())  # <=== This will work
+7

All Articles