Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access json content of http post request with Klein in python

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.

like image 564
JLTChiu Avatar asked Jun 06 '16 19:06

JLTChiu


1 Answers

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
like image 121
Dekel Avatar answered Sep 25 '22 00:09

Dekel