Getting Started with the Flask Framework

Flask - Basic Getting Started

Introduction

  • Flask is called a micro-framework, which only provides a robust core, and all other functions are implemented by extending the library; that is to say, it can be tailored according to the needs of the project. He is suitable for introductory learning as well as master research.

  • Composition: WSGI, template engine (Jinja2)

How WEB works

  • B/S and C/S Architecture

  • How B/S Architecture Works

    • Client (browser) <=> WEB server (nginx) <=> WSGI (uWSGI) <=> Python (flask) <=> database (MySQL)

    • Note: The flask framework comes with a test server and does not consider performance deployment.

Configure the virtual environment

  • Install virtualenv:pip3 install virtualenv

    • Create a virtual environment:virtualenv venv

    • Start the virtual environment:source venv/bin/activate

    • Exit the virtual environment:deactivate

  • Install virtualenvwrapper:

    • Install pip:sudo apt-get install python-pip

    • Install virtualenvwrapper:pip install virtualenvwrapper

    • Configuration:

      • Common directories dedicated to storing virtual environments:~/.virtualenvs

      • Add the following at the end of the file :~/.bashrc

      export WORKON_HOME=$HOME/.virtualenvs
      source $HOME/.local/bin/virtualenvwrapper.sh
      alias mkvirtualenv='mkvirtualenv -p /usr/bin/python'
      alias mkvirtualenv3='mkvirtualenv -p /usr/bin/python3'

      Reload: source ~/.bashrc

  • View virtual environment

    • lsvirtualenv or workon

  • Create a virtual environment

    • python2:mkvirtualenv 虚拟环境名

    • python3:mkvirtualenv3 虚拟环境名

  • Use a virtual environment:

    • workon 虚拟环境名

  • Exit the virtual environment

    • deactivate

  • delete virtual environment

    • rmvirtualenv 虚拟环境名

  • install flask

    • Create a virtual environment:mkvirtualenv3 flask

    • Install flask:pip install flask

use test

  • Code: see "manage.py"

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():return '<h1>Hello world!</h1>'if __name__ == '__main__':app.run()



  • start up:python manage.py runserver

  • Test: Browser Input127.0.0.1:5000

  • startup parameters

    parameter illustrate
    debug Whether to enable the debug mode, the default is False, the code modification will be automatically loaded after it is enabled
    threaded Whether to enable multithreading
    port designated port
      Specify the host, set to '0.0.0.0' to access by IP

    app.run(debug=True, threaded=True, port=5050, host='0.0.0.0')

request and response

  • variable or object

    name context illustrate
    current_app program context The currently running application instance
    g program context The global object, which handles the request's temporary data
    request request context The request object, which contains all the HTTP request information of the client
    session request context User session, for saving information that needs to be 'remembered'
  • request hook function

    function illustrate
    before_first_request before the first request
    before_request before each request
    after_request After each request, provided there is no exception
    teardown_request After each request, with or without exception

    The so-called hook function is the backdoor reserved for the user by the framework

view function

  • No parameter routing


    @app.route('/test/')
    def test():return 'for test yyy'
       
  • route with parameters

    see code

  • illustrate

    • After the '/' at the end of the route is added, it can be added or not during the test (in the browser)

    • If parameters are required, the parameters need to be written in <>, and the parameters of the corresponding view function should be consistent with the routing parameters

    • If you need to specify the parameter type, such as: int/float/path, etc., it should be written before the parameter name and separated from the parameter name by ':'

    • If no parameter class is specified, the default is string, and path is actually a string, except that '/' is no longer a delimiter

request

  • All the request information of the client is placed in the request object

  • Commonly used: url, method, args, headers, etc.

response (resposne)

  • Just return a string directly, the default status code is 200, indicating success

  • Returns a tuple, that is, specifying the status code directly after the string

  • You can also create a response object first, and then return the response object

redirect

  • Note: When the URL of the website is changed, it is necessary to support the old address

  • redirect: redirect function

  • url_for: Construct the routing address according to the view function name, the parameter is the view function name

abort

  • abort: Throws an exception to the system, the system will catch and handle it uniformly

  • @app.errorhandler: custom error display

Extension:

  • MVC: for decoupling

    • M: model, model, that is, the data model

    • V: view, view, responsible for display logic

    • C: controller, controller, responsible for business logic processing

  • MTV: The function is the same as MVC

    • M: model, model, that is, the data model

    • T: template: template, responsible for display logic

    • V: view function, view function, responsible for processing business logic

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324709311&siteId=291194637