简体   繁体   English

如何在python 2.7中以CherryPy接收JSON POST请求数据

[英]How to receive JSON POST request data in cherrypy in python 2.7

I'm trying to find out how to receive JSON POST data in Python 2.7 with a cherrypy installation that serves both html and json 我正在尝试找出如何使用既提供html又提供json的cherrypy安装在Python 2.7中接收JSON POST数据的方法

I'm using this script to send a demo JSON request 我正在使用此脚本发送演示JSON请求

import urllib2
import json

def mytest():

  d = {
    'hello': '1',
    'world': '2'
  }

  print(json.dumps(d))
  URL = 'http://localhost:8092/json_in'
  print(URL)
  post_data = json.dumps(d)

  req = urllib2.Request(URL, post_data)
  RESULT = urllib2.urlopen(req).read()
  print(RESULT)

if __name__ == '__main__':
  mytest()

The cherrypy side works like this 樱桃的一面是这样的

# -*- coding: utf-8 -*-^
import cherrypy
class WelcomePage:
    def index(self):
      return "<html><body>hello world</body><html>"
    index.exposed = True

    def json_in(self,**kwargs):
       print kwargs

       # this is dumb but works to grab the first and only argument
       for key,value in kwargs.iteritems():
         myjson = key

       parsed_json = json.loads(myjson)
       print(parsed_json['hello'])


       return "{}"

    json_in.exposed = True 


if __name__ == '__main__': 
  cherrypyconf = "cherrypy.conf" 
  cherrypy.quickstart(WelcomePage(),config=cherrypyconf)

When I start the server and send a request I can see my request in the consule (from the print command) but the string parse fails with the error TypeError: expected string or buffer 当我启动服务器并发送请求时,我可以在领事中看到我的请求(来自打印命令),但是字符串解析失败,并出现错误TypeError:期望的字符串或缓冲区

Any hint how to fix this? 任何提示如何解决这个问题?

UPDATE: 更新:

The problem seems that I didn't understand how to handle **kwargs. 问题似乎是我不明白如何处理** kwargs。 The updated code works (but uses a very dumb way to extract the JSON until I find the correct syntax to get the first argument) 更新的代码有效(但使用非常愚蠢的方式提取JSON,直到找到正确的语法以获取第一个参数为止)

You are not gaining advantage of some of the build in tools that cherrypy offers and the client code is not specifying the right content type. 您没有利用cherrypy提供的某些内置工具,并且客户端代码没有指定正确的内容类型。

The client code should looks like this: (notice the content type header): 客户端代码应如下所示:(注意内容类型标头):

import urllib2
import json

def mytest():

  d = {
    'hello': '1',
    'world': '2'
  }

  print(json.dumps(d))
  URL = 'http://localhost:8092/json_in'
  print(URL)
  post_data = json.dumps(d)

  req = urllib2.Request(URL, post_data, headers={
    'Content-Type': 'application/json'
  })
  RESULT = urllib2.urlopen(req).read()
  print(RESULT)

if __name__ == '__main__':
  mytest()

And your server code like this: 和您的服务器代码是这样的:

# -*- coding: utf-8 -*-
import cherrypy as cp


class WelcomePage:

    @cp.expose
    def index(self):
      return "<html><body>hello world</body><html>"

    @cp.expose
    @cp.tools.json_in()
    @cp.tools.json_out()
    def json_in(self):
       print(cp.request.json['hello'])
       return {}


if __name__ == '__main__':
    cherrypyconf = "cherrypy.conf"
    cp.quickstart(WelcomePage(),config=cherrypyconf)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM