Python API reference

App

The App class represents a Teo server app.

__init__

Create an app.

Examples

Create an app
app = App()

main_namespace

Retrieve the main namespace from the app. Namespace is where models, handlers, decorators and pipeline items are defined. See Namespace.

Examples

Retrieve the main namespace
main_namespace = app.main_namespace()

setup

Attach some code to run after the database is connected. The parameter Teo is in generated entities.

Examples

Run custom setup code
async def setup(teo: Teo):
  users = await teo.user.find_many({"where": {}})
  print(users)
 
app.setup(setup)

program

Define a custom program to run with Teo CLI. The parameter Teo is in generated entities.

Examples

Define a custom program
async def list_all_users(teo: Teo):
  users = await teo.user.find_many({"where": {}})
  print(users)
 
app.program("list_all_users", "description", setup)

run

Start the Teo server app.

Example

Run an server app
asyncio.run(app.run())

Namespace

Namespace is where things are defined and organized.

is_main

Whether the namespace is the main namespace.

is_std

Whether the namespace is the builtin standard namespace.

path

Get the namespace's path.

Example

Namespace's path

namespace_path: list[str] = namespace.path()

namespace

Get the namespace's child namespace by name or None.

namespace_or_create

Get the namespace's child namespace by name. If not present, create and return.

namespace_at_path

Get the namespace's child namespace at path.

namespace_or_create_at_path

The the namespace's child namespace at path. If not present, create and return.

define_model_decorator

Define a new model decorator on a namespace.

Example

Define a custom model decorator
def my_model_decorator(args: Any, model: Model):
    model.set_data("customDataKey", "customDataValue")
 
namespace.define_model_decorator("decoratorName", my_model_decorator)

define_model_field_decorator

Define a new model field decorator on a namespace.

Example

Define a custom model field decorator
def my_model_field_decorator(args: Any, field: Field):
    field.set_data("customDataKey", "customDataValue")
 
namespace.define_model_field_decorator("decoratorName", my_model_field_decorator)

define_model_relation_decorator

Define a new model relation decorator on a namespace.

Example

Define a custom model relation decorator
def my_model_relation_decorator(args: Any, relation: Relation):
    relation.set_data("customDataKey", "customDataValue")
 
namespace.define_model_relation_decorator("decoratorName", my_model_relation_decorator)

define_model_property_decorator

Define a new model property decorator on a namespace.

Example

Define a custom model property decorator
def my_model_property_decorator(args: Any, property: Property):
    property.set_data("customDataKey", "customDataValue")
 
namespace.define_model_property_decorator("decoratorName", my_model_property_decorator)

define_pipeline_item

Define a custom pipeline item on a namespace.

Example

Define a custom pipeline item
def my_pipeline_item(value: str, _args: Any, _object: User, _teo: Teo):
    return value + "-suffix"
 
app.main_namespace().define_pipeline_item("myItem", my_pipeline_item)

define_transform_pipeline_item

Define a transformer pipeline item. This is a shortcut to define_pipeline_item.

Example

Define a custom transformer
def my_append_suffix(value: str, _args: Any, _object: User, _teo: Teo):
    return value + "-suffix"
 
app.main_namespace().define_transform_pipeline_item("appendSuffix", my_append_suffix)
Define a custom transformer which errors
def my_append_suffix(value: str, _args: Any, _object: User, _teo: Teo):
    if value == "":
        raise Exception("value should not be empty")
    return value + "-suffix"
 
app.main_namespace().define_transform_pipeline_item("appendSuffix", my_append_suffix)

define_validator_pipeline_item

Define a validator pipeline item. This is a shortcut to define_pipeline_item.

Example

Define a custom validator pipeline item with bool return value
def number_is_even(value: int, _args: Any, _object: Any, _teo: Teo):
    return n % 2 == 0
 
app.main_namespace().define_validator_pipeline_item("numberIsEven", number_is_even)
Define a custom validator pipeline item with string return value
def number_is_even(value: int, _args: Any, _object: Any, _teo: Teo):
    if n % 2 == 0:
        return None
    else:
        return "value is not even"
 
app.main_namespace().define_validator_pipeline_item("numberIsEven", number_is_even)
Define a custom validator pipeline item which errors
def number_is_even(value: int, _args: Any, _object: Any, _teo: Teo):
    if n < 0:
        raise Exception("value is negative")
    elif n % 2 == 0:
        return None
    else:
        return "value is not even"
 
