1

Вот мой код примитивного сервера:

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 ответ 1

2
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()

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.