Flask notes 1

Flask notes

First clear look, you want to run a dynamic web page, we need

  1. A Web server to listen for and respond to the request, if the request is for a static file it directly to their return, if it is dynamic url forwards the request to the Web application.
  2. A Web application processing request to dynamically generate a response

Web servers typically are others which have achieved good, which is defined by the interface with the Web application we've written communication. WSGI is a unified Web server interface standard, if we write Web applications in accordance with WSGI, so it can run on any server complying with the standard, such as Gunicorn . (Compare the Java Servlet, Servlet specification in accordance with written applications are It can be run on any Servlet container, such as Tomcat and the Jetty, equivalent WSGI server Servlet container)

But WSGI still relatively bottom, shining directly write it too much trouble, so there is a Web framework, Python is well-known Flask and Django. The Java Servlet, too, there has been a corresponding Spring MVC framework. But Flask and Django has built-in server for testing, but not Spring MVC, Spring Boot touches can use the embedded tomcat container.

Flask is a micro-framework, "micro" refers to its core is very small, any optional features are not included. But Flask community provides a wealth of expansion plug-in, you can achieve what you want by selecting the function plug-ins required.

I. Introduction

Flask is a micro-framework, "micro" refers to its core is very small, any optional features are not included. But Flask community provides a wealth of expansion plug-in, you can achieve what you want by selecting the function plug-ins required.

Two, demo demo

Preparing the Environment

sudo apt install python-pip
sudo pip3 install flask
mkdir flask
cd flask/

hello-world.py file

#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask
app = Flask("__name__")  #这里以接受包或者模块为参数,一般传递__name__
                         #这里定义了变量app赋值为Flask()

@app.route('/')         #这里相当于定义了一个路由,具体访问一下本地就知道了
def index():            #路由的函数就是紧接着定义的函数
  return "Hello World!" #访问http://127.0.0.1:5000/(默认端口)界面返回Hello World!

@app.route('/say_hello')
def say_hello():
  return "Hello You are so Good!"  #访问http://127.0.0.1:5000/say_hello界面返回Hello You are so Good!

if (__name__=="__main__"):
  app.run()  #端口可以修改app.run(host='0.0.0.0',port=8000)

A very simple flask website has been set up successfully, directly run the python program

┌─[thekingofnight@parrot]─[~/flask]
└──╼ $chmod +x hello-world.py 
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $sudo ./hello-world.py 
 * Serving Flask app "__name__" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Of course, this may be, the effect is the same

┌─[thekingofnight@parrot]─[~/flask]
└──╼ $FLASK_APP=hello-world.py flask run
* Serving Flask app "hello-world"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Third, custom configuration files in several ways Flask

The first:

app.debug=True
app.secret_key='*****' # 随便填

The second:

app.config["DEBUG"]=True

或者

config = {
    "DEBUG":True,
    "SECRET_KEY":'***'
}
app.config.update(config)

Third: specify the configuration file, ps: the configuration file and run the file to be on the same path

app.config.from_pyfile('settings.py')

The fourth: Using the class as a configuration file

Profile foo.py file

class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite://:memory:'


class ProductionConfig(Config):
    DATABASE_URI = 'mysql://user@localhost/foo'


class DevelopmentConfig(Config):
    DEBUG = True


class TestingConfig(Config):
    TESTING = True
# 导入该类
# app.config.from_object('python类或类的路径')
app.config.from_object(foo.DevelopmentConfig)

Fourth, routing

Using the route in several ways

The first:

from flask import Flask,request
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def index():
    print(request)
    if request.method == "POST":
        return "我是首页 POST"
    else:
        return "我是首页 GET"
if __name__ == '__main__':
    app.run()

The second:

from flask import Flask,request
app = Flask(__name__)
def index():
    return "我是首页"
app.add_url_rule('/','index',index,methods=['GET','POST'])
if __name__ == '__main__':
    app.run()

Fifth, reverse analysis

from flask import Flask,redirect,url_for,request

app = Flask(__name__)

@app.route('/',methods=['GET','POST'],endpoint='index_plf') # endpoint 反向路由别名
def index():
    print(request)
    if request.method == "POST":
        return "我是首页 POST"
    else:
        return "我是首页 GET"
    
@app.route('/register',methods=['GET','POST'])
def register():
    print(request)
    if request.method == "POST":
        return "注册界面 POST"
    else:
        return redirect(url_for('index_plf'))       # url_for从定向到指定别名为index_plf的路由视图中

if __name__ == '__main__':
    app.run()

When we use get access 127.0.0.1:5000/register, it will jump directly to the index view function

Six, four swordsman

From orientation: redirect

from flask import Flask,redirect,url_for,request

app = Flask(__name__)

@app.route('/',methods=['GET','POST'],endpoint='index_plf') # endpoint 反向路由别名
def index():
    print(request)
    if request.method == "POST":
        return "我是首页 POST"
    else:
        return "我是首页 GET"
    
@app.route('/register',methods=['GET','POST'])
def register():
    print(request)
    if request.method == "POST":
        return "注册界面 POST"
    else:
        return redirect(url_for('index_plf'))       # url_for从定向到指定别名为index_plf的路由视图中

if __name__ == '__main__':
    app.run()

Return json data: jsonify

from flask import Flask,jsonify
app = Flask(__name__)

@app.route('/plf',methods=['GET','POST'])
def plf():
    print(request)
    if request.method == "POST":
        return jsonify({"status":"OK","msg":"plf界面 POST"})
    else:
        return jsonify({"status":"OK","msg":"plf界面 GET"})
if __name__ == '__main__':
    app.run()

"""
{
  "msg": "plf\u754c\u9762 GET", 
  "status": "OK"
}
"""

Rendering page: render_template

from flask import Flask,render_template,request
app = Flask(__name__)

@app.route('/lt',methods=['GET','POST'])
def lt():
    print(request)
    if request.method == "POST":
        return render_template('lt.html',age=18)
    else:
        return render_template('lt.html',age=18)
if __name__ == '__main__':
    app.run()

ps: Note template rendering, html file should be placed in templates folder. At the same time we must pay attention to the file must run to keep up templates folder in the same directory

Response Object: Response

from flask import Flask,Response
app = Flask(__name__)

@app.route('/plf_test',methods=['GET','POST'])
def plf_test():
    print(request)
    if request.method == "POST":
        return Response("plf_test界面 POST")
    else:
        return Response("plf_test界面 GET")
if __name__ == '__main__':
    app.run()

Guess you like

Origin www.cnblogs.com/plf-Jack/p/11594175.html