Python Flask 学习笔记

1. Flask Hello world

from flask import Flask

# app = Flask(__name__) 默认是static
app = Flask(__name__, static_url_path="/s", static_folder="test1")


@app.route('/')
def hello_world():
    return 'Hello World'


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

2. 调用参数信息

  • 方法一,方便继承复用

    app.config.from_object(DefaultConfig)

  • 方法二,独立文件保护敏感数据

    app.config.from_pyfile("setting1.py")

  • 方法三,设置环境变量

    app.config.from_envvar("ENV1")

from flask import Flask


class DefaultConfig(object):
    SECRUITY_KEY = "QASDRFTGYUYTREWQTY"


app = Flask(__name__, static_url_path="/s", static_folder="test1")

# 方法一,方便继承复用
# app.config.from_object(DefaultConfig)
# 方法二,独立文件保护敏感数据
# app.config.from_pyfile("setting1.py")
# 方法三,设置环境变量
app.config.from_envvar("ENV1")

@app.route('/')
def hello_world():
    # 读取配置信息
    return app.config["SECRUITY_KEY"]


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

setting1.py

SECRUITY_KEY = "dfghjhdesdfgbh`12567"

3. app.run()替代

修改默认配置

image-20210708190136670.png

app.url_map

import json

from flask import Flask


def create_flask_app(config):
    app = Flask(__name__, static_url_path="/s", static_folder="test1")
    app.config.from_object(config)
    return app

class DefaultConfig(object):
    SECRUITY_KEY = "QASDRFTGYUYTREWQTY"

class DevelopmentConfig(DefaultConfig):
    DEBUG = True

app = create_flask_app(DevelopmentConfig)

@app.route('/')
def hello_world():
    # 读取配置信息
    return app.config["SECRUITY_KEY"]

@app.route("/url")
def url():
    urls = app.url_map.iter_rules()
    return json.dumps({url.endpoint: url.rule for url in urls})

# print(app.url_map)

for url in app.url_map.iter_rules():
    print(f"name={url.endpoint}, path={url.rule}")
# if __name__ == '__main__':
#     app.run(host="0.0.0.0", port=5000)

4. 蓝图

image-20210708190429374.png
from flask import Flask, Blueprint

app = Flask(__name__, static_url_path="/s", static_folder="test1")

# 创建蓝图对象
user_bp = Blueprint("user", __name__)


@user_bp.route("/profile", methods=["POST"])
def get_profile():
    return "user profile"


# 注册蓝图
# 127.0.0.1:5000/profile
# app.register_blueprint(user_bp)
# 127.0.0.1:5000/user/profile
app.register_blueprint(user_bp, url_prefix="/user")

from goods import goods_bp
app.register_blueprint(goods_bp, url_prefix="/goods")


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

_init_.py

from flask import Blueprint

goods_bp = Blueprint("goods", __name__, )

from . import views

view.py

from . import goods_bp

@goods_bp.route("/good")
def getGoods():
    return "goods"

5. URL路径参数

image-20210708205052019.png
from flask import Flask, request
from werkzeug.routing import BaseConverter

class MobileConverter(BaseConverter):
    regex = r"1[3-9]\d{9}"

app = Flask(__name__)

app.url_map.converters["mobile"] = MobileConverter

# @app.route('/users/')
@app.route('/users/')
def getUserId(usr_id):
    print(type(usr_id))
    return f'usr id: {usr_id}'

@app.route('/phone/')
def getMobile(mon_num):
    print(type(mon_num))
    return f'mobile number: {mon_num}'

# /articles?channerl_id=123
@app.route("/articles")
def getActiclr():
    channel_id = request.args.get("channerl_id")
    return f"channerl id: {channel_id}"

@app.route("/upload", methods=["POST"])
def uploadFile():
    file = request.files["pic"]
    # with open("./demo.png", "wb") as nf:
    #     nf.write(file.read())
    file.save("./demo.png")
    return "ok"

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

6. 模板响应

templates/index.html




    
    Title


hhhhhhhhhhhhhhhhhhhhhhhhh

{{my_str}}
{{my_int}} asxdcfghjkl;

