【问题标题】:How to write JSON post body to a file in Python如何在 Python 中将 JSON 帖子正文写入文件
【发布时间】:2020-07-07 20:42:58
【问题描述】:

我是 Python 和开放系统技术的新手。我正在用 python 开发一个 http 服务器,它将接收来自 TPF 系统的 JSON 格式的 HTTP POST 请求。 我正在尝试从 POSTMAN 测试我的 python 服务器,我将示例 JSON POST 请求发送到在我的机器上运行的 localhost:8000,我想要的是获取 JSON POST 正文并写入文件。

我有以下代码,它将读取 JSON POST 正文并将相同的响应发送回客户端,但是我无法弄清楚如何将相同的响应转储到用户提供的文件:

from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
from datetime import datetime
import os.path
import json




class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        print('this is PNR compare service Response')
        infi = input("enter the name of the file (.json extension) to save  compare result : ")
        infi = os.path.normpath(infi)
        fi = open(infi,'a+')
        now = datetime.now()
        dt_string = now.strftime(" %d/%m/%Y %H:%M:%S\n")
        fi.write('this is PNR compare service Response at' + dt_string)
                
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()      
        response = BytesIO()
        response.write(b'This is POST request. ')
        response.write(b'Received: ')
        response.write(body)
        self.wfile.write(response.getvalue())
        #json.dump(body,fi)  
        #json.dump(response.getvalue(),fi)
        #json.dump(response.getvalue(),fi)
        fi.close()



httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
httpd.serve_forever()

由于我的响应是字节格式,json.dump 失败/发生异常(字节类型的对象不是 JSON 可序列化的),因为它需要一个 JSON 字符串。有什么简单的方法可以直接从 POST 请求中获取 JSON 正文吗?我的 post 请求将非常繁重,并且 JSON 正文非常大,因此寻找一种有效的方法来解析响应并将其转储到文件中。

【问题讨论】:

  • 您已经收到一个 JSON 对象。你想用json.loads解码它,而不是用json.dump编码它。
  • 谢谢!工作! :) 数据 = json.loads(body) json.dump(data,fi)
  • 你根本不需要解码它,如果你只是要立即重新编码它。

标签: python json output


【解决方案1】:

example answer:

import json

data = {}
data['people'] = []
data['people'].append({
    'name': 'Larry',
    'website': 'google.com',
    'from': 'Michigan'
})
data['people'].append({
    'name': 'Tim',
    'website': 'apple.com',
    'from': 'Alabama'
})

with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)

你也可以试试this solution

【讨论】:

    【解决方案2】:

    谢谢,我通过下面的代码设法做到了这一点(literal_eval 和 json.dumps 然后作为字符串写入文件),但是,我相信有更好的方法可以做到这一点,我会继续进一步探索。谢谢大家。

    从 http.server 导入 HTTPServer、BaseHTTPRequestHandler 从 io 导入 BytesIO 从日期时间导入日期时间 导入 os.path 从 ast 导入literal_eval 导入json

    类 SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        print('this is PNR compare service Response')
        infi = input("enter the name of the file (.json extension) to save  compare result : ")
        infi = os.path.normpath(infi)
        fi = open(infi,'a+')
        now = datetime.now()
        dt_string = now.strftime(" %d/%m/%Y %H:%M:%S\n")
        fi.write('\nthis is PNR compare service Response at' + dt_string)
                
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()      
        response = BytesIO()
        response.write(b'This is POST request. ')
        response.write(b'Received: ')
        response.write(body)
        self.wfile.write(response.getvalue())
    
        data = literal_eval(body.decode('utf8'))
        #s = json.dumps(data, indent=4, sort_keys=True)
        s = json.dumps(data, indent=4, sort_keys=False)
        fi.write(s)
        #json.dump(data,fi)
        
        fi.close()
    

    httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler) httpd.serve_forever()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-25
      • 2020-11-08
      • 2020-10-06
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多