Installing Flask-sqlalchemy
Pip Install Flask-sqlalchemy
Load SQLAlchemy
Add in hello.py
From Flask.ext.sqlalchemy import SQLAlchemy
Initialize settings
Add in hello.py
Set Database link Address
1 app.config['sqlalchemy_database_uri'mysql+mysqldb:// < database user name >:< password >@< database address >/< database name >charset=utf8'
Create User Class
1 classUser (db. Model):2 __tablename__='username'3ID = db. Column (db. integer,primary_key=True)4Name = db. Column (db. String (+), unique = true,index=True)5 6 def __repr__(self):7 return '<user {0}>'. Format (Self.name)
- __TABLENAME__: Table Name
- Id&name: Two fields in the data table are integer and character type
- def __repr__ (self): corresponds to the Repr (object) function, which returns a printable string that can be used to represent an object
Add a Database action statement under the View user function
1@app. Route ('/user', methods=['GET','POST'])2 defUser ():3Name =None4New =False5form =Nameform ()6 ifform.validate_on_submit ():7Name =Form.name.data8Form.name.data ="'9 ifUser.query.filter_by (Name=name). First () isNone:TenDb.session.add (User (name =name)) One Db.session.commit () ANew =True - returnRender_template ('user.html', form = Form,name = Name,new = new)
- NEW: Whether the user flag bit, the default is Flase, when the user name entered in the database is not found when the flag becomes true, and finally pass the value to user.html
- User.query.filter_by (Name=name). First (): Query the data table, name = Enter the user name, and return to the record found
- Db.session.add (user name = name): Inserts a user record into the datasheet
Add in user.html to determine the condition for a new user
1 {% block page_content%}2 <Divclass= "Container">3 <Divclass= "Row">4 <Divclass= "Col-md-3">5 {{wtf.quick_form (form)}}6 {% If name%}7 {% If new%}8 <H1>Welcome, {{name}}</H1>9 {% Else%}Ten <H1>See you again, {{name}}</H1> One {% endif%} A {% endif%} - </Div> - </Div> the </Div> -{% Endblock%}
{% if new%} {% Else%} {% ENDIF%}: Determines the new value, which is true when the welcom <user> is displayed, and False when see you again,<user>
Database operation statements
- User.query.all (): Find all records in datasheet
- User.query.filter (User.name.startswith (' M ')). All (): Find all user names in the data table that start with M
- U=user (name= ' John '): Use the User class to generate a character "<user john>"
- Db.session.add (U): Add the John user to the data table, "<user john>"
- Db.commit (): Modify action to submit data table
- Db.session.delete (u): Delete John user in datasheet
Flask-16 Using Flask-sqlalchemy