Giter Club home page Giter Club logo

pyasyncmysql's Introduction

pyasyncmysql

Данная библиотека написана для упрощения асинхронной работы с базой данных MySQL и используется мною в небольших проектах, в которых можно обойтись без SQLAlchemy.

Installation

Установите, клонировав репозиторий и установив зависимости из файла requirements.txt

Usage

import asyncio

from pyasyncmysql import DB, DBConfig

TABLE = "users"

config = DBConfig(host="127.0.0.1",
                  port=3306,
                  username="root",
                  password="",
                  database="rsa")


async def insert_rsa_session(username:        str,
                             hashed_password: str) -> None:
    async with DB(conf=config) as db:
        await db.insert(table=TABLE,
                        username=username,
                        hashed_password=hashed_password)


async def main():
    await insert_rsa_session(username="root",
                             hashed_password="17808bf2-8258-4408-835a-0c59b20715f3")

if __name__ == "__main__":
    asyncio.run(main())

Больше примеров можно найти в директории examples

Documentation

async def select(*args:    ...,
                 table:    str,
                 **kwargs: ...) -> tuple | None:
    """

    Выборка
        > SELECT (...) FROM table WHERE (...)

    :param table: Таблица
    :param args: Поля для выборки, если не указано - выборка всех полей
    :param kwargs: Пары ключ=значение для условий, если не указано - выборка всей таблицы
    :return: Выборка, если выборка не содержит строк - None
    """

async def insert(table:   str,
                **kwargs: ...) -> int:
    """

    Добавление строки в таблицу
        > INSERT INTO table VALUES (...)

    :param table: Таблица
    :param kwargs: Пары ключ-значение (имя_столбца=значение)
    :return: Возвращает id строки, если строка успешно добавлена
    """

async def delete(table:    str,
                 **kwargs: ...) -> None:
    """

    Удаление строки из таблицы по условию
        > DELETE FROM table WHERE (...)

    :param table: Название таблицы
    :param kwargs: Пары ключ=значение для условий, если не указано - удаление всех строк таблицы
    :return:
    """

async def update(table:    str,
                 **kwargs: ...) -> None:
    """

    Обновляет строку в таблице
        > UPDATE table SET (...) WHERE (where_...)

    Если условия не указаны, будут обновлены все строки

    :param table: Название таблицы
    :param kwargs: С префиксом where_ > пары ключ=значение для условий
                   Без префикса > поля, которые будут обновлены
    :return:
    """    

Authors

License

GNU GPL-3.0

pyasyncmysql's People

Watchers

Egor avatar

pyasyncmysql's Issues

TypeError if select returns None

Empty select return should be [] rather than None for better exceptions checking

async with DB(conf=DB_CONFIG) as db:
    order = await db.select(OrdersTableFields.ORDER_DATA.value,
                            table=Tables.ORDERS_TABLE.value,
                            order_id=callback_data.order_id)

    try:
        order = order[0][0]
    except IndexError:
        logger.error(msg=f"Order not found in DB: {callback_data.order_id}")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.