簡體   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