Flask notes: 5: Database

Source: Internet
Author: User

The project folder needs to be assigned permissions under Linux and Mac, or it cannot be executed
The Flask-sqlalchemy extension is used in flask to manage program data.
Modifying a configuration file myblog/config.py
csrf_enabled=truesecret_key= ' you-will-never-guess ' Import osbasedir = Os.path.abspath (Os.path.dirname (__file__)) Sqlalchemy_database_uri = ' sqlite:///' + os.path.join (basedir, ' app.db ') Sqlalchemy_migrate_repo = Os.path.join ( Basedir, ' db_repository ') sqlalchemy_track_modifications=true#db file created in the same directory as the Create script # Sqlalchemy_database_uri is the Flask-sqlalchemy the required extensions. This is the path to our database file. # Sqlalchemy_migrate_repo is the folder used to store sqlalchemy-migrate database files. #SQLALCHEMY_TRACK_MODIFICATIONS not set to True will cause an error (seemingly no code will work)


Modifying the initialization script app/__init__.py
From flask import flaskfrom flask.ext.sqlalchemy import sqlalchemyapp=flask (__name__) app.config.from_object (' config ' Db=sqlalchemy (APP) from app import views,models# import flask-sqlalchemy# Create a DB object, this is our database # import a new module called Models


write the models module app/models.py
From app import Dbclass User (db. Model):    ID = db. Column (db. Integer, primary_key=true)    nickname = db. Column (db. String (+), Index=true, unique=true)    email = db. Column (db. String (+), Index=true, unique=true)    posts = db.relationship (' Post ', backref= ' author ', lazy= ' dynamic ')    def _ _repr__ (self):        return ' <user%r> '% (Self.nickname) class Post (db. Model):    ID = db. Column (db. Integer, Primary_key = True)    BODY = db. Column (db. String (    timestamp) = db. Column (db. DateTime)    user_id = db. Column (db. Integer, Db. ForeignKey (' user.id '))    def __repr__ (self):        return ' <post%r> '% (self.body)


Table relationships:
#数据模型类要继承db. Modeldb. Column () is the creation of a columndb. Integer is an integral typedb. string is of typePrimary_key = True is the primary keyIndex=true Adding Indexesunique=true full Table unique db.relationship (), the first argument is the class name, and the second backref name seems to be random (this parameter is user_id replaced with Authou when new data is added ), A third fixed lazy= ' dynamic ' db.relationship () define the contact of the primary key and the foreign keydb. ForeignKey () is a foreign keythe __repr__ method tells Python how to print a class object so that we can use it for debugging purposes.
Create a database mybolg/db_cj.py
From app import Dbdb.create_all () #create_all () is to create a database


executing this script will create the database
test new User xz_user.py
From app Import db, Modelsdef add_com (u):    db.session.add (U)    db.session.commit () U = models. User (nickname= ' John ', email= ' [email protected] ') add_com (u) w=models. User (nickname= ' Susan ', email= ' [email protected] ') add_com (w) #session. Add () adding data #session.commit () COMMIT Transaction




Test new article xz_body.py
Import Datetimefrom App Import db, MODELSU = models. User.query.get (1) p = models. Post (body= ' My first post! ', Timestamp=datetime.datetime.utcnow (), Author=u) Db.session.add (P) db.session.commit () # Authou is the user_id in the Post data Class (yes)




Test Query User cx_user.py
From app Import db, modelsusers = models. User.query.all () Print usersfor u in users:    print u.id,u.nicknamee=models. User.query.get (1) Print ep=models. User.query.filter_by (nickname= "John"). First () print P.idprint p.emaild=models. User.query.filter (models. User.email.endswith (' @email. com ')). All () Print D


Results:[<user u ' John ';, <user u ' Susan ';]1 John2 Susan<user u ' john ' >1[email protected][<user u ' John ';, <user u ' Susan ';]#query这个属性是查询, Query.all () is a query for all#query. Get () is the query primary key#filter_by () is a single filter condition, first () is selected#query. filter_by (Filter conditions). First () query the filter criteria#filter () multiple filter conditions
Test Query Article cx_body.py
From app Import db, MODELSU = models. User.query.get (1) Print uposts = U.posts.all () print postse=models. User.query.get (2) print E.posts.all ()


Results:<user u ' john ' >[<post u ' my first post! ' ;][  ]
test emptying the database db_qk.py
From app Import db, modelsusers = models. User.query.all () for u in Users:    db.session.delete (u) posts = models. Post.query.all () for p in posts:    Db.session.delete (P) db.session.commit () #session. Delete ()




Flask notes: 5: Database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.