Комментарии (1)
Ответ сгенерирован нейросетью и может содержать ошибки
Response: ответ сервера на запрос
Response (ответ) — это объект, который сервер возвращает клиенту в ответ на HTTP запрос. Response содержит статус операции, заголовки (metadata) и тело ответа (данные).
Структура HTTP Response
Каждый HTTP response состоит из трёх частей:
┌─────────────────────────────────────┐
│ Status Line (Строка статуса) │ HTTP/1.1 200 OK
├─────────────────────────────────────┤
│ Headers (Заголовки) │ Content-Type: application/json
│ │ Content-Length: 124
│ │ Set-Cookie: session=abc123
├─────────────────────────────────────┤
│ Body (Тело ответа) │ {"user": "John", "age": 30}
└─────────────────────────────────────┘
1. Status Line (Строка статуса)
Определяет успешность запроса через код статуса:
HTTP/1.1 200 OK
│ │ │
│ │ └─ Текстовое объяснение
│ └────── Числовой код
└────────────── Версия протокола
Основные коды статуса:
-
2xx — Успех
- 200 OK — запрос выполнен успешно
- 201 Created — ресурс создан
- 204 No Content — успех, но нет тела ответа
-
3xx — Редирект
- 301 Moved Permanently — перманентный редирект
- 302 Found — временный редирект
- 304 Not Modified — кэш актуален
-
4xx — Ошибка клиента
- 400 Bad Request — неправильный запрос
- 401 Unauthorized — требуется авторизация
- 403 Forbidden — доступ запрещён
- 404 Not Found — ресурс не найден
-
5xx — Ошибка сервера
- 500 Internal Server Error — ошибка сервера
- 502 Bad Gateway — неправильный gateway
- 503 Service Unavailable — сервис недоступен
2. Headers (Заголовки ответа)
Это metadata, описывающие ответ:
Content-Type: application/json # Тип содержимого
Content-Length: 1234 # Размер тела
Cache-Control: max-age=3600 # Кэширование (1 час)
Set-Cookie: session=xyz; Path=/ # Установить куку
Access-Control-Allow-Origin: * # CORS разрешить всем
ETag: "123abc456" # Уникальный идентификатор версии
Location: /api/users/123 # URL перенаправления (для редирект)
X-Custom-Header: CustomValue # Кастомный заголовок
3. Body (Тело ответа)
Сама информация, которую клиент получает:
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"status": "active"
}
Response в Python (библиотека requests)
import requests
# Отправить запрос
response = requests.get('https://api.example.com/users/123')
# Доступ к компонентам Response
print(response.status_code) # 200
print(response.headers) # {'Content-Type': 'application/json'}
print(response.text) # Строка с телом
print(response.json()) # Автоматическая десериализация JSON
# Проверка статуса
if response.status_code == 200:
data = response.json()
print(f"User: {data['name']}")
elif response.status_code == 404:
print("User not found")
elif response.status_code == 500:
print("Server error")
Создание Response на сервере (FastAPI/Flask)
FastAPI:
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/api/users/{user_id}")
async def get_user(user_id: int):
# Автоматически сериализует в JSON
return {"id": user_id, "name": "John"}
@app.post("/api/users")
async def create_user(user_data: dict):
# Возврат с кастомным статус-кодом
return JSONResponse(
status_code=201,
content={"id": 1, "message": "User created"}
)
@app.get("/api/data")
async def get_data(response: Response):
# Установка заголовков вручную
response.headers["X-Custom-Header"] = "CustomValue"
response.headers["Cache-Control"] = "max-age=3600"
return {"data": [1, 2, 3]}
@app.get("/api/redirect")
async def redirect():
# Редирект
return JSONResponse(
status_code=302,
headers={"Location": "/api/home"}
)
Flask:
from flask import Flask, jsonify, make_response
app = Flask(__name__)
@app.route('/api/users/<int:user_id>')
def get_user(user_id):
# Автоматический JSON response
return jsonify({"id": user_id, "name": "John"})
@app.route('/api/users', methods=['POST'])
def create_user():
# Response с кастомным статус-кодом
response = make_response(
jsonify({"id": 1, "message": "User created"}),
201 # Created
)
return response
@app.route('/api/download')
def download():
# Возврат файла
with open('file.pdf', 'rb') as f:
response = make_response(f.read())
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = 'attachment; filename=file.pdf'
return response
Обработка Response в клиенте
Синхронный код (requests):
import requests
response = requests.get('https://api.example.com/users')
# Проверка статуса
if response.ok: # Эквивалент 200-299
users = response.json()
print(users)
else:
print(f"Error: {response.status_code}")
print(response.text) # Текст ошибки
# Обработка различных кодов
try:
response.raise_for_status() # Выбросит исключение для 4xx/5xx
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e}")
Асинхронный код (aiohttp):
import aiohttp
import asyncio
async def fetch_user(session, user_id):
async with session.get(f'https://api.example.com/users/{user_id}') as response:
if response.status == 200:
data = await response.json()
return data
else:
print(f"Error: {response.status}")
return None
async def main():
async with aiohttp.ClientSession() as session:
user = await fetch_user(session, 123)
print(user)
asyncio.run(main())
Типы Response
1. JSON Response
response = {"status": "success", "data": {}}
2. HTML Response
response = "<html><body>Hello</body></html>"
3. File Download
response = open('document.pdf', 'rb').read()
4. Stream (для больших файлов)
@app.get("/api/large-file")
async def stream_file():
def generate():
with open('large.zip', 'rb') as f:
chunk = f.read(1024 * 1024) # 1MB chunks
while chunk:
yield chunk
chunk = f.read(1024 * 1024)
return StreamingResponse(generate())
5. Redirect
from fastapi.responses import RedirectResponse
@app.get("/old-url")
async def old_endpoint():
return RedirectResponse(url="/new-url", status_code=301)
Response Headers и Кэширование
# Кэш на клиенте на 1 час
response.headers['Cache-Control'] = 'public, max-age=3600'
# Без кэша
response.headers['Cache-Control'] = 'no-cache, no-store'
# CORS
response.headers['Access-Control-Allow-Origin'] = '*'
# Безопасность
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
Вывод
Response — это центральный объект в веб-разработке. Он содержит:
- Статус — код успешности операции
- Заголовки — metadata о данных
- Тело — сами данные
Правильная работа с responses критична для создания надёжных веб-приложений.