Peewee – Using MySQL

Peewee – Using MySQL ”; Previous Next As mentioned earlier, Peewee supports MySQL database through MySQLDatabase class. However, unlike SQLite database, Peewee can’t create a MySql database. You need to create it manually or using functionality of DB-API compliant module such as pymysql. First, you should have MySQL server installed in your machine. It can be a standalone MySQL server installed from https://dev.mysql.com/downloads/installer/. You can also work on Apache bundled with MySQL (such as XAMPP downloaded and installed from https://www.apachefriends.org/download.html ). Next, we install pymysql module, DB-API compatible Python driver. pip install pymysql The create a new database named mydatabase. We shall use phpmyadmin interface available in XAMPP. If you choose to create database programmatically, use following Python script − import pymysql conn = pymysql.connect(host=”localhost”, user=”root”, password=””) conn.cursor().execute(”CREATE DATABASE mydatabase”) conn.close() Once a database is created on the server, we can now declare a model and thereby, create a mapped table in it. The MySQLDatabase object requires server credentials such as host, port, user name and password. from peewee import * db = MySQLDatabase(”mydatabase”, host=”localhost”, port=3306, user=”root”, password=””) class MyUser (Model): name=TextField() city=TextField(constraints=[SQL(“DEFAULT ”Mumbai””)]) age=IntegerField() class Meta: database=db db_table=”MyUser” db.connect() db.create_tables([MyUser]) The Phpmyadmin web interface now shows myuser table created. Print Page Previous Next Advertisements ”;

Peewee – Retrieving Row Tuples/Dictionaries

Peewee – Retrieving Row Tuples/Dictionaries ”; Previous Next It is possible to iterate over the resultset without creating model instances. This may be achieved by using the following − tuples() method. dicts() method. Example To return data of fields in SELECT query as collection of tuples, use tuples() method. qry=Contacts.select(Contacts.City, fn.Count(Contacts.City).alias(”count”)) .group_by(Contacts.City).tuples() lst=[] for q in qry: lst.append(q) print (lst) Output The output is given below − [ (”Chennai”, 1), (”Delhi”, 2), (”Indore”, 1), (”Mumbai”, 1), (”Nagpur”, 1), (”Nasik”, 3), (”Pune”, 1) ] Example To obtain collection of dictionary objects − qs=Brand.select().join(Item).dicts() lst=[] for q in qs: lst.append(q) print (lst) Output The output is stated below − [ {”id”: 1, ”brandname”: ”Dell”, ”item”: 1}, {”id”: 2, ”brandname”: ”Epson”, ”item”: 2}, {”id”: 3, ”brandname”: ”HP”, ”item”: 1}, {”id”: 4, ”brandname”: ”iBall”, ”item”: 3}, {”id”: 5, ”brandname”: ”Sharp”, ”item”: 2} ] Print Page Previous Next Advertisements ”;

Peewee – Useful Resources

Peewee – Useful Resources ”; Previous Next The following resources contain additional information on Peewee. Please use them to get more in-depth knowledge on this. Python Programming Certification 2024 Most Popular  9 Courses     1 eBooks Tutorialspoint More Detail Artificial Intelligence and Machine Learning Certification 2024 Most Popular  7 Courses     1 eBooks Tutorialspoint More Detail Java Certification 2024 Best Seller  7 Courses     1 eBooks Tutorialspoint More Detail Print Page Previous Next Advertisements ”;

Peewee – Sorting

Peewee – Sorting ”; Previous Next It is possible to select records from a table using order_by clause along with model’s select() method. Additionally, by attaching desc() to the field attribute on which sorting is to be performed, records will be collected in descending order. Example Following code display records from contact table in ascending order of City names. rows=Contacts.select().order_by(Contacts.City) print (“Contact list in order of city”) for row in rows: print (“RollNo:{} Name: {} City:{}”.format(row.RollNo,row.Name, row.City)) Output Here is the sorted list which is arranged according to ascending order of city name. Contact list in order of city RollNo:107 Name: Beena City:Chennai RollNo:102 Name: Amar City:Delhi RollNo:108 Name: John City:Delhi RollNo:103 Name: Raam City:Indore RollNo:101 Name: Anil City:Mumbai RollNo:106 Name: Hema City:Nagpur RollNo:104 Name: Leena City:Nasik RollNo:109 Name: Jaya City:Nasik RollNo:110 Name: Raja City:Nasik RollNo:105 Name: Keshav City:Pune Example Following code displays list in descending order of Name field. rows=Contacts.select().order_by(Contacts.Name.desc()) print (“Contact list in descending order of Name”) for row in rows: print (“RollNo:{} Name: {} City:{}”.format(row.RollNo,row.Name, row.City)) Output The output is as follows − Contact list in descending order of Name RollNo:110 Name: Raja City:Nasik RollNo:103 Name: Raam City:Indore RollNo:104 Name: Leena City:Nasik RollNo:105 Name: Keshav City:Pune RollNo:108 Name: John City:Delhi RollNo:109 Name: Jaya City:Nasik RollNo:106 Name: Hema City:Nagpur RollNo:107 Name: Beena City:Chennai RollNo:101 Name: Anil City:Mumbai RollNo:102 Name: Amar City:Delhi Print Page Previous Next Advertisements ”;

