peewee(1)

peewee Documentation

Section 1 peewee bookworm source

Description

. .

.

\\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2]

. RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1

. RE

peewee - peewee Documentation [image]

Peewee is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use.

a small, expressive ORM

python 2.7+ and 3.4+ (developed with 3.6)

supports sqlite, mysql, postgresql and cockroachdb

tons of extensions

\%postgresql\%mysql\%sqlite\%cockroachdb

Peewee\(aqs source code hosted on \%GitHub.

New to peewee? These may help:

Quickstart

Example twitter app

Using peewee interactively

Models and fields

Querying

Relationships and joins

Most users will want to simply install the latest version, hosted on PyPI:

pip install peewee

Peewee comes with a couple C extensions that will be built if Cython is available.

Sqlite extensions, which includes Cython implementations of the SQLite date manipulation functions, the REGEXP operator, and full-text search result ranking algorithms.

The project is hosted at \%https://github.com/coleifer/peewee and can be installed using git:

git clone https://github.com/coleifer/peewee.git cd peewee python setup.py install

NOTE:

On some systems you may need to use sudo python setup.py install to install peewee system-wide.

If you would like to build the SQLite extension in a git checkout, you can run:

# Build the C extension and place shared libraries alongside other modules. python setup.py build_ext -i

You can test your installation by running the test suite.

python runtests.py

You can test specific features or specific database drivers using the runtests.py script. To view the available test runner options, use:

python runtests.py --help

NOTE:

To run tests against Postgres or MySQL you need to create a database named "peewee_test". To test the Postgres extension module, you will also want to install the HStore extension in the postgres test database:

-- install the hstore extension on the peewee_test postgres db. CREATE EXTENSION hstore;

NOTE:

To use Peewee, you typically won\(aqt need anything outside the standard library, since most Python distributions are compiled with SQLite support. You can test by running import sqlite3 in the Python console. If you wish to use another database, there are many DB-API 2.0-compatible drivers out there, such as pymysql or psycopg2 for MySQL and Postgres respectively.

\%Cython: used to expose additional functionality when using SQLite and to implement things like search result ranking in a performant manner. Since the generated C files are included with the package distribution, Cython is no longer required to use the C extensions.

\%apsw: an optional 3rd-party SQLite binding offering greater performance and comprehensive support for SQLite\(aqs C APIs. Use with APSWDatabase.

\%gevent is an optional dependency for SqliteQueueDatabase (though it works with threading just fine).

\%BerkeleyDB can be compiled with a SQLite frontend, which works with Peewee. Compiling can be tricky so \%here are instructions.

Lastly, if you use the Flask framework, there are helper extension modules available.

Peewee includes two SQLite-specific C extensions which provide additional functionality and improved performance for SQLite database users. Peewee will attempt to determine ahead-of-time if SQLite3 is installed, and only build the SQLite extensions if the SQLite shared-library is available on your system.

If, however, you receive errors like the following when attempting to install Peewee, you can explicitly disable the compilation of the SQLite C extensions by settings the NO_SQLITE environment variable.

fatal error: sqlite3.h: No such file or directory

Here is how to install Peewee with the SQLite extensions explicitly disabled:

$ NO_SQLITE=1 python setup.py install

This document presents a brief, high-level overview of Peewee\(aqs primary features. This guide will cover:

\%Model Definition

\%Storing data

\%Retrieving Data

NOTE:

If you\(aqd like something a bit more meaty, there is a thorough tutorial on creating a "twitter"-style web app using peewee and the Flask framework. In the projects examples/ folder you can find more self-contained Peewee examples, like a \%blog app.

I strongly recommend opening an interactive shell session and running the code. That way you can get a feel for typing in queries.

Model classes, fields and model instances all map to database concepts:

center; |l|l|. _ T{ Object T} T{ Corresponds to... T} _ T{ Model class T} T{ Database table T} _ T{ Field instance T} T{ Column on a table T} _ T{ Model instance T} T{ Row in a database table T} _

When starting a project with peewee, it\(aqs typically best to begin with your data model, by defining one or more Model classes:

from peewee import *

db = SqliteDatabase(\(aqpeople.db\(aq)

class Person(Model): name = CharField() birthday = DateField()

class Meta: database = db # This model uses the "people.db" database.

NOTE:

Peewee will automatically infer the database table name from the name of the class. You can override the default name by specifying a table_name attribute in the inner "Meta" class (alongside the database attribute). To learn more about how Peewee generates table names, refer to the table_names section.

Also note that we named our model Person instead of People. This is a convention you should follow -- even though the table will contain multiple people, we always name the class using the singular form.

There are lots of field types suitable for storing various types of data. Peewee handles converting between pythonic values and those used by the database, so you can use Python types in your code without having to worry.

Things get interesting when we set up relationships between models using foreign key relationships. This is simple with peewee:

class Pet(Model): owner = ForeignKeyField(Person, backref=\(aqpets\(aq) name = CharField() animal_type = CharField()

class Meta: database = db # this model uses the "people.db" database

Now that we have our models, let\(aqs connect to the database. Although it\(aqs not necessary to open the connection explicitly, it is good practice since it will reveal any errors with your database connection immediately, as opposed to some arbitrary time later when the first query is executed. It is also good to close the connection when you are done -- for instance, a web app might open a connection when it receives a request, and close the connection when it sends the response.

db.connect()

We\(aqll begin by creating the tables in the database that will store our data. This will create the tables with the appropriate columns, indexes, sequences, and foreign key constraints:

db.create_tables([Person, Pet])

Let\(aqs begin by populating the database with some people. We will use the save() and create() methods to add and update people\(aqs records.

from datetime import date uncle_bob = Person(name=\(aqBob\(aq, birthday=date(1960, 1, 15)) uncle_bob.save() # bob is now stored in the database # Returns: 1

NOTE:

When you call save(), the number of rows modified is returned.

You can also add a person by calling the create() method, which returns a model instance:

grandma = Person.create(name=\(aqGrandma\(aq, birthday=date(1935, 3, 1)) herb = Person.create(name=\(aqHerb\(aq, birthday=date(1950, 5, 5))

To update a row, modify the model instance and call save() to persist the changes. Here we will change Grandma\(aqs name and then save the changes in the database:

grandma.name = \(aqGrandma L.\(aq grandma.save() # Update grandma\(aqs name in the database. # Returns: 1

Now we have stored 3 people in the database. Let\(aqs give them some pets. Grandma doesn\(aqt like animals in the house, so she won\(aqt have any, but Herb is an animal lover:

bob_kitty = Pet.create(owner=uncle_bob, name=\(aqKitty\(aq, animal_type=\(aqcat\(aq) herb_fido = Pet.create(owner=herb, name=\(aqFido\(aq, animal_type=\(aqdog\(aq) herb_mittens = Pet.create(owner=herb, name=\(aqMittens\(aq, animal_type=\(aqcat\(aq) herb_mittens_jr = Pet.create(owner=herb, name=\(aqMittens Jr\(aq, animal_type=\(aqcat\(aq)

After a long full life, Mittens sickens and dies. We need to remove him from the database:

herb_mittens.delete_instance() # he had a great life # Returns: 1

NOTE:

The return value of delete_instance() is the number of rows removed from the database.

Uncle Bob decides that too many animals have been dying at Herb\(aqs house, so he adopts Fido:

herb_fido.owner = uncle_bob herb_fido.save()

The real strength of our database is in how it allows us to retrieve data through queries. Relational databases are excellent for making ad-hoc queries.

Let\(aqs retrieve Grandma\(aqs record from the database. To get a single record from the database, use Select.get():

grandma = Person.select().where(Person.name == \(aqGrandma L.\(aq).get()

We can also use the equivalent shorthand Model.get():

grandma = Person.get(Person.name == \(aqGrandma L.\(aq)

Let\(aqs list all the people in the database:

for person in Person.select(): print(person.name)

# prints: # Bob # Grandma L. # Herb

Let\(aqs list all the cats and their owner\(aqs name:

query = Pet.select().where(Pet.animal_type == \(aqcat\(aq) for pet in query: print(pet.name, pet.owner.name)