Code for auxiliary development using SQLAlchemy in flask

Source: Internet
Author: User

Installation Method

1) apt-ge Installation

Copy codeThe Code is as follows: sudo apt-get install Flask-SQLAlchemy

2) download the installation package for Installation

Copy codeThe Code is as follows: # You can directly use it in py after installation.
Import flask
From flask. ext. sqlalchemy import SQLAlchemy

App = flask. Flask (_ name __)
#-SqlAlchemy database address is configured in Settings
# Sqlite ex: "sqlite: // dbname. db"
App. config. from_object ("Settings ")
Db = SQLAlchemy (app)
Db. init_app (app)
#-When create_all () is called, all templates inherited from db. Model will be created.
# Model ex: see Class AdminInfo
Db. create_all ()

Class AdminInfo (db. Model ):
Id = db. Column (db. Integer, primary_key = True)
Name = db. Column (db. String (16 ))
Password = db. Column (db. String (32 ))
Kidname = db. Column (db. String (16 ))
Diy_show = db. Column (db. Text)

Def _ init _ (self, name, password, kidname, diy_show ):
Self. name = name
Self. password = password
Self. kidname = kidname
Self. diy_show = diy_show

Def _ repr _ (self ):
Return "<name: % s pw: % s>" % (self. name, '* len (self. password ))

In this way, you can use SQLAlchemy in the render template.

Copy codeThe Code is as follows: # perform operations on AdminInfo
Ai = AdminInfo ("gaoyiping", "gaoyiping", u "My name is Gao Yiping", u "Hello everyone, my name is Gao Yiping. What is your name? Let's make friends. ")
# In this way, an SQL Data instance has been created.
# Insert a database
Db. session. add (ai)
# Db commit
Db. session. commit ()

# If you want to query
AdminInfo. query. all ()
#>>> [<Name: gaoyiping pw: **********>,]
AdminInfo. query. get (1) # query the first inserted record
#>>> <Name: gaoyiping pw: *********>
AdminInfo. query. filter_by (name = "gaoyiping ")
#>>> <Name: gaoyiping pw: *********>

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.