Peewee – Insert a New Record

Peewee – Insert a New Record ”; Previous Next In Peewee, there are more than one commands by which, it is possible to add a new record in the table. We have already used save() method of Model instance. rec1=User(name=”Rajesh”, age=21) rec1.save() The Peewee.Model class also has a create() method that creates a new instance and add its data in the table. User.create(name=”Kiran”, age=19) In addition to this, Model also has insert() as class method that constructs SQL insert query object. The execute() method of Query object performs adding a row in underlying table. q = User.insert(name=”Lata”, age=20) q.execute() The query object is an equivalent INSERT query.q.sql() returns the query string. print (q.sql()) (”INSERT INTO “User” (“name”, “age”) VALUES (?, ?)”, [”Lata”, 20]) Here is the complete code that demonstrates the use of above ways of inserting record. from peewee import * db = SqliteDatabase(”mydatabase.db”) class User (Model): name=TextField() age=IntegerField() class Meta: database=db db_table=”User” db.create_tables([User]) rec1=User(name=”Rajesh”, age=21) rec1.save() a=User(name=”Amar”, age=20) a.save() User.create(name=”Kiran”, age=19) q = User.insert(name=”Lata”, age=20) q.execute() db.close() We can verify the result in SQLiteStudio GUI. Bulk Inserts In order to use multiple rows at once in the table, Peewee provides two methods: bulk_create and insert_many. insert_many() The insert_many() method generates equivalent INSERT query, using list of dictionary objects, each having field value pairs of one object. rows=[{“name”:”Rajesh”, “age”:21}, {“name”:”Amar”, “age”:20}] q=User.insert_many(rows) q.execute() Here too, q.sql() returns the INSERT query string is obtained as below − print (q.sql()) (”INSERT INTO “User” (“name”, “age”) VALUES (?, ?), (?, ?)”, [”Rajesh”, 21, ”Amar”, 20]) bulk_create() This method takes a list argument that contains one or more unsaved instances of the model mapped to a table. a=User(name=”Kiran”, age=19) b=User(name=”Lata”, age=20) User.bulk_create([a,b]) Following code uses both approaches to perform bulk insert operation. from peewee import * db = SqliteDatabase(”mydatabase.db”) class User (Model): name=TextField() age=IntegerField() class Meta: database=db db_table=”User” db.create_tables([User]) rows=[{“name”:”Rajesh”, “age”:21}, {“name”:”Amar”, “age”:20}] q=User.insert_many(rows) q.execute() a=User(name=”Kiran”, age=19) b=User(name=”Lata”, age=20) User.bulk_create([a,b]) db.close() Print Page Previous Next Advertisements ”;

Peewee – Overview

Peewee – Overview ”; Previous Next Peewee is a Python Object Relational Mapping (ORM) library which was developed by a U.S. based software engineer Charles Leifer in October 2010. Its latest version is 3.13.3. Peewee supports SQLite, MySQL, PostgreSQL and Cockroach databases. Object Relational Mapping is a programming technique for converting data between incompatible type systems in object-oriented programming languages. Class as defined in an Object Oriented (OO) programming language such as Python, is considered as non-scalar. It cannot be expressed as primitive types such as integers and strings. On the other hand, databases like Oracle, MySQL, SQLite and others can only store and manipulate scalar values such as integers and strings organised within tables. The programmer must either convert the object values into groups of scalar data types for storage in the database or convert them back upon retrieval, or only use simple scalar values within the program. In an ORM system, each class maps to a table in the underlying database. Instead of writing tedious database interfacing code yourself, an ORM takes care of these issues, while you can focus on programming the logics of the system. Environment setup To install latest version of Peewee as hosted on PyPI (Python Package Index), use pip installer. pip3 install peewee There are no other dependencies for Peewee to work. It works with SQLite without installing any other package as sqlite3 module is bundled with standard library. However, to work with MySQL and PostgreSQL, you may have to install DB-API compatible driver modules pymysql and pyscopg2 respectively. Cockroach database is handled through playhouse extension that is installed by default along with Peewee. Peewee is an open source project hosted on https://github.com/coleifer/peewee repository. Hence, it can be installed from here by using git. git clone https://github.com/coleifer/peewee.git cd peewee python setup.py install Print Page Previous Next Advertisements ”;

