Skip to main content

Flask-Tortoise

Flask-Tortoise is an extension for Flask that adds support for asynchronous Tortoise-ORM to your application with in-built migration system. It aims to simplify using Tortoise-ORM with Flask by providing useful defaults and extra helpers that make it easier to accomplish common tasks.

Tortoise-ORM is one of the best tool to interact with the database asynchronously. It's clean and Django type implementation provides you a better view and understanding of the database ORM system. Also you can use the Pydantic data module to write the error-less code.

The main aim of Tortoise-ORM is to provide the same service and api like the Django-ORM.

Installing

Install and update from PYPI:

pip install -U Flask-Tortoise

Install from source code:

git clone https://github.com/marktennyson/Flask-Tortoise
cd Flask-Tortoise && pip install .

Simple Examples for better understanding:

from flask import Flask, jsonify
from flask_tortoise import Tortoise
from random import choice


STATUSES = ["New", "Old", "Gone"]

app:"Flask" = Flask(__name__)
app.config['TORTOISE_ORM_DATABASE_URI'] = 'sqlite://db.sqlite3'

db:"Tortoise" = Tortoise(app)


class Users(db.Model):
    id = db.IntField(pk=True)
    status = db.CharField(20)

    def __str__(self):
        return f"User {self.id}: {self.status}"


class Workers(db.Model):
    id = db.IntField(pk=True)
    status = db.CharField(20)

    def __str__(self):
        return f"Worker {self.id}: {self.status}"

@app.get("/")
async def list_all():
    users = await Users.all()
    workers = await Workers.all()
    return jsonify(
        {"users": [str(user) for user in users], "workers": [str(worker) for worker in workers]}
    )


@app.get("/user")
async def add_user():
    user = await Users.create(status=choice(STATUSES))  # nosec
    return str(user)


@app.get("/worker")
async def add_worker():
    worker = await Workers.create(status=choice(STATUSES))  # nosec
    return str(worker)

@app.get("/get-worker")
async def get_worker():
    worker:"Workers" = await Workers.get(id=1)
    return str(worker.status)


if __name__ == '__main__':
    app.run(debug=True, port=8080)

If you save your models into a separate file than you have mention the file name on app config:

let's assume you have stores all of your models at models.py file.

models.py file
from flask_tortoise import Tortoise, Model, fields

db:"Tortoise" = Tortoise()


class Users(db.Model):
    id = db.IntField(pk=True)
    status = db.CharField(20)

    def __str__(self):
        return f"User {self.id}: {self.status}"


class Workers(db.Model):
    id = db.IntField(pk=True)
    status = db.CharField(20)

    def __str__(self):
        return f"Worker {self.id}: {self.status}"
app.py file:
from flask import Flask, jsonify
from models import *
from random import choice


STATUSES = ["New", "Old", "Gone"]

app:"Flask" = Flask(__name__)
app.config['TORTOISE_ORM_DATABASE_URI'] = 'sqlite://db.sqlite3'
app.config['TORTOISE_ORM_MODELS'] = "models" # if you have more than one models file then : ["models_1", "models_2", "models_3"]

db.init_app(app)

@app.get("/")
async def list_all():
    users = await Users.all()
    workers = await Workers.all()
    return jsonify(
        {"users": [str(user) for user in users], "workers": [str(worker) for worker in workers]}
    )


@app.get("/user")
async def add_user():
    user = await Users.create(status=choice(STATUSES))  # nosec
    return str(user)


@app.get("/worker")
async def add_worker():
    worker = await Workers.create(status=choice(STATUSES))  # nosec
    return str(worker)

@app.get("/get-worker")
async def get_worker():
    worker:"Workers" = await Workers.get(id=1)
    return str(worker.status)


if __name__ == '__main__':
    app.run(debug=True, port=8080)

Contributing:

We welcome all types of contributions. If you face any issue while using this module then please let us know by creating a github issue on the official github repo. If you have the solution for the issue raised by you or somebody else then please fork this repo and create a pull request with the main branch.

How to run this project on local machine:
  1. Fork this repo.
  2. Clone this repo on your local machine.
  3. create a virtual environment using python virtualenv module and activate it.
  4. now run python setup.py install.
  5. the above command will install the latest dev version of Flask-Tortoise on the virtual environment.

Contributor List:

License

GNU General Public License v3 or later (GPLv3+)

Copyright (c) 2021 Aniket Sarkar(aniketsarkar@yahoo.com)

Metadata

Release files for Flask-Tortoise 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for Flask-Tortoise 0.0.1
File Size Uploaded Provenance Actions
Flask-Tortoise-0.0.1.tar.gz 28.0 kB Without provenance Details for Flask-Tortoise-0.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for Flask-Tortoise 0.0.1
File Interpreter ABI Platform Actions
Flask_Tortoise-0.0.1-py3-none-any.whl Python 3 none any Details for Flask_Tortoise-0.0.1-py3-none-any.whl

Total release size: 55.1 kB

Release files / Flask-Tortoise-0.0.1.tar.gz

Download URL Flask-Tortoise-0.0.1.tar.gz
Size 28.0 kB
Tags Source
SHA-256 checksum
How to use checksums
7dd3630ac6a1642c039b135f734333cd3a2c6ffdd65052fea6e7b731fe38dc83
BLAKE2b-256 checksum
How to use checksums
27ba184e5598b9ec4ffef0cf3ff95dd0bf0c48f2645f584e44e87ec092be2ed8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.4.2 requests/2.25.1 setuptools/45.2.0 requests-toolbelt/0.8.0 tqdm/4.61.1 CPython/3.8.10

Release files / Flask_Tortoise-0.0.1-py3-none-any.whl

Download URL Flask_Tortoise-0.0.1-py3-none-any.whl
Size 27.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e2a7c10c6ee5034b9aa9714864c547286e6a4da1f1b233a5e17dbdb69ced53d7
BLAKE2b-256 checksum
How to use checksums
e6ec0d9397b9db8a80e1aa080ba933129fa151180358236f4cfa2cab05158aa6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.4.2 requests/2.25.1 setuptools/45.2.0 requests-toolbelt/0.8.0 tqdm/4.61.1 CPython/3.8.10

Security for Flask-Tortoise 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page