Flask

Flask

Flask是一個基於Python開發而且依賴jinja2模板和Werkzeug WSGI服務的一個微型框架,對於Werkzeug本質是Socket服務端,其用於接收http請求並對請求進行預處理,而後觸發Flask框架,開發人員基於Flask框架提供的功能對請求進行相應的處理,並返回給用戶,若是要返回給用戶複雜的內容時,須要藉助jinja2模板來實現對模板的處理,即:將模板和數據進行渲染,將渲染後的字符串返回給用戶瀏覽器。html

默認狀況下,Flask 不包含數據庫抽象層、表單驗證,或是其它任何已有多種庫能夠勝任的功能。然而,Flask 支持用擴展來給應用添加這些功能,如同是 Flask 自己實現的同樣。衆多的擴展提供了數據庫集成、表單驗證、上傳處理、各類各樣的開放認證技術等功能。Flask 也許是「微小」的,但它已準備好在需求繁雜的生產環境中投入使用。數據庫

pip3 install flask

django與flask都是基於wsgi,可是django是wsgiref,flask是werkzeugdjango

from werkzeug.wrappers import Request,Response
from werkzeug.serving import run_simple

@Request.application
def hello(request):
    return Response('Hello World!')

if __name__ == '__main__':
    # 請求一旦進來,執行第三個參數   參數()
    run_simple('localhost',4000,hello)

擴展flask

加括號
類加括號,走init 對象,走call 函數

基本使用

from flask import Flask

app = Flask(__name__)  # 一個flask的類對象
@app.route('/index')
def index():
    return 'Hello World'
if __name__ =='__main__':
    app.run()   # ---> run_simple(host,post,app)

問題:run_simple與app.run()之間的聯繫瀏覽器

app.run(),會將咱們建立的app對象當作第一個參數,傳值
.
源碼裏面:
        from werkzeug.serving import run_simple
        try:
            run_simple(host, port, self, **options)
        finally:
            self._got_first_request = False

因此app.run()  本質也是調用了 run_simple, **options就是咱們建立的app對象
app請求進來,既是對象加() 執行call 方法 ---> 入口

flask沒有本身的模板渲染---> jinja2cookie

flask的文件名肯定session

由app = Flask(__name__)進源碼

    def __init__(
        self,
        import_name,
        static_url_path=None,
        static_folder='static',
        static_host=None,
        host_matching=False,
        subdomain_matching=False,
        template_folder='templates',
        instance_path=None,
        instance_relative_config=False,
        root_path=None
    ):

添加請求方式app

@app.route('/login',methods=['GET','POST'])

取數據框架

視圖函數默認沒有參數,flask的一大特色:請求相關數據不是用參數傳遞,

請求進來數據會將放在空調(request),
request.args # 獲取GET傳來的值
request.form # 獲取POST傳過來的值

返回提醒信息加**dom

方式一:return render_template('login.html',msg = '用戶名或密碼錯誤')
方式二:return render_template('login.html',**{'msg':'用戶名或密碼錯誤'})

將信息放入session

session['user_info'] = user
默認放到瀏覽器的cookie

需加個簽名(加密)不加會報錯
app.secret_key = 'zxvbmfas'   # 自定製加鹽

注意:用戶剛進來session裏面沒有值,但會爲其生成一個字典,session---> 字典,
  字典先序列化爲字符串,再加密,再寫到cookie
全部從session取值能夠經過get

app = Flask(__name__)
app.secret_key = 'zxvbmfas'   # 自定製加鹽

用戶登陸及顯示用戶具體信息

from flask import Flask,render_template,request,redirect,session

app = Flask(__name__)
app.secret_key = 'zxvbmfas'   # 自定製加鹽
app.debug = True  # 自動重啓

USER_DICT = {
    '1':{'name':'vzh','age':18},
    '2':{'name':'lishi','age':28},
    '3':{'name':'jassin','age':38},
}


@app.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    if user == 'jassin' and pwd == '123':
        # 用戶信息放入session
        session['user_info'] = user
        return redirect('/index')
    else:
        return render_template('login.html',msg = '用戶名或密碼錯誤')
        # return render_template('login.html',**{'msg':'用戶名或密碼錯誤'})

@app.route('/index')
def index():
    user_info = session.get('user_info')
    if not user_info:
        return redirect('/login')

    # 展現列表信息
    return render_template('index.html',user_dict = USER_DICT)

@app.route('/detail')
def detail():
    user_info = session.get('user_info')
    if not user_info:
        return redirect('/login')
    # 獲取get請求的uid
    uid = request.args.get('uid')
    info = USER_DICT.get(uid)
    print('用戶信息',info)
    # 展現列表信息
    return render_template('detail.html', info=info)

@app.route('/logout')
def logout():
    del session['user_info']
    return redirect('/login')

if __name__ == '__main__':
    app.run()
app.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
    <ul>
        {% for k,v in user_dict.items() %}
            <li>{{v.name}} <a href="/detail?uid={{k}}">查看詳細</a></li>
        {% endfor %}
    </ul>
</body>
</html>
index
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>用戶登陸</title>
</head>
<body>
    <h1>登陸</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="password" name="pwd">
        <input type="submit" value="提交">{{ msg }}

    </form>
</body>
</html>
login
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
    <h1>詳細信息頁面</h1>
    <div>用戶名:{{info.name}}</div>
    <div>年齡:{{info.age}}</div>
</body>
</html>
detail.html
相關文章
相關標籤/搜索