Peewee - Using MySQL



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.

My Databases

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.

Php My Admin
Advertisements