Peewee – Query Builder

Peewee – Query Builder ”; Previous Next Peewee also provides a non-ORM API to access the databases. Instead of defining models and fields, we can bind the database tables and columns to Table and Column objects defined in Peewee and execute queries with their help. To begin with, declare a Table object corresponding to the one in our database. You have to specify table name and list of columns. Optionally, a primary key can also be provided. Contacts=Table(”Contacts”, (”id”, ”RollNo”, ”Name”, ”City”)) This table object is bound with the database with bind() method. Contacts=Contacts.bind(db) Example Now, we can set up a SELECT query on this table object with select() method and iterate over the resultset as follows − names=Contacts.select() for name in names: print (name) Output The rows are by default returned as dictionaries. {”id”: 1, ”RollNo”: 101, ”Name”: ”Anil”, ”City”: ”Mumbai”} {”id”: 2, ”RollNo”: 102, ”Name”: ”Amar”, ”City”: ”Delhi”} {”id”: 3, ”RollNo”: 103, ”Name”: ”Raam”, ”City”: ”Indore”} {”id”: 4, ”RollNo”: 104, ”Name”: ”Leena”, ”City”: ”Nasik”} {”id”: 5, ”RollNo”: 105, ”Name”: ”Keshav”, ”City”: ”Pune”} {”id”: 6, ”RollNo”: 106, ”Name”: ”Hema”, ”City”: ”Nagpur”} {”id”: 7, ”RollNo”: 107, ”Name”: ”Beena”, ”City”: ”Chennai”} {”id”: 8, ”RollNo”: 108, ”Name”: ”John”, ”City”: ”Delhi”} {”id”: 9, ”RollNo”: 109, ”Name”: ”Jaya”, ”City”: ”Nasik”} {”id”: 10, ”RollNo”: 110, ”Name”: ”Raja”, ”City”: ”Nasik”} If needed, they can be obtained as tuples, namedtuples or objects. Tuples The program is as follows − Example names=Contacts.select().tuples() for name in names: print (name) Output The output is given below − (1, 101, ”Anil”, ”Mumbai”) (2, 102, ”Amar”, ”Delhi”) (3, 103, ”Raam”, ”Indore”) (4, 104, ”Leena”, ”Nasik”) (5, 105, ”Keshav”, ”Pune”) (6, 106, ”Hema”, ”Nagpur”) (7, 107, ”Beena”, ”Chennai”) (8, 108, ”John”, ”Delhi”) (9, 109, ”Jaya”, ”Nasik”) (10, 110, ”Raja”, ”Nasik”) Namedtuples The program is stated below − Example names=Contacts.select().namedtuples() for name in names: print (name) Output The output is given below − Row(id=1, RollNo=101, Name=”Anil”, City=”Mumbai”) Row(id=2, RollNo=102, Name=”Amar”, City=”Delhi”) Row(id=3, RollNo=103, Name=”Raam”, City=”Indore”) Row(id=4, RollNo=104, Name=”Leena”, City=”Nasik”) Row(id=5, RollNo=105, Name=”Keshav”, City=”Pune”) Row(id=6, RollNo=106, Name=”Hema”, City=”Nagpur”) Row(id=7, RollNo=107, Name=”Beena”, City=”Chennai”) Row(id=8, RollNo=108, Name=”John”, City=”Delhi”) Row(id=9, RollNo=109, Name=”Jaya”, City=”Nasik”) Row(id=10, RollNo=110, Name=”Raja”, City=”Nasik”) To insert a new record, INSERT query is constructed as follows − id = Contacts.insert(RollNo=111, Name=”Abdul”, City=”Surat”).execute() If a list of records to be added is stored either as a list of dictionaries or as list of tuples, they can be added in bulk. Records=[{‘RollNo’:112, ‘Name’:’Ajay’, ‘City’:’Mysore’}, {‘RollNo’:113, ‘Name’:’Majid’,’City’:’Delhi’}} Or Records=[(112, ‘Ajay’,’Mysore’), (113, ‘Majid’, ‘Delhi’)} The INSERT query is written as follows − Contacts.insert(Records).execute() The Peewee Table object has update() method to implement SQL UPDATE query. To change City for all records from Nasik to Nagar, we use following query. Contacts.update(City=”Nagar”).where((Contacts.City==”Nasik”)).execute() Finally, Table class in Peewee also has delete() method to implement DELETE query in SQL. Contacts.delete().where(Contacts.Name==”Abdul”).execute() Print Page Previous Next Advertisements ”;

