标签: tortoise-orm

如何使用 pytest、fastapi 和 tortoise-orm 回滚每个测试?

我正在为 crud 编写单元测试,我使用的框架是 FastAPI,ORM 是 tortoise,测试模块是 pytest。

我有这个配置文件:

import os

import pytest
from starlette.testclient import TestClient
from tortoise.contrib.fastapi import register_tortoise

from app.config import Settings, get_settings
from app.main import create_application


def get_settings_override():
    return Settings(
        testing=1, database_url=os.environ.get("DATABASE_TEST_URL")
    )

@pytest.fixture(scope="module")
def test_app_with_db():
    # set up
    app = create_application()
    app.dependency_overrides[get_settings] = get_settings_override

    # Link with DB for testing
    register_tortoise(
        app,
        db_url=os.environ.get("DATABASE_TEST_URL"),
        modules={"models": ["app.infra.postgres.models"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )
    with TestClient(app) as test_client:

        # testing
        yield test_client

    # tear down
Run Code Online (Sandbox Code Playgroud)

另外,我进行了这些测试,第一个测试创建了一个新的载体。第二个,创建一个运营商,然后搜索数据库中所有现有的运营商。

import json
from app.infra.postgres.crud.cft import cft …
Run Code Online (Sandbox Code Playgroud)

python pytest fastapi tortoise-orm

7
推荐指数
1
解决办法
3589
查看次数

使用 Tortoise-ORM 在 FastAPI 中进行测试

我正在尝试在Python 3.8下使用Tortoise ORM在FastAPI中编写一些异步测试,但我不断收到相同的错误(见最后)。过去几天我一直在试图解决这个问题,但不知何故,我最近在创建测试方面的所有努力都没有成功。

我正在关注fastapi 文档tortoise 文档

主要.py

# UserPy is a pydantic model
@app.post('/testpost')
async def world(user: UserPy) -> UserPy:
    await User.create(**user.dict())
    # Just returns the user model
    return user
Run Code Online (Sandbox Code Playgroud)

simple_test.py

from fastapi.testclient import TestClient
from httpx import AsyncClient

@pytest.fixture
def client1():
    with TestClient(app) as tc:
        yield tc

@pytest.fixture
def client2():
    initializer(DATABASE_MODELS, DATABASE_URL)
    with TestClient(app) as tc:
        yield tc
    finalizer()

@pytest.fixture
def event_loop(client2):              # Been using client1 and client2 on this
    yield …
Run Code Online (Sandbox Code Playgroud)

python python-3.8 fastapi tortoise-orm

6
推荐指数
1
解决办法
4365
查看次数

如何在 Tortoise-ORM 中使用 Postgresql 数组字段

几乎如标题所示,我正在尝试设置 Tortoise-ORM 模型,其中包含与 Postgresql 数组列相对应的字段。

似乎要正确地做到这一点,我需要从 asyncpg (因为它具有完整的数组支持)向上扩展 Tortoise Field 进行构建。然而,我刚刚开始使用乌龟,也许有一些更好/更简单的方法/有人已经做了类似的事情。

python postgresql asyncpg tortoise-orm

5
推荐指数
1
解决办法
3195
查看次数

Tortoise ORM for Python 没有返回实体的关系(Pyndantic,FastAPI)

我正在使用 Tortoise ORM 作为异步 orm 库制作一个示例 Fast Api 服务器,但我似乎无法返回我定义的关系。这些是我的关系:

# Category
from tortoise.fields.data import DatetimeField
from tortoise.models import Model
from tortoise.fields import UUIDField, CharField
from tortoise.fields.relational import ManyToManyField
from tortoise.contrib.pydantic import pydantic_model_creator


class Category(Model):
    id = UUIDField(pk=True)
    name = CharField(max_length=255)
    description = CharField(max_length=255)
    keywords = ManyToManyField(
        "models.Keyword", related_name="categories", through="category_keywords"
    )
    created_on = DatetimeField(auto_now_add=True)
    updated_on = DatetimeField(auto_now=True)



Category_dto = pydantic_model_creator(Category, name="Category", allow_cycles = True)
Run Code Online (Sandbox Code Playgroud)
# Keyword
from models.expense import Expense
from models.category import Category
from tortoise.fields.data import DatetimeField
from tortoise.fields.relational import …
Run Code Online (Sandbox Code Playgroud)

python postgresql pydantic fastapi tortoise-orm

5
推荐指数
1
解决办法
951
查看次数

Python Tortoise-ORM:在 __str__ 中使用相关模型字段

我正在使用 AIOHTTP 开发 API 服务,尝试集成一些异步 ORM,第一个候选者是 Tortoise-ORM。在 Django 项目中,我有很多链接模型,其__str__方法如下:

from tortoise.models import Model
from tortoise import fields

class Department(Model):
    id = fields.IntField(pk=True)
    title = fields.TextField()
    upper = fields.ForeignKeyField('models.Department', related_name='children')

    def __str__(self):
        if self.upper is not None:
            return f'{self.id} Department {self.title} of {self.upper.title}'
        else:
            return f'{self.id} Department {self.title}, head'

class Employee(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
    dep = fields.ForeignKeyField('models.Department', related_name='employees')

    def __str__(self):
        return f'{self.id}. Employee {self.name} of {self.dep.title}'
Run Code Online (Sandbox Code Playgroud)

以便每个对象在描述中显示其相关模型。但在 Tortoise 中我得到一个错误:

AttributeError:“QuerySet”对象没有属性“title”

我想不可能在__str__方法中等待查询。那么,是否有可能使用相关模型的字段来使用 Tortoise-ORM 创建对象表示?

python orm python-asyncio aiohttp tortoise-orm

4
推荐指数
1
解决办法
7901
查看次数

带逻辑运算符的 Tortoise ORM 过滤器

我有两张桌子

class User(models.Model):
    id = fields.BigIntField(pk=True)
    name = CharField(max_length=100)
    tags: fields.ManyToManyRelation["Tag"] = fields.ManyToManyField(
        "models.Tag", related_name="users", through="user_tags"
    )

class Tag(models.Model):
    id = fields.BigIntField(pk=True)
    name = fields.CharField(max_length=100)
    value = fields.CharField(max_length=100)
    users: fields.ManyToManyRelation[User]
Run Code Online (Sandbox Code Playgroud)

我们假设这个虚拟数据

#users
bob = await User.create(name="bob")
alice = await User.create(name="alice")

#tags
foo = await Tag.create(name="t1", value="foo")
bar = await Tag.create(name="t2", value="bar")

#m2m
await bob.tags.add(foo)
await alice.tags.add(foo, bar)
Run Code Online (Sandbox Code Playgroud)

现在我想统计同时拥有标签foo和 的用户baralice在本例中,所以应该是1

下面的查询将为我提供单级过滤,但是如何指定 应该同时user具有foo和?bartags

u = await User.filter(tags__name="t1", tags__value="foo").count()
Run Code Online (Sandbox Code Playgroud)

python orm python-3.x tortoise-orm

3
推荐指数
1
解决办法
6472
查看次数

模型关系未在 Tortoise-ORM + FastAPI 中显示

我正在使用 Tortoise-ORM 作为其 orm 来使用 FastAPI,并遇到了问题。具体来说,我无法返回模型中的关系。

\n

这是我的应用程序结构。结构的灵感来自 Django 的应用程序结构。

\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Dockerfile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 LICENSE\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Pipfile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Pipfile.lock\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 README.md\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 app\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 contacts\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.py\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 models.py\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 routers.py\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.py\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 resources\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 constants.py\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 core_model.py\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 database.py\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 middlewares.py\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 users\n\xe2\x94\x82       \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x82       \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.py\n\xe2\x94\x82       \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 models.py\n\xe2\x94\x82       \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 routers.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 docker-compose.yml\n
Run Code Online (Sandbox Code Playgroud)\n

数据库连接的设置app/resources/database.py如下;

\n
.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Dockerfile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 LICENSE\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Pipfile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Pipfile.lock\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 README.md\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 app\n\xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 contacts\n\xe2\x94\x82   \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x82   \xe2\x94\x82 …
Run Code Online (Sandbox Code Playgroud)

python python-3.x fastapi tortoise-orm

3
推荐指数
1
解决办法
3446
查看次数

如何使用 tortoise ORM 执行本机 SQL

我想使用tortoise ORM来执行原生SQL。我应该怎么办?我找不到执行此操作的方法或类。

python native-sql tortoise-orm

2
推荐指数
1
解决办法
3686
查看次数