Exemplo n.º 1
0
async def test_bulk(
        bulk_in: BulkIn,
        model=Depends(get_model)
):
    qs = model.filter(pk__in=bulk_in.pk_list)
    pydantic = pydantic_queryset_creator(model)
    ret = await pydantic.from_queryset(qs)
    return ret.dict()
Exemplo n.º 2
0
async def run():
    await Tortoise.init(db_url="sqlite://:memory:",
                        modules={"models": ["__main__"]})
    await Tortoise.generate_schemas()

    Event_Pydantic = pydantic_model_creator(Event)
    Event_Pydantic_List = pydantic_queryset_creator(Event)
    Tournament_Pydantic = pydantic_model_creator(Tournament)
    Team_Pydantic = pydantic_model_creator(Team)

    # print(Event_Pydantic_List.schema_json(indent=4))
    # print(Event_Pydantic.schema_json(indent=4))
    # print(Tournament_Pydantic.schema_json(indent=4))
    # print(Team_Pydantic.schema_json(indent=4))

    tournament = await Tournament.create(name="New Tournament")
    tournament2 = await Tournament.create(name="Old Tournament")
    await Event.create(name="Empty")
    event = await Event.create(name="Test", tournament=tournament)
    event2 = await Event.create(name="TestLast", tournament=tournament)
    event3 = await Event.create(name="Test2", tournament=tournament2)
    await Address.create(city="Santa Monica", street="Ocean", event=event)
    await Address.create(city="Somewhere Else", street="Lane", event=event2)
    team1 = await Team.create(name="Onesies")
    team2 = await Team.create(name="T-Shirts")
    team3 = await Team.create(name="Alternates")
    await event.participants.add(team1, team2, team3)
    await event2.participants.add(team1, team2)
    await event3.participants.add(team1, team3)

    p = await Event_Pydantic.from_tortoise_orm(await Event.get(name="Test"))
    print("One Event:", p.json(indent=4))

    p = await Tournament_Pydantic.from_tortoise_orm(
        await Tournament.get(name="New Tournament"))
    print("One Tournament:", p.json(indent=4))

    p = await Team_Pydantic.from_tortoise_orm(await Team.get(name="Onesies"))
    print("One Team:", p.json(indent=4))

    pl = await Event_Pydantic_List.from_queryset(
        Event.filter(address__event_id__isnull=True))
    print("All Events without addresses:", pl.json(indent=4))
Exemplo n.º 3
0
    date = fields.DatetimeField()
    # image = fields.CharField(max_length=1000)
    # owner: fields.ForeignKeyRelation['User'] = fields.ForeignKeyField(
    #     'models.User', related_name='items'
    # )

    def min_price(self) -> float:
        return self.price + ((self.price * self.min_per)/100)

    def mid_price(self) -> float:
        mid = (self.max_per + self.min_per)/2
        return self.price + ((self.price * mid)/100)

    def max_price(self) -> float:
        return self.price + ((self.price * self.max_per)/100)

    class PydanticMeta:
        computed = ("min_price", "mid_price", "max_price")


"""Пользователи"""
UserPydantic = pydantic_model_creator(User, name="User")
UserInPydantic = pydantic_model_creator(User, name="UserIn", exclude_readonly=True)
UserPydanticList = pydantic_queryset_creator(User)
UserInPydanticList = pydantic_queryset_creator(User, include=('id',))


"""Продукт"""
ItemPydantic = pydantic_model_creator(Item, name="Items")
ItemInPydantic = pydantic_model_creator(Item, name="ItemsIn", exclude_readonly=True)
ItemPydanticList = pydantic_queryset_creator(Item)
Exemplo n.º 4
0
    id = fields.IntField(pk=True)
    email = fields.CharField(max_length=100, unique=True)
    hashed_password = fields.CharField(max_length=1000)
    is_active = fields.BooleanField(default=True)

    # При сохранении хеширование пароля по умолчанию
    async def save(self, *args, **kwargs) -> None:
        self.hashed_password = "******"
        await super().save(*args, **kwargs)

    class PydanticMeta:
        exclude = ['hashed_password']


class Item(models.Model):
    """Модель items"""
    id = fields.IntField(pk=True)
    title = fields.CharField(max_length=100)
    description = fields.TextField()
    owner = fields.ForeignKeyField('models.User', related_name='items')

    class PydanticMeta:
        allow_cycles = False