app.main_namespace().define_validator_pipeline_item("numberIsEven", number_is_even)

define_callback_pipeline_item

Define a callback pipeline item. This is a shortcut to define_pipeline_item.

Example

Define a custom callback pipeline item
def my_custom_callback(value: Any, _args: Any, _object: Any, _teo: Teo):
    # do something with the value
    return None
 
app.main_namespace().define_callback_pipeline_item("myCustomCallback", my_custom_callback)
Define a custom callback pipeline item which errors
def my_custom_callback(_args: Any, object: User, _teo: Teo):
    if object.email.endswith("somesuffix"):
        raise Exception("invalid operation")
    return None
 
app.main_namespace().define_callback_pipeline_item("myCustomCallback", my_custom_callback)

define_compare_pipeline_item

Define a compare pipeline item. This is a shortcut to define_pipeline_item.

Example

Define a custom compare pipeline item

def compare(old: int, new: int, _args: Any, _object: Any, _teo: Teo):
    # do some callback with the old value and the new value
    # return a validation result if the new value is invalid
    valid = true | false
    return valid
 
app.main_namespace().define_compare_pipeline_item("compare", compare)

define_middleware

Define a middleware on a namespace.

Example

Define a custom middleware
def my_wrap1(args):
    async def middleware(ctx, next):
        print("before request")
        res = await next(ctx)
        print("after request")
        return res
    return middleware
 
app.main_namespace().define_middleware("logBeforeAfter", my_middleware)

define_handler

Define a custom route handler on a namespace.

Example

Define a custom route handler
async def my_handler(_request):
    return Response.data({"myKey": "myValue"})
 
app.main_namespace().define_handler("myHandler", my_handler)

define_handler_group

Define a handler group on a namespace.

Example

Define a custom handler group
def my_group(group: HandlerGroup):
    async def my_handler(_request):
        return Response.data({"myKey": "myValue"})
    group.define_handler("myHandler", my_handler)
 
app.main_namespace().define_handler_group("MyHandlerGroup", my_group)

define_model_handler_group

Define model handlers on a namespace.

Example

Define a custom model handler group
def my_group(group: HandlerGroup):
    async def my_handler(_request: Request):
        return Response.data({"myKey": "myValue"})
    group.define_handler("myHandler", my_handler)
 
app.main_namespace().define_handler_group("User", my_group)

HandlerGroup

A handler group is a container for defining custom route handlers.

define_handler

Define a custom route handler on a handler group.

Example

Define a custom route handler
def my_group(group: HandlerGroup):
    async def my_handler(_request: Request):
        return Response.data({"myKey": "myValue"})
    group.define_handler("myHandler", my_handler)
 
app.main_namespace().define_handler_group("MyHandlerGroup", my_group)

Request

A request represents an HTTP request.

method

Retrieve the request's method.

path

Retrieve the request's path.

query_string

Retrieve the request's query string.

content_type

Retrieve the request's content type.

headers

Retrieve the request's headers.

ReadOnlyHeaderMap

The ReadOnlyHeaderMap class represents readonly headers on a request.

keys

Retrieve the header map's keys.

len

Retrieve the length of the header map.

contains_key

Whether the headers contain a specific key.

get

Retrieve the value of a header entry by key.

Response

The Response class represents an HTTP response.

empty

Create an empty response.

Example

Create an empty response
Response.empty()

string

Create a string response.

Example

Create a simple text response
Response.string("Hello, world!", "text/plain")

teon

Create a Teon response.

html

Create an HTML response.

Example

Create an HTML response
Response.html("<html><body>Hello, world!</body></html>")

data

Create a Teon response which contains a data field.

data_meta

Create a Teon response which contains a data field and a meta field.

file

Create a file response.

Example

Create a file response
Response.file("a.txt")

redirect

Create a redirect response.

Example

Create a redirect response
Response.redirect("https://example.com")

set_code

Set the response code.

code

Retrieve the response code.

headers

Retrieve the response headers.

is_empty

Whether the response body is empty.

is_file

Whether the response body is a file.

get_file

Retrieve the response file path. If the response' type is not file, None is returned.

is_text

Whether the response body is text.

get_text

Retrieve the response text. If the response' type is not text, None is returned.

