forked from mtusi2026/mtusi2026lab2
ЛР 2: мессенджер на PostgreSQL и сессии в Redis
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""HTTP-граница: FastAPI, коды состояния, формат ошибок, курсоры."""
|
||||
@@ -0,0 +1,28 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
from ..domain.errors import Invalid
|
||||
from ..domain.models import Keyset
|
||||
from .timefmt import from_rfc3339, to_rfc3339
|
||||
|
||||
MAX_LENGTH = 512
|
||||
|
||||
|
||||
def encode(scope: str, position: Keyset) -> str:
|
||||
payload = {'s': scope, 't': to_rfc3339(position.created_at), 'i': str(position.id)}
|
||||
raw = json.dumps(payload, separators=(',', ':'), sort_keys=True).encode('utf-8')
|
||||
return base64.urlsafe_b64encode(raw).decode('ascii').rstrip('=')
|
||||
|
||||
|
||||
def decode(scope: str, value: str) -> Keyset:
|
||||
if not value or len(value) > MAX_LENGTH:
|
||||
raise Invalid('cursor недействителен для этого запроса')
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(value + '=' * (-len(value) % 4))
|
||||
payload = json.loads(raw)
|
||||
if not isinstance(payload, dict) or payload.get('s') != scope:
|
||||
raise ValueError('scope mismatch')
|
||||
return Keyset(created_at=from_rfc3339(payload['t']), id=UUID(payload['i']))
|
||||
except Exception:
|
||||
raise Invalid('cursor недействителен для этого запроса') from None
|
||||
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, Request, status
|
||||
|
||||
from ..db.redis import RedisSessionStore
|
||||
from ..domain.errors import Unauthorized
|
||||
from ..domain.models import User
|
||||
from ..services.chats import ChatService
|
||||
from ..services.messages import MessageService
|
||||
from ..services.users import UserService
|
||||
|
||||
_BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Services:
|
||||
users: UserService
|
||||
chats: ChatService
|
||||
messages: MessageService
|
||||
sessions: RedisSessionStore
|
||||
|
||||
|
||||
def services(request: Request) -> Services:
|
||||
return request.app.state.services
|
||||
|
||||
|
||||
def user_service(container: Services = Depends(services)) -> UserService:
|
||||
return container.users
|
||||
|
||||
|
||||
def chat_service(container: Services = Depends(services)) -> ChatService:
|
||||
return container.chats
|
||||
|
||||
|
||||
def message_service(container: Services = Depends(services)) -> MessageService:
|
||||
return container.messages
|
||||
|
||||
|
||||
def session_store(container: Services = Depends(services)) -> RedisSessionStore:
|
||||
return container.sessions
|
||||
|
||||
|
||||
def _bearer_error() -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail='требуется действующая Bearer-сессия',
|
||||
headers={'WWW-Authenticate': _BEARER_CHALLENGE},
|
||||
)
|
||||
|
||||
|
||||
async def bearer_token(authorization: str | None = Header(None)) -> str:
|
||||
if not authorization:
|
||||
raise _bearer_error()
|
||||
scheme, separator, token = authorization.partition(' ')
|
||||
if scheme.lower() != 'bearer' or not separator or not token or token.strip() != token:
|
||||
raise _bearer_error()
|
||||
return token
|
||||
|
||||
|
||||
async def current_user(
|
||||
token: str = Depends(bearer_token),
|
||||
container: Services = Depends(services),
|
||||
) -> User:
|
||||
user_id = await container.sessions.get_user_id(token)
|
||||
if user_id is None:
|
||||
raise _bearer_error()
|
||||
try:
|
||||
return await container.users.identify(user_id)
|
||||
except Unauthorized:
|
||||
raise _bearer_error() from None
|
||||
@@ -0,0 +1,96 @@
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from ..domain.errors import Conflict, DomainError, Invalid, NotFound, Unauthorized, Unavailable
|
||||
|
||||
logger = logging.getLogger('app.error')
|
||||
|
||||
CODE_BY_STATUS = {
|
||||
400: 'invalid_request',
|
||||
401: 'unauthorized',
|
||||
404: 'not_found',
|
||||
409: 'conflict',
|
||||
413: 'payload_too_large',
|
||||
415: 'unsupported_media_type',
|
||||
429: 'rate_limited',
|
||||
500: 'internal_error',
|
||||
503: 'unavailable',
|
||||
}
|
||||
|
||||
STATUS_BY_DOMAIN = {
|
||||
Invalid: 400,
|
||||
Unauthorized: 401,
|
||||
NotFound: 404,
|
||||
Conflict: 409,
|
||||
Unavailable: 503,
|
||||
}
|
||||
|
||||
|
||||
def code_for(status: int) -> str:
|
||||
if status in CODE_BY_STATUS:
|
||||
return CODE_BY_STATUS[status]
|
||||
return 'invalid_request' if status < 500 else 'internal_error'
|
||||
|
||||
|
||||
def error_response(status: int, message: str, request_id: str, code: str = '') -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={'error': {'code': code or code_for(status), 'message': message, 'request_id': request_id}},
|
||||
)
|
||||
|
||||
|
||||
def _domain_status(error: DomainError) -> int:
|
||||
for kind, status in STATUS_BY_DOMAIN.items():
|
||||
if isinstance(error, kind):
|
||||
return status
|
||||
return 500
|
||||
|
||||
|
||||
def _describe(error: RequestValidationError) -> str:
|
||||
"""Краткое указание на пол, без stack trace и внутреннего устройства"""
|
||||
for item in error.errors():
|
||||
if item.get('type') == 'json_invalid':
|
||||
return 'тело запроса не является корректным JSON'
|
||||
location = '.'.join(str(part) for part in item.get('loc', ()) if part != 'body')
|
||||
return f'некорректное поле {location}' if location else 'некорректный запрос'
|
||||
return 'некорректный запрос'
|
||||
|
||||
|
||||
def request_id(request) -> str:
|
||||
return getattr(request.state, 'request_id', 'unknown')
|
||||
|
||||
|
||||
def install(app: FastAPI) -> None:
|
||||
@app.exception_handler(DomainError)
|
||||
async def _on_domain(request, error: DomainError) -> JSONResponse:
|
||||
return error_response(_domain_status(error), error.message, request_id(request))
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def _on_validation(request, error: RequestValidationError) -> JSONResponse:
|
||||
return error_response(400, _describe(error), request_id(request))
|
||||
|
||||
@app.exception_handler(SQLAlchemyError)
|
||||
async def _on_database(request, error: SQLAlchemyError) -> JSONResponse:
|
||||
logger.warning('database error request_id=%s type=%s', request_id(request), type(error).__name__)
|
||||
return error_response(503, 'база данных недоступна', request_id(request))
|
||||
|
||||
@app.exception_handler(OSError)
|
||||
async def _on_storage_socket(request, error: OSError) -> JSONResponse:
|
||||
logger.warning('storage socket error request_id=%s type=%s', request_id(request), type(error).__name__)
|
||||
return error_response(503, 'обязательное хранилище недоступно', request_id(request))
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def _on_http(request, error: StarletteHTTPException) -> JSONResponse:
|
||||
message = error.detail if isinstance(error.detail, str) and error.detail else 'ошибка запроса'
|
||||
response = error_response(error.status_code, message, request_id(request))
|
||||
for name, value in (error.headers or {}).items():
|
||||
response.headers[name] = value
|
||||
return response
|
||||
|
||||
|
||||
__all__ = ['code_for', 'error_response', 'install']
|
||||
@@ -0,0 +1,38 @@
|
||||
import logging
|
||||
from uuid import uuid4
|
||||
|
||||
from starlette.datastructures import MutableHeaders
|
||||
|
||||
from .errors import error_response
|
||||
|
||||
logger = logging.getLogger('app')
|
||||
|
||||
|
||||
class RequestContext:
|
||||
def __init__(self, app) -> None:
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope, receive, send) -> None:
|
||||
if scope['type'] != 'http':
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
request_id = uuid4().hex
|
||||
scope.setdefault('state', {})['request_id'] = request_id
|
||||
started = False
|
||||
|
||||
async def send_wrapper(message) -> None:
|
||||
nonlocal started
|
||||
if message['type'] == 'http.response.start':
|
||||
started = True
|
||||
MutableHeaders(scope=message)['X-Request-Id'] = request_id
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, send_wrapper)
|
||||
except Exception:
|
||||
logger.exception(f'unhandled error request_id={request_id} path={scope.get("path")}')
|
||||
if started:
|
||||
raise
|
||||
response = error_response(500, 'внутренняя ошибка', request_id)
|
||||
await response(scope, receive, send_wrapper)
|
||||
@@ -0,0 +1,3 @@
|
||||
from . import auth, chats, health, messages, users
|
||||
|
||||
__all__ = ['auth', 'chats', 'health', 'messages', 'users']
|
||||
@@ -0,0 +1,71 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from binascii import Error as Base64Error
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
||||
|
||||
from ...auth.tokens import create_token
|
||||
from ...db.redis import RedisSessionStore
|
||||
from ...domain.models import User
|
||||
from ...services.users import UserService
|
||||
from ..deps import bearer_token, current_user, session_store, user_service
|
||||
from ..schemas import SessionOut, UserOut
|
||||
from ..timefmt import to_rfc3339
|
||||
|
||||
router = APIRouter(prefix='/api/v1/auth/sessions', tags=['auth'])
|
||||
|
||||
_BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
|
||||
|
||||
def _unauthorized_basic() -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail='неверные учётные данные',
|
||||
headers={'WWW-Authenticate': _BASIC_CHALLENGE},
|
||||
)
|
||||
|
||||
|
||||
def _parse_basic(authorization: str | None) -> tuple[str, str]:
|
||||
if not authorization:
|
||||
raise _unauthorized_basic()
|
||||
scheme, separator, encoded = authorization.partition(' ')
|
||||
if scheme.lower() != 'basic' or not separator or not encoded:
|
||||
raise _unauthorized_basic()
|
||||
try:
|
||||
decoded = base64.b64decode(encoded, validate=True).decode('utf-8')
|
||||
except (Base64Error, UnicodeDecodeError):
|
||||
raise _unauthorized_basic() from None
|
||||
username, separator, password = decoded.partition(':')
|
||||
if not separator or not username:
|
||||
raise _unauthorized_basic()
|
||||
return username, password
|
||||
|
||||
|
||||
@router.post('', status_code=status.HTTP_201_CREATED, response_model=SessionOut)
|
||||
async def create_session(
|
||||
authorization: str | None = Header(None),
|
||||
users: UserService = Depends(user_service),
|
||||
sessions: RedisSessionStore = Depends(session_store),
|
||||
) -> SessionOut:
|
||||
username, password = _parse_basic(authorization)
|
||||
user = await users.authenticate(username, password)
|
||||
if user is None:
|
||||
raise _unauthorized_basic()
|
||||
token = create_token()
|
||||
expires_at = await sessions.create(user.id, token)
|
||||
return SessionOut(
|
||||
token=token,
|
||||
token_type='Bearer',
|
||||
expires_at=to_rfc3339(expires_at),
|
||||
user=UserOut.from_domain(user),
|
||||
)
|
||||
|
||||
|
||||
@router.delete('/current', status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||
async def revoke_session(
|
||||
token: str = Depends(bearer_token),
|
||||
_: User = Depends(current_user),
|
||||
sessions: RedisSessionStore = Depends(session_store),
|
||||
) -> None:
|
||||
await sessions.revoke(token)
|
||||
@@ -0,0 +1,49 @@
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from ...domain.models import User
|
||||
from ...services.chats import ChatService
|
||||
from .. import cursors
|
||||
from ..deps import chat_service, current_user
|
||||
from ..schemas import (
|
||||
LIMIT_DEFAULT,
|
||||
LIMIT_MAX,
|
||||
LIMIT_MIN,
|
||||
ChatOut,
|
||||
ChatPageOut,
|
||||
CreateChat,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix='/api/v1/chats', tags=['chats'])
|
||||
|
||||
|
||||
@router.post('', status_code=201, response_model=ChatOut)
|
||||
async def create(
|
||||
body: CreateChat,
|
||||
actor: User = Depends(current_user),
|
||||
chats: ChatService = Depends(chat_service),
|
||||
) -> ChatOut:
|
||||
return ChatOut.from_domain(await chats.create(actor, body.title, body.member_ids))
|
||||
|
||||
|
||||
@router.get('', response_model=ChatPageOut)
|
||||
async def page(
|
||||
actor: User = Depends(current_user),
|
||||
chats: ChatService = Depends(chat_service),
|
||||
limit: int = Query(LIMIT_DEFAULT, ge=LIMIT_MIN, le=LIMIT_MAX),
|
||||
cursor: Optional[str] = Query(None, min_length=1, max_length=cursors.MAX_LENGTH),
|
||||
) -> ChatPageOut:
|
||||
scope = f'chats:{actor.id}'
|
||||
after = cursors.decode(scope, cursor) if cursor is not None else None
|
||||
return ChatPageOut.from_domain(await chats.page(actor, after, limit), scope)
|
||||
|
||||
|
||||
@router.get('/{chat_id}', response_model=ChatOut)
|
||||
async def get(
|
||||
chat_id: UUID,
|
||||
actor: User = Depends(current_user),
|
||||
chats: ChatService = Depends(chat_service),
|
||||
) -> ChatOut:
|
||||
return ChatOut.from_domain(await chats.get(actor, chat_id))
|
||||
@@ -0,0 +1,28 @@
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from redis.exceptions import RedisError
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from ...domain.errors import Unavailable
|
||||
|
||||
from ..schemas import HealthOut
|
||||
|
||||
router = APIRouter(tags=['health'])
|
||||
|
||||
|
||||
@router.get('/health/live', response_model=HealthOut)
|
||||
async def live() -> HealthOut:
|
||||
return HealthOut(status='ok')
|
||||
|
||||
|
||||
@router.get('/health/ready', response_model=HealthOut)
|
||||
async def ready(request: Request) -> HealthOut:
|
||||
if not request.app.state.ready:
|
||||
raise HTTPException(status_code=503, detail='приложение не готово принимать трафик')
|
||||
try:
|
||||
async with request.app.state.engine.connect() as connection:
|
||||
await connection.execute(text('SELECT 1'))
|
||||
await request.app.state.redis.ping()
|
||||
except (SQLAlchemyError, RedisError, Unavailable, OSError):
|
||||
raise HTTPException(status_code=503, detail='обязательное хранилище недоступно') from None
|
||||
return HealthOut(status='ok')
|
||||
@@ -0,0 +1,42 @@
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from ...domain.models import User
|
||||
from ...services.messages import MessageService
|
||||
from .. import cursors
|
||||
from ..deps import current_user, message_service
|
||||
from ..schemas import (
|
||||
LIMIT_DEFAULT,
|
||||
LIMIT_MAX,
|
||||
LIMIT_MIN,
|
||||
CreateMessage,
|
||||
MessageOut,
|
||||
MessagePageOut,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix='/api/v1/chats/{chat_id}/messages', tags=['messages'])
|
||||
|
||||
|
||||
@router.post('', status_code=201, response_model=MessageOut)
|
||||
async def send(
|
||||
chat_id: UUID,
|
||||
body: CreateMessage,
|
||||
actor: User = Depends(current_user),
|
||||
messages: MessageService = Depends(message_service),
|
||||
) -> MessageOut:
|
||||
return MessageOut.from_domain(await messages.send(actor, chat_id, body.text))
|
||||
|
||||
|
||||
@router.get('', response_model=MessagePageOut)
|
||||
async def page(
|
||||
chat_id: UUID,
|
||||
actor: User = Depends(current_user),
|
||||
messages: MessageService = Depends(message_service),
|
||||
limit: int = Query(LIMIT_DEFAULT, ge=LIMIT_MIN, le=LIMIT_MAX),
|
||||
cursor: Optional[str] = Query(None, min_length=1, max_length=cursors.MAX_LENGTH),
|
||||
) -> MessagePageOut:
|
||||
scope = f'messages:{chat_id}'
|
||||
after = cursors.decode(scope, cursor) if cursor is not None else None
|
||||
return MessagePageOut.from_domain(await messages.history(actor, chat_id, after, limit), scope)
|
||||
@@ -0,0 +1,18 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from ...domain.models import User
|
||||
from ...services.users import UserService
|
||||
from ..deps import current_user, user_service
|
||||
from ..schemas import CreateUser, UserOut
|
||||
|
||||
router = APIRouter(prefix='/api/v1', tags=['users'])
|
||||
|
||||
|
||||
@router.post('/users', status_code=201, response_model=UserOut)
|
||||
async def register(body: CreateUser, users: UserService = Depends(user_service)) -> UserOut:
|
||||
return UserOut.from_domain(await users.register(body.username, body.display_name, body.password))
|
||||
|
||||
|
||||
@router.get('/users/me', response_model=UserOut)
|
||||
async def me(actor: User = Depends(current_user)) -> UserOut:
|
||||
return UserOut.from_domain(actor)
|
||||
@@ -0,0 +1,147 @@
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from ..domain.models import Chat, Message, Page, User
|
||||
from . import cursors
|
||||
from .timefmt import to_rfc3339
|
||||
|
||||
NAME_MAX = 100
|
||||
TEXT_MAX = 4000
|
||||
MEMBERS_MAX = 100
|
||||
LIMIT_MIN = 1
|
||||
LIMIT_MAX = 100
|
||||
LIMIT_DEFAULT = 50
|
||||
|
||||
|
||||
def not_blank(value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError('строка не может состоять только из пробельных символов')
|
||||
return value
|
||||
|
||||
|
||||
class Strict(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class HealthOut(Strict):
|
||||
status: str = 'ok'
|
||||
|
||||
|
||||
class CreateUser(Strict):
|
||||
username: str = Field(min_length=3, max_length=32, pattern=r'^[a-z0-9_]{3,32}$')
|
||||
display_name: str = Field(min_length=1, max_length=NAME_MAX)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator('display_name')
|
||||
@classmethod
|
||||
def _display_name(cls, value: str) -> str:
|
||||
return not_blank(value)
|
||||
|
||||
|
||||
class UserOut(Strict):
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
@classmethod
|
||||
def from_domain(cls, user: User) -> 'UserOut':
|
||||
return cls(
|
||||
id=user.id,
|
||||
username=user.username,
|
||||
display_name=user.display_name,
|
||||
created_at=to_rfc3339(user.created_at),
|
||||
)
|
||||
|
||||
|
||||
class SessionOut(Strict):
|
||||
token: str = Field(min_length=32)
|
||||
token_type: str = 'Bearer'
|
||||
expires_at: str
|
||||
user: UserOut
|
||||
|
||||
|
||||
class CreateChat(Strict):
|
||||
title: str = Field(min_length=1, max_length=NAME_MAX)
|
||||
member_ids: list[UUID] = Field(min_length=1, max_length=MEMBERS_MAX)
|
||||
|
||||
@field_validator('title')
|
||||
@classmethod
|
||||
def _title(cls, value: str) -> str:
|
||||
return not_blank(value)
|
||||
|
||||
@field_validator('member_ids')
|
||||
@classmethod
|
||||
def _members_unique(cls, value: list[UUID]) -> list[UUID]:
|
||||
if len(set(value)) != len(value):
|
||||
raise ValueError('member_ids не должен содержать дубликаты')
|
||||
return value
|
||||
|
||||
|
||||
class ChatOut(Strict):
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: list[UUID]
|
||||
created_at: str
|
||||
|
||||
@classmethod
|
||||
def from_domain(cls, chat: Chat) -> 'ChatOut':
|
||||
return cls(
|
||||
id=chat.id,
|
||||
title=chat.title,
|
||||
member_ids=list(chat.member_ids),
|
||||
created_at=to_rfc3339(chat.created_at),
|
||||
)
|
||||
|
||||
|
||||
class CreateMessage(Strict):
|
||||
text: str = Field(min_length=1, max_length=TEXT_MAX)
|
||||
|
||||
@field_validator('text')
|
||||
@classmethod
|
||||
def _text(cls, value: str) -> str:
|
||||
return not_blank(value)
|
||||
|
||||
|
||||
class MessageOut(Strict):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
@classmethod
|
||||
def from_domain(cls, message: Message) -> 'MessageOut':
|
||||
return cls(
|
||||
id=message.id,
|
||||
chat_id=message.chat_id,
|
||||
sender_id=message.sender_id,
|
||||
text=message.text,
|
||||
created_at=to_rfc3339(message.created_at),
|
||||
)
|
||||
|
||||
|
||||
class ChatPageOut(Strict):
|
||||
items: list[ChatOut]
|
||||
next_cursor: Optional[str]
|
||||
|
||||
@classmethod
|
||||
def from_domain(cls, page: Page, scope: str) -> 'ChatPageOut':
|
||||
return cls(
|
||||
items=[ChatOut.from_domain(chat) for chat in page.items],
|
||||
next_cursor=cursors.encode(scope, page.next) if page.next else None,
|
||||
)
|
||||
|
||||
|
||||
class MessagePageOut(Strict):
|
||||
items: list[MessageOut]
|
||||
next_cursor: Optional[str]
|
||||
|
||||
@classmethod
|
||||
def from_domain(cls, page: Page, scope: str) -> 'MessagePageOut':
|
||||
return cls(
|
||||
items=[MessageOut.from_domain(message) for message in page.items],
|
||||
next_cursor=cursors.encode(scope, page.next) if page.next else None,
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def to_rfc3339(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def from_rfc3339(value: str) -> datetime:
|
||||
if not isinstance(value, str) or not value.endswith('Z'):
|
||||
raise ValueError('timestamp must end with Z')
|
||||
return datetime.fromisoformat(value[:-1]).replace(tzinfo=timezone.utc)
|
||||
Reference in New Issue
Block a user