Flask-16 Using Flask-sqlalchemy

Source: Internet
Author: User

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)
    1. __TABLENAME__: Table Name
    2. Id&name: Two fields in the data table are integer and character type
    3. 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)
    1. 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
    2. User.query.filter_by (Name=name). First (): Query the data table, name = Enter the user name, and return to the record found
    3. 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
    1. User.query.all (): Find all records in datasheet
    2. User.query.filter (User.name.startswith (' M ')). All (): Find all user names in the data table that start with M
    3. U=user (name= ' John '): Use the User class to generate a character "<user john>"
    4. Db.session.add (U): Add the John user to the data table, "<user john>"
    5. Db.commit (): Modify action to submit data table
    6. Db.session.delete (u): Delete John user in datasheet

Flask-16 Using Flask-sqlalchemy

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.