Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /Voltane-EU_djfapi /djfapi /utils /fastapi_django.py
| from decimal import Decimal | |
| from enum import Enum | |
| from functools import wraps | |
| from typing import List, Optional, Union | |
| from django.core import signals | |
| from django.db.models import Manager, Q, QuerySet, aggregates | |
| from django.db.utils import ProgrammingError | |
| from fastapi.exceptions import RequestValidationError | |
| from pydantic import BaseModel, Extra | |
| from pydantic.error_wrappers import ErrorWrapper | |
| from .fastapi import Pagination | |
| try: | |
| from psycopg2.errorcodes import UNDEFINED_FUNCTION | |
| UndefinedFunction = None | |
| except ImportError: | |
| from psycopg.errors import UndefinedFunction | |
| UNDEFINED_FUNCTION = None | |
| class AggregationFunction(Enum): | |
| avg = 'avg' | |
| count = 'count' | |
| max = 'max' | |
| min = 'min' | |
| sum = 'sum' | |
| class AggregateResponse(BaseModel): | |
| class Value(BaseModel, extra=Extra.allow): | |
| value: Union[int, float, Decimal] | |
| values: List[Value] | |
| def aggregation( | |
| objects: Union[QuerySet, Manager], | |
| *, | |
| q_filters: Q = Q(), | |
| aggregation_function: Enum, | |
| field: Enum, | |
| group_by: Optional[List[str]] = None, | |
| pagination: Pagination, | |
| distinct: bool = False, | |
| ): | |
| def aggregate(): | |
| query = objects.filter(q_filters) | |
| fields = [] | |
| value = field.value if isinstance(field, Enum) else field | |
| if distinct and value == '*': | |
| raise RequestValidationError([ErrorWrapper(ValueError(), ('query', 'distinct'))]) | |
| annotations = { | |
| 'value': getattr(aggregates, aggregation_function.value.title())(value, distinct=distinct), | |
| } | |
| try: | |
| if group_by: | |
| fields += [g.value for g in group_by] | |
| query = query.values(*fields).annotate(**annotations) | |
| return list(pagination.query(query).values(*fields, 'value')) | |
| else: | |
| query = query.aggregate(**annotations) | |
| return [query] | |
| except ProgrammingError as error: | |
| if (UndefinedFunction and isinstance(error.__cause__, UndefinedFunction)) or ( | |
| UNDEFINED_FUNCTION and error.__cause__.pgcode == UNDEFINED_FUNCTION | |
| ): | |
| raise RequestValidationError( | |
| [ErrorWrapper(ProgrammingError(), ('query', 'aggregation_function'))] | |
| ) from error | |
| raise | |
| return {'values': aggregate()} | |
| def request_signalling(func): | |
| def wrapper(*args, **kwargs): | |
| signals.request_started.send(sender='request_signalling_wrapper') | |
| result = func(*args, **kwargs) | |
| signals.request_finished.send(sender='request_signalling_wrapper') | |
| return result | |
| return wrapper | |
Xet Storage Details
- Size:
- 2.67 kB
- Xet hash:
- 3074a229fcbe436faa66ef23c554f7ffb961c0b3cf0306a0616a0c3a30fb3760
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.