我是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主体?我的发布请求将非常繁重,并且将具有非常大的JSON正文,因此寻求一种有效的方法来将响应解析并转储到文件中。
答案 0 :(得分:1)
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。
答案 1 :(得分:0)
谢谢,我以某种方式通过下面的代码(literal_eval和json.dumps然后以字符串形式写入文件)来做到这一点,但是,我相信有更好的方法可以做到这一点,我将继续进行探索。谢谢大家。
从http.server导入HTTPServer,BaseHTTPRequestHandler 从io导入BytesIO 从datetime导入datetime 导入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()