Вот мой код:
Код: Выделить всё
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
print("---request received")
print("path:", self.path)
print("headers:", self.headers)
if self.path == "/":
body = {
"message": "Hello bro, this is your HTTP response"
}
response_body = json.dumps(body).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(response_body)))
self.end_headers()
self.wfile.write(response_body)
else:
body = {
"error": "Route not found"
}
response_body = json.dumps(body).encode("utf-8")
self.send_response(404)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(response_body)))
self.end_headers()
self.wfile.write(response_body)
server = HTTPServer(("localhost", 8000), Handler)
print("server running on localhost 8000")
server.serve_forever()
Код: Выделить всё
curl -v http://localhost:8000/
Код: Выделить всё
HTTP/1.0 200 OK
Content-Length: 52
Content-Type: application/json
Server: BaseHTTP/0.6 Python/3.10.0
Код: Выделить всё
{"message": "Hello bro, this is your HTTP response"}
Код: Выделить всё
self.send_response(200)
Код: Выделить всё
self.send_header(...)
и
Код: Выделить всё
self.wfile.write(response_body)
Но я не понимаю точного порядка и внутреннего потока.
Мои вопросы:
- Отправляет ли send_response() данные клиенту немедленно или временно сохраняет строку состояния?
- Действительно ли заголовки отправляются только тогда, когда end_headers()?
- Почему нам нужно кодировать JSON с помощью .encode("utf-8") перед его записью?
- Почему в ответе отображается HTTP/1.0, хотя я использую Curl, а в запросе написано GET / HTTP/1.1?
- Похоже ли это на то, что делают такие платформы, как FastAPI, но с большей абстракцией?
Как правильно относиться к этому процессу?>