Orm для postgresql python

Configuration

Connetion is made before the very first query to database. By default 20 thread safe connection pool is reserved sql.Db(‘..’, size=20) . To establish connection manually call sql.db.init() . sql.db.get() gets free database connection from the pull, after finishing a job the connection is returned back to the connection pull by calling sql.db.put(connection) .

Alternatively every model can have its own database connection and its own schema, it is achieved by extending sql.Table, the default model class:

Let us create a demo schema for a small tutorial:
We will have two tables: users and groups, users table will reference groups table to showcase some joins
           Once we have tables we create classes for representing users and groups table rows as objects:
Also defining properties is not required as orm creates object properties on the fly, but having them is much more descriptive.

Model

We extend sql.Table for our Groups model. The naming goes like this: Class name in singular [ Group ] and model name is in plural [ Groups ] as Groups model produces Group class objects:

Where type = Group attaches previously created class to a model.
    Let us pause a bit to create a friendly md5 hash function which we used in password encoder:
Storing passwords in md5 hashs is not recomended in real world scenario, you should use bcrypt instead.

Create some groups by simply calling Groups.add and passing dict type object, where keys of the object are Groups.fields dict keys:

Method will generate and run following query:

Newly created row is selected in the same query using RETURNING and converted into Group object, manager now holds

Following query will be generated:
                                    Let us create a pretty print function
Actually newly created user is an object of a class User, but pprint will visualise it like a dictionary:
Notice that password we input was plain '123' string and in query it is md5 hash thanks to encoder defined to that field 'password': .

Here we add some more users for scientific purposes:

 Wich will get user by following query and because we defined a join on Groups model, query will contain LEFT JOIN on groups table:
                Let us look inside User object
If you look closer you see that even user.group is an object, actually it is an object of the Group class.

Save

Saving happens via id and dict corresponding fields and values, save returns updated object of the user:

While savingi you pass only fields which you inted to update, at least one field is required.
                               Everything happens in same query: update, select and also join on groups table

user in case of success now contains actually updated object:

                             Difference between filter and search is that search consists with only OR criterias and filter with AND .
In addition with Table.all, Table.filter has paging and result is object of sql.Result:

But if you want to create some custom query Model class helps a lot with query templating and converting select result into objects of User:
           Field types are: string(default), int, float, bool, date and json

Field type is specified by 'type': 'int'

        If 'null' is True then None values are transfered as null , by default None value fields are ignored in inserts and updates as 'null' is False .

Json field requires keys setting:

Источник

Peewee ORM манипуляция базами данных

Ни для кого не новость, что большинство сегодняшних приложений взаимодействуют с базами данных. Особенно с движками на основе RDBMS (движки DB с поддержкой SQL). Как и любой другой язык программирования, Pyhton также предоставляет как собственные библиотеки для взаимодействия с базами данных, так и от третьих лиц. Как правило, вам нужно прописать запросы SQL для CRUD операций. Это нормально, однако иногда получается мешанина:

  • Шеф решил перейти с MySQL в… MSSQL и у вас нет выбора, кроме как кивнуть и внести правки в свои запросы в соответствии с другим движком баз данных;
  • Вам нужно сделать несколько запросов, чтобы получить одну часть данных из другой таблицы;
  • Список можно продолжать долго, не так ли?

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Чтобы разобраться с этим, в игру вступает ORM.

Введение в ORM

ORM – это акроним от Object Relational Mapping (Объектно-реляционное отображение). Но что именно оно делает?

Из википедии:

Объектно-реляционное отображение — это технология программирования, которая связывает базы данных с концепциями объектно-ориентированных языков программирования, создавая «виртуальную объектную базу данных». Существуют как проприетарные, так и свободные реализации этой технологии.
Звучит круто, да?

Что такое Peewee?

Peewee (http://docs.peewee-orm.com/en/latest/) – это небольшое ORM, которое в данный момент поддерживает postgresql, mysql и sqlite. Разумеется, это не единственное ORM для разработчиков Python. К примеру, Django предоставляет собственную ORM библиотеку, кроме этого, всегда есть SqlAlchemy. Хорошая сторона Peewee – это то, что он занимает мало места, его легко освоить, и вы можете приступить к работе с приложениями за несколько минут.

Достаточно слов, перейдем к кодам!

Установка Peewee

Как и многие другие библиотеки Python, вы можете установить Peewee при помощи pip:

Источник

Читайте также:  Menu maker in css
Оцените статью