is_teon

Whether the response body is a teon object.

get_teon

Retrieve the response Teon value. If the response' type is not Teon, None is returned.

ReadWriteHeaderMap

The ReadWriteHeaderMap class represents readwrite headers on a response.

keys

Retrieve the header map's keys.

len

Retrieve the length of the header map.

contains_key

Whether the headers contain a specific key.

get

Retrieve the value of a header entry by key.

set

Set a new value of a header entry at key.

Entity model

API documentation for generated model entities.

find_many

Find many objects with params same as findMany handler.

Signature

async def find_many(self, query: ModelFindManyArgs, /) -> list[ModelName]:

Arguments

NameRequiredTypeDescription
queryYesModelFindManyArgsThe finder

Examples

Find all users
users = await teo.user.find_many({})
Find users filtered by name
users = await teo.user.find_many({
    "where": {
        "name": "John"
    }
})
Find users ordered by createdAt
users = await teo.user.find_many({
    "orderBy": {
        "createdAt": "desc"
    }
})
Find users with posts
users = await teo.user().find_many({
    "include": {
        "posts": true
    }
})

find_unique

Find a unique object with params same as find_unique handler.

Signature

async def find_unique(self, query: ModelFindUniqueArgs, /) -> Optional[Model]

Arguments

NameRequiredTypeDescription
queryYesModelFindUniqueArgsThe finder

Examples

Find a unique user
user = await teo.user.find_unique({
    "where": {
        "id": 1
    }
})

find_first

Find an object with params same as find_first handler.

Signature

async def find_unique(self, query: ModelFindFirstArgs, /) -> Optional[Model]

Arguments

NameRequiredTypeDescription
queryYesModelFindFirstArgsThe finder

Examples

Find a user
user = await teo.user.find_first({
    "where": {
        "age": 20
    }
})

count_objects

Count objects in the model.

Signature

async def count_objects(self, query: ModelCountArgs, /) -> usize

Arguments

NameRequiredTypeDescription
queryYesModelCountArgsThe finder

Examples

Count objects
number_of_objects = await teo.user.count_objects({})

count_fields

Count fields in the model.

Signature

async def count_objects(self, query: ModelCountArgs, /) -> ModelCountAggregateResult

Arguments

NameRequiredTypeDescription
queryYesModelCountArgsThe finder

Examples

Count objects
count_result = await teo.user.count_fields({
    "select": {
        "createdAt": true
    }
})

aggregate

Aggregate on the model.

Signature

async def aggregate(self, query: ModelAggregateArgs, /) -> ModelAggregateResult

Arguments

NameRequiredTypeDescription
queryYes&ValueThe finder

Examples

Aggregate on the model
aggregate_result = await teo.user.aggregate({})

group_by

Group by on the model.

Signature

async def aggregate(self, query: ModelGroupByArgs, /) -> list[ModelAggregateResult]

Arguments

NameRequiredTypeDescription
queryYes&ValueThe finder

Example

Group by on the model
group_by_result = await teo.record.group_by({
    "by": "name"
})

create

Create a new model object.

Signature

async def create(self, input: ModelCreateInput, /) -> Model

Arguments

NameRequiredTypeDescription
valuesYesModelCreateInputThe create data

Examples

Create a new Post
post = await Post.create({ "title": "Post 1" })

Entity object

is_new

Returns true if object is new.

is_modified

Returns true if object is modified.

set

Set values to an object. The onSet pipeline is triggered.

Signature

async def set(self, values: ModelUpdateInput) -> None

Arguments

NameRequiredTypeDescription
valuesYesModelUpdateInputThe set data

Examples

Set values to a user
await user.set({ "name": "Peter", "age": 15 })

update

Update values on an object.

Signature

async def set(self, values: ModelScalarUpdateInput) -> None

Arguments

NameRequiredTypeDescription
valuesYesModelScalarUpdateInputThe update data

Examples

Update values on a user
await user.update({ "name": "Peter", "age": 15 })

save

Save an object.

Signature

async def save(self) -> None

Examples

Save a post
await post.save()

delete

Delete an object.

Signature

async def delete(self) -> None

Examples

Delete a post
await post.delete()

to_teon

Convert the object to a teon result value.

Signature

async def to_teon(self: Model) -> ModelResult

Examples

Convert an object to its result type
value = await object.to_teon()