Sqlaichemy-based Flask directory

Source: Internet
Author: User

Pre-knowledge

Basic use of flask

Quickly set up the development of the directory, we can use the flask in the development of the project when the directory is directly used, no need to create their own.

Flask-sqlalchemy

Flask-sqlalchemy is the equivalent of a binder, and he binds flask with SQLAlchemy,

Installation
Pip Install flask-SQLAlchemy
Use
    • __init__.py in your project:
# Import and Instantiate SQLAlchemy  from Import  = SQLAlchemy ()
Import Models

Precautions:

    • -Must be before the blueprint is imported
    • -Must import models.py

In the __init__.py

# Initialize Db.init_app (APP)

    • Write configuration in configuration file
      # ##### sqlalchemy configuration file ##### " Mysql+pymysql://root:[email Protected]:3306/s9day122?charset=utf8 "  = ten= 5

      More detailed information on configuration---> bash here

    • Create a class in models.py (corresponding database table) models.py best created in the root directory
 fromSqlalchemy.ext.declarativeImportDeclarative_base fromSQLAlchemyImportColumn fromSQLAlchemyImportInteger,string,text,date,datetime fromSQLAlchemyImportCreate_engine fromChunImportDBclassUsers (db. Model):__tablename__='Users'ID= Column (Integer, primary_key=True) name= Column (String (+), Index=true, nullable=False) depart_id= Column (Integer)
    • When the above content is configured, we can already add table operations to the database (but we don't normally use it, and there are components behind it to help us implement it)
# Generating tables (using the app context)  from Import  =#  app_ctx = app/g#  __enter__, put in    Local by Localstack # call Localstack to get the app in the local, then go to the app to get the configuration
    • Work with the database based on ORM.
 fromFlaskImportBlueprint fromChunImportDB fromChunImportModelsus= Blueprint ('US',__name__) @us. Route ('/index')defindex ():#using SQLAlchemy to insert a single piece of data into a database    #Db.session.add (models. Users (name= ' high-piece set ', depart_id=1))    #Db.session.commit ()    #Db.session.remove ()result =Db.session.query (models. Users). All ()Print(Result) db.session.remove ()

Flask-script

This component can help us add like Django, enter commands for Runserver, or customize commands for ourselves.

Installation
Using configuration

Import the module in the manage.py file and register the manager

 from Import  == Manager (APP)if__name__'__main__' :     # App.run ()    Manager.run ()

When this is done, we can runserver open our Flask program with the command.

manage.py runserver-h 127.0.0.1-p 8001

Custom commands

Location-Pass Parameter

 fromChunImportCreate_app fromFlask_scriptImportManagerapp=Create_app () Manager=Manager (APP) @manager. CommanddefCustom (ARG):"""custom command python manage.py custom 123:p Aram ARG:: return:"""    Print(ARG)if __name__=='__main__':    #App.run ()Manager.run ()

Keyword Pass-through

 fromChunImportCreate_app fromFlask_scriptImportManagerapp=Create_app () Manager=Manager (APP) @manager. Option ('- N','--name', dest='name') @manager. Option ('- u','--url', dest='URL')defcmd (name, URL):"""custom command execution: Python manage.py cmd-n wupeiqi-u http://www.oldboyedu.com:p Aram name::p Aram URL:: retur N:"""    Print(name, URL)if __name__=='__main__':    #App.run ()Manager.run ()

Flask-migrate

Dependent Flask-script

Installation
Use

In the manage.py file:

#-*-coding:utf-8-*- fromBaseflaskImportCreate_app fromBaseflaskImportDB fromFlask_scriptImportManager fromFlask_migrateImportMigrate, Migratecommandapp=Create_app () Manager=Manager (APP) Migrate (app, DB)"""# Database migration named Python manage.py db init #初始化的时候执行一次 python manage.py db migrate #相当于Django的makemigration python ma nage.py DB Upgrade #相当于Django的migrate"""Manager.add_command ('DB', Migratecommand)if __name__=='__main__': Manager.run ()#App.run ()

Click to download the sample

Sqlaichemy-based Flask directory

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.