Peewee – Atomic Transactions

Peewee – Atomic Transactions ”; Previous Next Peewee’s database class has atomic() method that creates a context manager. It starts a new transaction. Inside the context block, it is possible to commit or rollback the transaction depending upon whether it has been successfully done or it encountered exception. with db.atomic() as transaction: try: User.create(name=”Amar”, age=20) transaction.commit() except DatabaseError: transaction.rollback() The atomic() can also be used as decorator. @db.atomic() def create_user(nm,n): return User.create(name=nm, age=n) create_user(”Amar”, 20) More than one atomic transaction blocks can also be nested. with db.atomic() as txn1: User.create(”name”=”Amar”, age=20) with db.atomic() as txn2: User.get(name=”Amar”) Print Page Previous Next Advertisements ”;

Peewee – SQL Functions

Peewee – SQL Functions ”; Previous Next American National Standards Institute (ANSI) Structured Query Language (SQL) standard defines many SQL functions. Aggregate functions like the following are useful in Peewee. AVG() – Returns the average value. COUNT() – Returns the number of rows. FIRST() – Returns the first value. LAST() – Returns the last value. MAX() – Returns the largest value. MIN() – Returns the smallest value. SUM() – Returns the sum. In order to implement these SQL functions, Peewee has a SQL helper function fn(). In above example, we used it to find count of records for each city. Following example builds a SELECT query that employs SUM() function. Using Bill and Item tables from models defined earlier, we shall display sum of quantity of each item as entered in Bill table. Item table The item table with the data is given below − Id Item Name Price 1 Laptop 25000 2 Printer 12000 3 Router 4000 Bill table The bill table is as follows − Id Item_id Brand_id Quantity 1 1 3 5 2 2 2 2 3 3 4 5 4 2 2 6 5 3 4 3 6 1 3 1 Example We create a join between Bill and Item table, select item name from Item table and sum of quantity from Bill table. from peewee import * db = SqliteDatabase(”mydatabase.db”) class BaseModel(Model): class Meta: database = db class Item(BaseModel): itemname = TextField() price = IntegerField() class Brand(BaseModel): brandname = TextField() item = ForeignKeyField(Item, backref=”brands”) class Bill(BaseModel): item = ForeignKeyField(Item, backref=”bills”) brand = ForeignKeyField(Brand, backref=”bills”) qty = DecimalField() db.create_tables([Item, Brand, Bill]) qs=Bill.select(Item.itemname, fn.SUM(Bill.qty).alias(”Sum”)) .join(Item).group_by(Item.itemname) print (qs) for q in qs: print (“Item: {} sum: {}”.format(q.item.itemname, q.Sum)) db.close() Above script executes the following SELECT query − SELECT “t1″.”itemname”, SUM(“t2″.”qty”) AS “Sum” FROM “bill” AS “t2” INNER JOIN “item” AS “t1” ON (“t2″.”item_id” = “t1″.”id”) GROUP BY “t1″.”itemname” Output Accordingly, the output is as follows − Item: Laptop sum: 6 Item: Printer sum: 8 Item: Router sum: 8 Print Page Previous Next Advertisements ”;

Peewee – Connection Management

Peewee – Connection Management ”; Previous Next Database object is created with autoconnect parameter set as True by default. Instead, to manage database connection programmatically, it is initially set to False. db=SqliteDatabase(“mydatabase”, autoconnect=False) The database class has connect() method that establishes connection with the database present on the server. db.connect() It is always recommended to close the connection at the end of operations performed. db.close() If you try to open an already open connection, Peewee raises OperationError. >>> db.connect() True >>> db.connect() Traceback (most recent call last): File “<stdin>”, line 1, in <module> File “c:peeweelibsite-packagespeewee.py”, line 3031, in connect raise OperationalError(”Connection already opened.”) peewee.OperationalError: Connection already opened. To avoid this error, use reuse_if_open=True as argument to connect() method. >>> db.connect(reuse_if_open=True) False Calling close() on already closed connection won’t result error. You can however, check if the connection is already closed with is_closed() method. >>> if db.is_closed()==True: db.connect() True >>> Instead of explicitly calling db.close() in the end, it is also possible to use database object as context_manager. from peewee import * db = SqliteDatabase(”mydatabase.db”, autoconnect=False) class User (Model): user_id=TextField(primary_key=True) name=TextField() age=IntegerField() class Meta: database=db db_table=”User” with db: db.connect() db.create_tables([User]) Print Page Previous Next Advertisements ”;