UserPydantic = pydantic_model_creator(User, name="User")
UserInPydantic = pydantic_model_creator(User, name="UserIn", exclude_readonly=True)
UserPydanticList = pydantic_queryset_creator(User)

ItemPydantic = pydantic_model_creator(Item, name="Items")
Exemplo n.º 5
0
class JobListOut(BaseModel):
    rows: pydantic_queryset_creator(Job)
    total: int
Exemplo n.º 6
0

# -*- tag -*-
# Tag create/update
TagCreateRequest = pydantic_model_creator(Tag,
                                          name="TagCreateRequest",
                                          exclude_readonly=True)

TagCreateResponse = pydantic_model_creator(Category,
                                           name="TagCreateResponse",
                                           exclude=["articles"])
TagCreateResponse.Config.json_encoders = json_encoders

# Tag List
TagListSerializer = pydantic_queryset_creator(Tag,
                                              name="TagListSerializer",
                                              exclude=["articles"])


class TagListResponse(PydanticResponse):
    results: List[TagListSerializer]


class TagResponse(BaseModel):
    id: int
    name: str


# -*- Category -*-
# Category create/update
CategoryCreateRequest = pydantic_model_creator(Category,
Exemplo n.º 7
0
    @staticmethod
    async def get_weather_for_cities(cities: list) -> None:
        tasks = []
        for city in cities:
            task = asyncio.create_task(City.get_weather(city))
            tasks.append(task)

        await asyncio.gather(*tasks)

    class PydanticMeta:
        computed = ('weather', )


class CreateCity(BaseModel):
    title: str


class CityAll(BaseModel):
    id: int
    title: str


Tortoise.init_models(settings.MODELS, 'models')

City_Pydantic = pydantic_model_creator(City, name='City')
CityIn_Pydantic = pydantic_model_creator(City,
                                         name='City',
                                         exclude_readonly=True)

City_Pydantic_List = pydantic_queryset_creator(City)
Exemplo n.º 8
0
    Business,
    CustomerDepositTransaction,
    DebitTransaction,
    TransactionStatus,
)

# Customer
InputCustomerSchema = pydantic_model_creator(Customer,
                                             exclude=("id", "wallets",
                                                      "created_at",
                                                      "modified_at"))
OutputCustomerSchema = pydantic_model_creator(Customer)

# CustomerWallet
OutputCustomerWalletSchema = pydantic_model_creator(CustomerWallet)
OutputCustomerWalletListSchema = pydantic_queryset_creator(CustomerWallet)

# Business
InputBusinessSchema = pydantic_model_creator(Business,
                                             exclude=("id", "wallets",
                                                      "created_at",
                                                      "modified_at"))
OutputBusinessSchema = pydantic_model_creator(Business)

# BusinessWallet
OutputBusinessWalletSchema = pydantic_model_creator(BusinessWallet)

