Learn simple tutorial flask project framework

  Prior to look back at recently made two flask Framework project code to write, because he is responsible for the business logic of an API that is not the whole frame from start to finish practice again, take this look back, write a very simple little project and record down, as their understanding of the ideas and combing framework flask notes summarized.

  1. preparation

  Download and install python (my personal habits is python3) and mysql database.

  2. The development of the directory structure

  First, there is no fixed framework flask project directory structure of the organization, so we have to work out their own directory structure of your own style habits. Need to be stored by file type, first simply as the following directories:

  3. coding

  Starting from 3.1 apps \ __ init__.py in, create a flask instance, and its parameters set attributes:

# - * - Coding: utf8 - * - 
from flask Import the Flask
 Import os
 from datetime Import timedelta
 from .app_login.views Import login_blue
 from .app_manager.views Import manager_blue 


DEF create_app (): 
    app = the Flask ( __name__ )   # Create a flask instance 

    app .register_blueprint (login_blue)   # registration blueprint (routing) 
    app.register_blueprint (manager_blue) 

    app.config.update (of SECRET_KEY = os.urandom (24))   # set key
    = timedelta app.permanent_session_lifetime (= 24 minutes * 60 )
     return App   # returns flask example of setting all the parameters

  3.2 Run inlet: run.py, run flask instance.

# - * - Coding: utf8 - * - 
from Apps Import create_app
 from conf Import conf 

App = create_app ()   # get flask example 

IF  __name__ == ' __main__ ' :
     # start the service; debug mode is turned on, the listener IP and port in conf .py provided in 
    app.run (debug = conf.DEBUG, port = conf.PORT, host = conf.HOST)

  3.3 Configuration parameters: conf.py. Set different parameters based on production, test, develop three environments, specific parameter values ​​to fill in their set when you install mysql.

# - * - Coding: utf8 - * - 
Import os 


class Config (Object): 
    DEBUG = True   # the Flask debug mode is turned 
    DB_NAME = ' danni '   # database name 
    DB_HOST = ' 127.0.0.1 '   # database IP 

    DB_PORT = 3306   # database port (mysql default: 3306) 
    DB_UN = ''   # database account name 
    DB_PW = ''   # database password 


class ProductionConfig (Config):
     "", " 
    production 
    " ""
    DEBUG = False  #flask debug mode is turned on 


class TestingConfig (Config):
     "" " 
    test environment 
    " "" 
    DB_HOST = ' 127.0.0.1 '   # database IP address 
    R_HOST = ' 127.0.0.1 '    # Redis IP address 


class DevelopConfig (Config):
     "" " 
    development environment 
    "" " 
    pORT = 8082   # the Flask port; flask default monitor local 127.0.0.1:5000 
    HOST = ' 0.0.0.0 '   # the Flask bind ip; 0.0.0.0 represents listen to all addresses 


# automatically determine the production environment config 
IF os. path.exists('production.conf'):
    conf = ProductionConfig()
    conf_ver = 'conf.ProductionConfig'
    conf_env = u'生产环境'
elif os.path.exists('test.conf'):
    conf = TestingConfig()
    conf_ver = 'conf.TestingConfig'
    conf_env = u'测试环境'
else:
    conf = DevelopConfig()
    conf_ver = 'conf.DevelopConfig'
    conf_env = U ' Development Environment ' 

  Parameter settings 3.4 database connection: libs \ db.py

# - * - Coding: UTF8 - * - 
Import pymysql
 from the conf Import the conf 


# connection database 
db = pymysql.connect (host = conf.DB_HOST, port = conf.DB_PORT, user = conf.DB_UN, passwd = conf.DB_PW, db = conf.DB_NAME) 

# establish cursor 
cursor = db.cursor (pymysql.cursors.DictCursor = cursor)   # returns {} or [{}, {}, ...] 
# cursor = db.cursor () returns # () or ((), (), ...)

  3.5 After these parameters are set into the business logic code: apps \ app_manager; divided into three parts: __ init__.py is responsible for initializing variables, the model.py processing data in a database, the views.py api responsible for different logical interfaces; business scenario : girls a conventional table, at the console to obtain information about all the users in the table.

Girls table information (name field value can not be repeated) danni the database:

 model.py: operation data database

# - * - Coding: UTF8 - * - 
from libs.db Import DB
 Import datetime
 Import pymysql 


# user acquires information corresponding to the user name of the user; if the user is empty, all user information is acquired 
DEF get_users (user): 
    SQL = ' * Status from Girls WHERE SELECT = 1001! ' 
    IF User: 
        SQL + = ' and name =% a ' % User
     # database connection parameters provided libs / db.py 
    Cursor = db.cursor (Cursor = pymysql.cursors.DictCursor )   # returns {} or [{}, {}, ...] 
    the cursor.execute (SQL) 
    Users =cursor.fetchall () 
    cursor.close ()   # remember to turn off 
    return the Users

views.py in obtaining data from the front-end, according to the function call model.py in the query parameters and business logic

# - * - Coding: utf8 - * - 
from the Flask Import the Blueprint, render_template, Request, jsonify
 from .model Import get_users, insert_user 

# declare a blueprint; set up a blueprint name, path, templates and static files and documents stored url prefix 
manager_blue = the Blueprint ( ' Manager ' , the __name__ , template_folder = ' ../../template ' , static_folder = ' ../../static ' , url_prefix = ' / Manager ' ) 


# the url and view function to bind 
# accessories Member information 
@ manager_blue.route ( ' / getUser ', Methods = [ ' POST ' ])   # define url requests and methods: POST 
DEF The get_user (): 
    Data = Request.Form   # acquired data distal 
    User Data = [ ' User ' ] 
    Users = get_users (User)   # call model.py in get_users () 
    return jsonify ({ " code " : 200 is, " MSG " : " Success " , " Data " : Users})

  4. Start the service : namely running run.py:python3 run.py;

  Follow the prompts to add the ip and port define their own route to access the address: http: //139.224.10.202: 8082 / manager / getuser

  Return result:

  5. end

  Here is a complete framework for the process, but there are front-end template rendering, get access, pit encountered sql statement did not mention here, you can refer to the full project code (also very simple, relatively easy to understand).

Guess you like

Origin www.cnblogs.com/hongdanni/p/11922575.html