繁体   English   中英

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

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

我正在尝试找出如何使用既提供html又提供json的cherrypy安装在Python 2.7中接收JSON POST数据的方法

我正在使用此脚本发送演示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()

樱桃的一面是这样的

# -*- 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)

当我启动服务器并发送请求时,我可以在领事中看到我的请求(来自打印命令),但是字符串解析失败,并出现错误TypeError:期望的字符串或缓冲区

任何提示如何解决这个问题?

更新:

问题似乎是我不明白如何处理** kwargs。 更新的代码有效(但使用非常愚蠢的方式提取JSON,直到找到正确的语法以获取第一个参数为止)

您没有利用cherrypy提供的某些内置工具,并且客户端代码没有指定正确的内容类型。

客户端代码应如下所示:(注意内容类型标头):

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()

和您的服务器代码是这样的:

# -*- 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