在Python中检索JSON以响应POST [英] Retrieving JSON in Python in response to POST

查看:202
本文介绍了在Python中检索JSON以响应POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从服务器获取JSON以在Python代码中使用它.出于测试目的,我通过curl进行了POST:

I'm trying to get a JSON from a server to use it in a Python code. For test purposes, I did POST by curl:

$ curl -u trial:trial -H "Content-Type: application/json"
-X POST -d '{"BP_TSM":"22"}' http://some-host --trace-ascii -

我的Java代码似乎可以正确处理创建JSON作为响应.请查看curl命令的结果:

My Java code seems to correctly handle creating JSON as a response. Please look at the result of curl command:

 == Info: About to connect() to localhost port 8080 (#0)
== Info:   Trying ::1...
== Info: Connected to localhost (::1) port 8080 (#0)
== Info: Server auth using Basic with user 'trial'
=> Send header, 224 bytes (0xe0)
0000: POST /get/auth HTT
0040: P/1.1
0047: Authorization: Basic dHJpYWw6dHJpYWw=
006e: User-Agent: curl/7.29.0
0087: Host: localhost:8080
009d: Accept: */*
00aa: Content-Type: application/json
00ca: Content-Length: 15
00de: 
=> Send data, 15 bytes (0xf)
0000: {"BP_TSM":"22"}
== Info: upload completely sent off: 15 out of 15 bytes
<= Recv header, 23 bytes (0x17)
0000: HTTP/1.1 202 Accepted
<= Recv header, 34 bytes (0x22)
0000: Server: Payara Micro #badassfish
<= Recv header, 32 bytes (0x20)
0000: Content-Type: application/json
<= Recv header, 37 bytes (0x25)
0000: Date: Thu, 22 Mar 2018 14:30:43 GMT
<= Recv header, 21 bytes (0x15)
0000: Content-Length: 108
<= Recv header, 29 bytes (0x1d)
0000: X-Frame-Options: SAMEORIGIN
<= Recv header, 2 bytes (0x2)
0000: 
<= Recv data, 108 bytes (0x6c)
0000: {"title":"Free Music Archive - Albums","message":"","total":"112
0040: 59","total_pages":2252,"page":1,"limit":"5"}
{"title":"Free Music Archive - Albums","message":"","total":"11259","total_pages

":2252,"page":1,"limit":"5"}== Info: Connection #0 to host localhost left intact

现在,我希望Python脚本能够接收与curl相同的消息.我编写了以下Python代码(请注意,我不是Python开发人员):

Now I would like Python script be able to receive the same message that curl did. I wrote the following Python code (note I'm not Python developer):

import pickle
import requests
import codecs
import json
from requests.auth import HTTPBasicAuth
from random import randint
req = requests.get('server/get/auth', auth=HTTPBasicAuth('trial', 'trial'))
return pickle.dumps(req)

不幸的是,当执行return pickle.dumps(req)命令时,出现错误消息'unicode' object has no attribute 'copy'.我也尝试使用return json.dumps(req),但是这次我又遇到了另一个错误:

Unfortunately, I get error message 'unicode' object has no attribute 'copy' when return pickle.dumps(req) command is executed. I also tried using return json.dumps(req) but this time I get another error:

Traceback (most recent call last):
  File "/tmp/tmp8DfLJ7/usercode.py", line 16, in the_function
    return json.dumps(req)
  File "/usr/lib64/python2.7/json/__init__.py", line 244, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib64/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib64/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib64/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Response [405]> is not JSON serializable

我的Python代码是否有错误,还是我的Java服务器返回不正确的JSON的错误?

Do I have some error in Python code or is it fault of my Java server returning incorrect JSON?

推荐答案

您的Python代码中存在许多错误.

There are a number of errors in your Python code.

  • 您正在使用request.get进行POST.而是使用request.post.
  • 您没有将BP_TSM json字符串传递到您的请求中.在request.post中使用data=.
  • 您没有将-H开关模拟为卷曲.在request.post中使用headers=.
  • 您正在使用pickle的原因并不明显.不要那样做.
  • 当您不在函数中时,您正在使用return语句.不要那样做如果要打印到标准输出,请改用print()sys.stdout.write().
  • 如果您实际上想使用从JSON返回的变量(而不是简单地打印到stdout),则应调用req.json().
  • You are using request.get to POST. Instead, use request.post.
  • You are not passing the BP_TSM json string into your request. Use data= in your request.post.
  • You are not emulating the -H switch to curl. Use headers= in your request.post.
  • You are using pickle for no apparent reason. Don't do that.
  • You are using a return statement when you are not in a function. Don't do that. If you want to print to stdout, use print() or sys.stdout.write() instead.
  • If you actually want to use the returned variables from the JSON (as opposed to simply printing to stdout), you shoud invoke req.json().

这是您的代码的版本,已解决了问题.

Here is a version of your code with problems addressed.

import requests
import json
import sys
from requests.auth import HTTPBasicAuth

data = '{"BP_TSM": "22"}'                       # curl -d
headers = {'content-type': 'application/json'}  # curl -H
auth = HTTPBasicAuth('trial', 'trial')          # curl -u

req = requests.post(                            # curl -X POST
    'http://httpbin.org/post',
    auth=auth,
    data=data,
    headers=headers)
sys.stdout.write(req.text)         # Display JSON on stdout
returned_data = req.json()
my_ip = returned_data["origin"]    # Query value from JSON
print("My public IP is", my_ip)

这篇关于在Python中检索JSON以响应POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