Flask01--入門


1. 創建flask框架主程序

名字可以是app.py/run.py/main.py/index.py

from flask import Flask
app = Flask(__name__) 

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

if __name__ == '__main__':
    # 注意: flask默認端口5000
    app.run()

2. 代碼分析

# 導入Flask類
from flask import Flask

"""
import_name      Flask程序所在的包(模塊),傳 __name__ 就可以
                 其可以決定 Flask 在訪問靜態文件時查找的路徑
static_path      靜態文件訪問路徑(不推薦使用,使用 static_url_path 代替)
static_url_path  靜態文件訪問路徑,可以不傳,默認為:/ + static_folder
static_folder    靜態文件存儲的文件夾,可以不傳,默認為 static
template_folder  模板文件存儲的文件夾,可以不傳,默認為 templates
"""
app = Flask(import_name=__name__)


# 編寫路由視圖
# flask的路由是通過給視圖添加裝飾器的方式進行編寫的。當然也可以分離到另一個文件中。
# flask的視圖函數,flask中默認允許通過return返回html格式數據給客戶端。
@app.route(rule='/')
def index():
    return '<mark>Hello Word!</make>'

# 加載項目配置
class Config(object):
    # 開啟調試模式
    DEBUG = True

# flask中支持多種配置方式,通過app.config來進行加載,我們會這里常用的是配置類
app.config.from_object( Config )


# 指定服務器IP和端口
if __name__ == '__main__':
    # 運行flask
    app.run(host="0.0.0.0", port=5000)

3. 案例:登錄,顯示用戶信息

main.py

Copyfrom flask import Flask, render_template, request, redirect, session, url_for

app = Flask(__name__)
app.debug = True  # 調試模式
app.secret_key = 'xxxx-xxxx-xxxx-xxxx'  # 跟djangosetting中的秘鑰一個意思

USERS = {
    1: {'name': '張三', 'age': 18, 'gender': '男', 'text': "道路千萬條"},
    2: {'name': '李四', 'age': 28, 'gender': '男', 'text': "安全第一條"},
    3: {'name': '王五', 'age': 18, 'gender': '女', 'text': "行車不規范"},
}


@app.route('/detail/<int:nid>', methods=['GET'])
def detail(nid):
    user = session.get('user_info')
    if not user:
        return redirect('/login')

    info = USERS.get(nid)
    return render_template('detail.html', info=info)


@app.route('/index', methods=['GET'])
def index():
    # 從session中拿出user_info
    user = session.get('user_info')
    if not user:
        # return redirect('/login')
        url = url_for('l1')  # 反向解析
        print(url)
        return redirect(url)
    return render_template('index.html', user_dict=USERS)


@app.route('/login', methods=['GET', 'POST'], endpoint='l1')  # endpoint路由的別名,用作反向解析
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        # request.query_string
        # post提交過來的數據放在form中
        # get請求提交過來的數據query_string中
        user = request.form.get('user')w
        pwd = request.form.get('pwd')
        if user == 'lqw' and pwd == '123':
            # 往session中放入key和value
            session['user_info'] = user
            return redirect('/index')
        return render_template('login.html', error='用戶名或密碼錯誤')

# 分析源碼以后的路由寫法
def xxx():
    return 'xxx'


app.add_url_rule('/xxx', view_func=xxx)

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

detail.html

Copy<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>詳細信息 {{ info.name }}</h1>
<div>
    {{ info.text }}
</div>
</body>
</html>

index.html

Copy<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用戶列表</h1>
<table>
    {% for k,v in user_dict.items() %}
        <tr>
            <td>{{ k }}</td>
            <td>{{ v.name }}</td>
            <td>{{ v['name'] }}</td>
            <td>{{ v.get('name') }}</td>
            <td><a href="/detail/{{ k }}">查看詳細</a></td>
        </tr>
    {% endfor %}
</table>
</body>
</html>

login.html

Copy<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用戶登錄</h1>
<form method="post">
    <input type="text" name="user">
    <input type="text" name="pwd">
    <input type="submit" value="登錄">{{ error }}
</form>
</body>
</html>

4. 總結

# Flask三板斧:
    return '<mark>字符串</mark>'  # 提示: 支持HTML語法
    return render_template('index.html')
    return redirect('/login')

# 路由寫法(路徑,支持的請求方式,別名)
    # 基本的路由寫法
    @app.route('/login',methods=['GET','POST'],endpoint='l1')
    # 分析源碼以后的路由寫法
    def xxx():
        return 'xxx'
    app.add_url_rule('/xxx', view_func=xxx)

# 模板語言渲染
    同dtl,但是比dtl強大,支持加括號執行,字典支持中括號取值和get取值

# 分組(django中的有名分組)
    @app.route('/detail/<int:nid>',methods=['GET'])
    def detail(nid):

# 反向解析
    url_for('別名')

# 獲取前端傳遞過來的數據
    # get 請求
        request.query_string
    # post請求
        user = request.form.get('user')
        pwd = request.form.get('pwd')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM