Как вывести словарь json на локальном сервере python?
Вот мой код примитивного сервера:
import http.server
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
как подключить к нему json файл так, что бы доступ к данным был не по http://localhost:8080/db.json, а по http://localhost:8080/data
json файл:
{
"data": {
"barcode": "1234587867678",
"weight": "3",
"volume": "0.9",
"length_": "8",
"width": "2",
"height": "9",
"uniqueIndex": "555"
}
}
Ответы (1 шт):
Автор решения: 5c0rp
→ Ссылка
import json
import http.server
import socketserver
PORT = 8080
class Handler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/data':
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
with open('data.json') as json_data:
json_data = json.load(json_data)
self.wfile.write(bytes(json.dumps(json_data), "utf8"))
return
return super().do_GET()
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()