It is now, the end of the second and I feel I have an even better understanding of how flask works along with a working prototype database build in Flask. This data is an inventory system that Matt Jadud (My Professor) started to begin learning Flask. This time, I would be using peewee an open source database framework and that work alongside Flask in order to made access the database easier. Below, I will explain the what I learn and took away from this project as with giving a short tutorial of what I did.
Learn SQL was hard but very useful because now, I understand SQL statement and database tables. Thanks to SQLite.org and codecademy.com for your helpful tools and resources.
peewee is an open source ORM (object-relational mapper) library for python released under the MIT License. peewee is great because rather than going directly into the database itself, you can code python statement that relates back as SQl statement in your database making a database even easier to use. Below is an example of a simply Scheme definition.
from peewee import * db = SqliteDatabase('YOUR DATABASE NAME') class BaseModel(Model): THIS IS DATABASE CLASS THE PEEWEE WILL BE USING class Meta: database = db class User(BaseModel): INORDER FOR PEEWEE TO SEE TABLES IN YOUR DATABASE THEY MUST BE A CLASS IN THIS FORMAT WITH ALL THE COLOUMS LISTED LIKE BELOW uid = PrimaryKeyField() username = Text() password = Text() class Car(BaseModel): uid = PrimaryKey() owners = ForeignKeyField(Car, related_name='owners' User) status = TextField() timestamp = DateTimeField(default=datetime.datetime.now, index=True) User.create_table() Car.create_table() THIS IS HOW YOU CREATE THE TABLES.
Below is an example of data insertion:
User.create(username="hellrungj", password="Password") OR User = User(username="Admin", password="Root") User.save()
Below is an example of a querying:
User.get() YOU WILL GET A THE FIRST ROW IN THE TABLE User.select() YOU WILL GET EVERY ROW IN THE TABLE User.select().where(User.uid == 2) YOU WILL GET EVERY ROW WITH THE FIELD UID OF 2 IN THE TABLE User.select().where(User.uid == 2).get() YOU WILL GET THE FIRST ROW WITH THE FIRLD UID OF 2 IN THE TABLE
Below is an explain of updating a row:
Selected_User = User.select().where(User.uid == 2).get() FIRST YOU HAVE TO SELECT THE ROW YOU WANT TO CHANGE Selected_User.username = "hellrungj" Selected_User.password = "PassWord1234" Selected_User.save() ONCE YOU HAVE SELECTED THE ROW, YOU WILL USE THE SET THE VAULES OF THE FEILDS THEN USE .SAVE TO SAVE THE CHANGED FEILDS.
I hope, that this has helped and I will be releasing more about peewee in the following week. In the Next post, I will be going into more detail about SQL and the Inventory Flask project.