py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    mint = 1234
    mstr = "asdfvgbn"
    data = dict(
        my_int = 1234,
        my_str = "12345tgbfdsa"
    )
    # return render_template("index.html", my_str=mstr, my_int=mint)
    return render_template("index.html", **data)

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

7. 返回json

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def rejson():
    data = dict(
        my_int = 1234,
        my_str = "12345tgbfdsa"
    )
    return jsonify(data)

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

8. 构造响应状态

from flask import Flask, make_response

app = Flask(__name__)

@app.route('/re1')
def re1():
    return "state", 666, {"name": "kdk"}

@app.route('/re2')
def re2():
    resp = make_response("body")
    resp.headers["name"] = "hdk"
    resp.status = "404 good"
    return resp

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

9. cookie 和 session

from flask import Flask, make_response, request, session

class DefaultConfig(object):
    SECRET_KEY = "QASDRFTGYUYTREWQTY"

app = Flask(__name__)
app.config.from_object(DefaultConfig)

@app.route('/cooke')
def setCookie():
    resp = make_response("set cookie hdk")
    resp.set_cookie("name1", "hdk")
    return resp

@app.route('/getcooke')
def getCookie():
    resp = request.cookies.get("name1")
    return resp

@app.route('/deleteCooke')
def deleteCookie():
    resp = make_response("set cookie hdk")
    resp.delete_cookie("name1", "hdk")
    return resp

@app.route('/setSession')
def setSession():
    session["name2"] = "hddk"
    return "seesion ok"

@app.route('/getSession')
def getSession():
    name = session.get("name2")
    return f"seesion: {name}"


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

10. 异常处理

from flask import Flask, request, abort

app = Flask(__name__)

# abort
@app.route("/articles")
def getActiclr():
    channel_id = request.args.get("channerl_id")
    if channel_id is None:
        abort(400)
    return f"channerl id: {channel_id}"

# code error
@app.errorhandler(500)
def internal_sever_error(e):
    return "Sever remove"

# catch error
@app.errorhandler(ZeroDivisionError)
def zero_division(e):
    print(e)
    return "can't 0"

@app.route("/o")
def getResult():
    r = 1/0
    return f"ok{r}"

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

11.请求钩子

启动中间件

from flask import Flask

app = Flask(__name__)

@app.before_first_request
def before_first_request():
    print("before_first_request")

@app.before_request
def before_request():
    print("before_request")

@app.after_request
def after_request(response):
    print("after_request")
    response.headers["Content-Type"] = "application/json"
    return response

@app.teardown_request
def teardown_request(response):
    print("teardown_request")

@app.route("/")
def index():
    print("view")
    return "index"

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

12. 上下文

from flask import Flask, current_app, g

app1 = Flask(__name__)
app2 = Flask(__name__)

#redis-cli
app1.redis_cli = "redis client1"
app2.redis_cli = "redis client2"


@app1.route('/app1')
def fetApp1():
    return f"{current_app.redis_cli}"

@app2.route('/app2')
def fetApp2():
    return f"{current_app.redis_cli}"

def db_query():
    uid = g.user_id
    uname = g.user_name
    return f"db result: {uid}, {uname}"

# g对象
@app1.route('/user')
def getUser():
    g.user_id = 123
    g.user_name = "hdk"
    return db_query()


from application import bp
app1.register_blueprint(bp)


if __name__ == '__main__':
    # only one
    app1.run()
    # app2.run()

application.py

from flask import Blueprint, current_app

bp = Blueprint("blue1", __name__)

@bp.route('/bp1')
def viewFunc():
    print(current_app.redis_cli)
    return "ok"

13. 认证机制

  • 特定强制需求->装饰器
  • 所有试图的需求->钩子
from flask import Flask, g, abort

app = Flask(__name__)

@app.before_request
def auth():
    g.user_id = 123
    # g.user_id = None


def login_required(func):
    def wrapper(*args, **kwargs):
        if g.user_id is None:
            abort(401)
        else:
            return func(*args, **kwargs)
    return wrapper

@app.route("/")
def index():
    print("view")
    return f"user is {g.user_id}"

@app.route("/profile")
@login_required
def getUserProfile():
    return f"user profile {g.user_id}"


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

你可能感兴趣的:(Python Flask 学习笔记)