analitics

Pages

Tuesday, July 30, 2019

Python 3.7.3 : Using the flask - part 004.

The goal of this tutorial is to interact with the database in order to use it with flask_sqlalchemy python module.
The db.Model is used to interact with the database.
A database doesn't need a primary key but if you using the flask-sqlalchemy you need to have it for each one table in order to connect it.
Let's see the database:
C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import db
>>> db.create_all()
>>> db.engine.table_names()
['user']
Let's add some data into database on user table:
C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from server import db
>>> from server import User
>>> first_user = User(username='catafest',email='catafest@yahoo.com')
>>> db.session.add(first_user)
>>> db.session.commit()
>>> test_user = User(username='test',email='test@test.com')
>>> db.session.add(test_user)
>>> db.session.commit()
Update is a simple issue.
Let's update the username test_user from test to user_test:
>>> test_user.username = 'user_test'
>>> db.session.commit()
The delete is simple like the add:
>>> db.session.delete(test_user)
>>> db.session.commit()
Let's use query:
>>> results=User.query.all()
>>> results[0].username
'catafest'
>>> results[0].email
'catafest@yahoo.com'
>>> results
The next step is an important issue because let you to see how result by content and query and filter by first result:
>>> q1 = User.query.filter_by(username='catafest')
>>> q1
...flask_sqlalchemy .basequery= ...
>>> print(q1)
SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email
FROM user
WHERE user.username = ?
>>> q2 = User.query.filter_by(username='catafest').first()
>>> q2
< User 1 >
>>> print(q2)
< User 1 >
>>> print(q1.username)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'BaseQuery' object has no attribute 'username'
>>> print(q2.username)
catafest
>>> print(q2.username,q2.email)
catafest catafest@yahoo.com 
In this case because the first is limited to one result the print of q2 is the correct way.