# CustomerDepositTransaction
InputDepositTransactionSchema = pydantic_model_creator(
    CustomerDepositTransaction,
    exclude=("id", "customer_wallet", "created_at", "status", "error"),
Exemplo n.º 9
0
    This references a Tournament
    """

    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=100)
    #: The date-time the Tournament record was created at
    created_at = fields.DatetimeField(auto_now_add=True)

    class Meta:
        # Define the default ordering
        #  the pydantic serialiser will use this to order the results
        ordering = ["name"]


# Create a list of models for population from a queryset.
Tournament_Pydantic_List = pydantic_queryset_creator(Tournament)
# Print JSON-schema
print(Tournament_Pydantic_List.schema_json(indent=4))


async def run():
    await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]})
    await Tortoise.generate_schemas()

    # Create objects
    await Tournament.create(name="New Tournament")
    await Tournament.create(name="Another")
    await Tournament.create(name="Last Tournament")

    # Serialise it
    tourpy = await Tournament_Pydantic_List.from_queryset(Tournament.all())
Exemplo n.º 10
0
# pylint: skip-file
"""Text pydantic schemas"""
from typing import List

from pydantic.main import BaseModel
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.contrib.pydantic import pydantic_queryset_creator

from app.models.db import Text


TextOut = pydantic_model_creator(Text, name="Text")
TextList = pydantic_queryset_creator(Text, name="TextList")


class TextListOut(BaseModel):
    count: int
    items: List[TextOut]  # type: ignore
Exemplo n.º 11
0
    title = fields.CharField(max_length=300)

    class Meta:
        table = "posts"

    def datatype(self) -> str:
        return "posts"


Post_Pydantic = pydantic_model_creator(Posts, name="Post")
PostIn_Pydantic = pydantic_model_creator(Posts,
                                         name="PostIn",
                                         exclude_readonly=True)
PostsList_Pydantic = pydantic_queryset_creator(
    Posts,
    name="Posts_List_Query",
    include=(tuple(["fetched_utc"])),
    computed=(tuple(["fetched_utc_ts", "datatype", "datapath"])),
)

Posts_Display = pydantic_model_creator(
    Posts,
    name="Posts_Display_Model",
    exclude=(tuple(["fetched_utc", "created_utc"])),
)


class Comments(Basedatamodel):
    """
    The Comments model
    """
Exemplo n.º 12
0
from datetime import datetime
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from uuid import UUID

from pydantic import BaseModel
from pydantic import validator
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.contrib.pydantic import pydantic_queryset_creator

from app.models.db.challenge import Challenge

ChallengeOut = pydantic_model_creator(Challenge, name="Challenge")
ChallengeList = pydantic_queryset_creator(Challenge, name="ChallengeList")


class ChallengeListOut(BaseModel):
    count: int
    items: List[ChallengeOut]  # type: ignore


class ChallengeIn(BaseModel):
    name: str
    challenge_end: datetime
    vote_end: datetime
    is_public: bool = True
    is_open: bool = True
    track_id: UUID
Exemplo n.º 13
0
from models import Users, Image, Faces
from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator

User_Pydantic = pydantic_model_creator(Users, name="User")
UserIn_Pydantic = pydantic_model_creator(Users,
                                         name="UserIn",
                                         exclude_readonly=True)
Image_Pydantic = pydantic_model_creator(Image, name="Image")
Faces_Pydantic_List = pydantic_queryset_creator(Faces)
Faces_Pydantic = pydantic_model_creator(Faces)
Exemplo n.º 14
0
from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator

from app.models.models import User


# build `Pydantic Model`
User_Pydantic = pydantic_model_creator(User)
User_Pydantic_List = pydantic_queryset_creator(User)
Exemplo n.º 15
0
# pylint: skip-file
"""User pydantic schemas"""
from typing import List

from pydantic import BaseModel
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.contrib.pydantic import pydantic_queryset_creator

from app.models.db.user import User

UserOut = pydantic_model_creator(User, name="User")
UserIn = pydantic_model_creator(User, name="UserIn", exclude_readonly=True)

UserList = pydantic_queryset_creator(User, name="UserList")


class UserListOut(BaseModel):
    count: int
    items: List[UserOut]  # type: ignore
Exemplo n.º 16
0
'''
Description: 
Version: 1.0
Autor: Moyu
Date: 2020-11-24 14:42:46
LastEditors: Moyu
LastEditTime: 2020-11-25 16:36:30
'''
from typing import Any, List

import models
from pydantic import BaseModel
from schemas.response import AbstractPageResult, AbstractResponse
from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator

SysUserResponse = pydantic_model_creator(models.SysUser, exclude=['password'])
SysUserListResponse = pydantic_queryset_creator(models.SysUser, exclude=['password'])


class LoginResponse(AbstractResponse):
    user: SysUserResponse
    token: str
    expires_at: int


class UserListResponse(AbstractPageResult):
    items: SysUserListResponse = []
Exemplo n.º 17
0
AngelCreateDtoBase = pydantic_model_creator(
    Angel,
    exclude=(
        "id",
        "guardian",
        "contacts",
        "address",
        "guardian_id",
        "address_id",
        "created",
        "updated",
    ),
)

AngelListDto = pydantic_queryset_creator(Angel, exclude=("guardian", ))


class AngelDto(AngelDtoBase):
    """Angel Schema."""

    photo: str = Field("",
                       example="https://mosine.googlestorage.2515-1515-145")
    address: AddressDto
    surgeries: List[str] = Field(...)
    alergies: List[str] = Field(...)
    medicines: List[str] = Field(...)
    contacts: List[ContactDtoAngel]


class AngelCreateDto(AngelCreateDtoBase):
Exemplo n.º 18
0
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=50, unique=True, null=False)

    questions: fields.ReverseRelation["Question"]

    class Meta:
        table = "subjects"


Tortoise.init_models(["database.models"], "models")

User_Pydantic = pydantic_model_creator(User, name="User", exclude=("password",))
UserIn_Pydantic = pydantic_model_creator(User, name="UserIn", exclude_readonly=True)

Quiz_Pydantic = pydantic_model_creator(Quiz, name="Quiz")
QuizIn_Pydantic = pydantic_model_creator(Quiz, name="QuizIn", exclude_readonly=True)
Quiz_Pydantic_List = pydantic_queryset_creator(Quiz)

Question_Pydantic = pydantic_model_creator(Question, name="Question")
QuestionIn_Pydantic = pydantic_model_creator(Question, name="QuestionIn", exclude_readonly=True)

QuizQuestion_Pydantic = pydantic_model_creator(Question, name="QuizQuestion")
QuizQuestionIn_Pydantic = pydantic_model_creator(Question, name="QuizQuestionIn", exclude_readonly=True)

Answer_Pydantic = pydantic_model_creator(Answer, name="Answer")
AnswerIn_Pydantic = pydantic_model_creator(Answer, name="AnswerIn", exclude_readonly=True)

Subject_Pydantic = pydantic_model_creator(Subject, name="Subject", exclude=("questions",))
SubjectIn_Pydantic = pydantic_model_creator(Subject, name="SubjectIn", exclude_readonly=True)
Subject_Pydantic_List = pydantic_queryset_creator(Subject, sort_alphabetically=True, exclude=("questions",))
Exemplo n.º 19
0
import re

from typing import List

from pydantic import validator
from pydantic.main import BaseModel
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.contrib.pydantic import pydantic_queryset_creator

from app.models.db import Submission

SOUNDCLOUD_REGEX = re.compile(
    r"https://soundcloud.com/[a-zA-Z-0-9]*/[A-Za-z-0-9]*")

SubmissionOut = pydantic_model_creator(Submission, name="Submission")
SubmissionList = pydantic_queryset_creator(Submission, name="SubmissionList")


class SubmissionListOut(BaseModel):
    count: int
    items: List[SubmissionOut]  # type: ignore


class SubmissionIn(BaseModel):
    url: str

    @validator("url")
    def url_is_soundcloud(cls, value: str) -> str:
        if SOUNDCLOUD_REGEX.findall(value):
            return value
Exemplo n.º 20
0
# pylint: skip-file
"""Vote pydantic schemas"""

from typing import List
from uuid import UUID

from pydantic.main import BaseModel
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.contrib.pydantic import pydantic_queryset_creator

from app.models.db import Vote

VoteOut = pydantic_model_creator(Vote, name="Vote")
VoteList = pydantic_queryset_creator(Vote, name="VoteList")


class VoteListOut(BaseModel):
    count: int
    items: List[VoteOut]  # type: ignore


class VoteIn(BaseModel):
    submission_id: UUID


class VoteCount(BaseModel):
    count: int
Exemplo n.º 21
0
        "id",
        "parent",
        "created_at",
        "updated_at",
        "deleted_at",
        "sort",
        "title",
        "icon",
        "keep_alive",
    ),
    computed=("meta", ),
)
print(SysMenu_Pydantic.schema_json())

SysMenu_List_Pydantic = pydantic_queryset_creator(
    SysMenu,
    exclude=(
        "id",
        "parent",
        "created_at",
        "updated_at",
        "deleted_at",
        "sort",
        "title",
        "icon",
        "keep_alive",
    ),
    computed=("meta", ),
    allow_cycles=True,
)
Exemplo n.º 22
0
from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator

from historedge_backend.models import User, Page, PageVisit

InputUserSchema = pydantic_model_creator(User,
                                         exclude=("id", "created_at",
                                                  "modified_at"))
OutputUserSchema = pydantic_model_creator(User)

OutputPageListSchema = pydantic_queryset_creator(Page)

OutputPageVisitListSchema = pydantic_queryset_creator(PageVisit)