python Web flask 視圖內(nèi)容和模板實現(xiàn)代碼
這篇文章主要介紹了python Web flask 視圖內(nèi)容和模板實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
基本使用
# 設(shè)置cookie值@ app.route('/set_cookie') def set_cookie(): response = make_response("set_cookie") response.set_cookie("name", "zhangsan") response.set_cookie("age", "13", 10) #10秒有效期 return response # 獲取cookie@ app.route('/get_cookie') def get_cookie(): #獲取cookie, 可以根據(jù)cookie的內(nèi)容來推薦商品信息# name = request.cookies['haha'] name = request.cookies.get('name') age = request.cookies.get('age') return "獲取cookie,name is %s, age is %s" % (name, age)# 設(shè)置SECRET_KEY app.config["SECRET_KEY"] = "fhdk^fk#djefkj&*&*&"# 設(shè)置session@ app.route('/set_session/<path:name>') def set_session(name): session["name"] = name session["age"] = "13" return "set session"# 獲取session內(nèi)容@ app.route('/get_session') def get_session(): name = session.get('name') age = session.get('age') return "name is %s, age is %s" % (name, age)
session的存儲依賴于cookie,在cookie保存的session編號
session編號生成,需要進行加密,所以需要設(shè)置secret_key secret_key的作用參考:
https://segmentfault.com/q/1010000007295395
上下文:保存的一些配置信息,比如程序名、數(shù)據(jù)庫連接、應(yīng)用信息等
相當(dāng)于一個容器,保存了 Flask 程序運行過程中的一些信息。
Flask中有兩種:請求上下文(session,cookie),應(yīng)用上下文(current_app,g)
current_app,g是全局變量:
current_app.test_value='value'
g.name='abc' # g是一個響應(yīng)里的全局變量可跨文件
渲染模板:
from flask import Flask, render_template app = Flask(__name__)# 默認省略了三個參數(shù), static_url_path, static_folder, template_folders def adds(a, b): return a + b@ app.route('/') def hello_world(): #定義數(shù)據(jù), 整數(shù), 字符串, 元祖, 列表, 字典, 函數(shù) num = 10 str = "hello" tuple = (1, 2, 3, 4) list = [5, 6, 7, 8] dict = { "name": "張三", "age": 13 } return render_template('file01.html', my_num = num, my_str = str, my_tuple = tuple, my_list = list, my_dict = dict, adds = adds)《 html》 { {} }, { { dict[‘name'] } }, { { dict.get(‘name') } } 和 { % % }, { { adds(1, 2) } }# 模板全局--直接使用@ app.template_global('adds') def adds(a, b): return a + b
過濾器&自定義過濾器
{{ 字符串 | 字符串過濾器 }} Safe,lower,upper,little,reverse,format {#防止轉(zhuǎn)義#} {{ str1 | safe}} 或 在方法里str2 = Markup("<b>只有學(xué)習(xí)才能讓我快樂</b>") {{ 列表 | 列表過濾器 }} First,last,length,sum,sort
def do_listreverse(li): #通過原列表創(chuàng)建一個新列表 temp_li = list(li) # 將新列表進行返轉(zhuǎn) temp_li.reverse() return temp_li app.add_template_filter(do_listreverse, 'lireverse')# 或1 @ app.template_filter('lireverse')# 或2 def do_listreverse(li): #通過原列表創(chuàng)建一個新列表 temp_li = list(li) # 將新列表進行返轉(zhuǎn) temp_li.reverse() return temp_li
<h2>my_array 原內(nèi)容:{{ my_array }}</h2> <h2> my_array 反轉(zhuǎn):{{ my_array | lireverse }}</h2>
宏、繼承、包含
宏 {% macro input(name,value='',type='text') %} <input type="{{type}}" name="{{name}}" value="{{value}}"> {% endmacro %} {{ input('name',value='zs')}} // 調(diào)用 繼承 父模板base: {% block top %} 頂部菜單 {% endblock top %} 子模板: {% extends 'base.html' %} {% block content %} 需要填充的內(nèi)容 {% endblock content %} 包含 {% include 'hello.html' %} Flask 的模板中特有變量和方法 {{config.DEBUG}} 輸出:True {{request.url}} 輸出:http://127.0.0.1 {{ g.name }} {{url_for('home')}} // url_for 會根據(jù)傳入的路由器函數(shù)名,返回該路由對應(yīng)的URL {{ url_for('post', post_id=1)}} 這個函數(shù)會返回之前在flask中通過flask()傳入的消息的列表,flash函數(shù)的作用很簡單,可以把由Python字符串表示的消息加入一個消息隊列中,再使用get_flashed_message()函數(shù)取出它們并消費掉 {%for message in get_flashed_messages()%} {{message}} {%endfor%} 模板規(guī)則: <form action="{{ url_for('login') }}" method="post"> <link rel="stylesheet" href="{{ url_for('static',filename='css.css') }}" rel="external nofollow" >
web表單
if request.method == 'POST': # post請求的數(shù)據(jù) print(request.form.get('uname')) print(request.form.get('upass')) # 存session return redirect("/") # get請求的數(shù)據(jù) print(request.args.get('uname')) print(request.args.get('upass')) # post請求的數(shù)據(jù) print(request.form.get('uname')) print(request.form.get('upass'))
CSRF
from flask_wtf import CSRFProtect #設(shè)置SECRET_KEY app.config["SECRET_KEY"] = "fjkdjfkdfjdk" #保護應(yīng)用程序 CSRFProtect(app)
{#設(shè)置隱藏的csrf_token,使用了CSRFProtect保護app之后,即可使用csrf_token()方法#} <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
PyCharm無法調(diào)用numpy(報錯ModuleNotFoundError:No?module?named?&a
本文主要介紹了PyCharm無法調(diào)用numpy(報錯ModuleNotFoundError:No?module?named?'numpy'),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02python腳本設(shè)置超時機制系統(tǒng)時間的方法
這篇文章主要介紹了python腳本設(shè)置超時機制系統(tǒng)時間的方法,感興趣的小伙伴們可以參考一下2016-02-02Python爬蟲:將headers請求頭字符串轉(zhuǎn)為字典的方法
今天小編就為大家分享一篇Python爬蟲:將headers請求頭字符串轉(zhuǎn)為字典的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08Python使用numpy模塊實現(xiàn)矩陣和列表的連接操作方法
今天小編就為大家分享一篇Python使用numpy模塊實現(xiàn)矩陣和列表的連接操作方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06python標(biāo)準(zhǔn)庫turtle海龜繪圖實現(xiàn)簡單奧運五環(huán)
這篇文章主要為大家介紹了python使用turtle實現(xiàn)最簡單簡單奧運五環(huán)繪圖,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05如何使Python中的print()語句運行結(jié)果不換行
這篇文章主要介紹了如何使Python中的print()顯示當(dāng)前語句后不換行,print() 是一個常用函數(shù),但是每次,print()語句顯示后都會換行,本問我們就來節(jié)日如何使print()顯示當(dāng)前語句后不換行,需要的朋友可以參考一下2022-03-03django利用request id便于定位及給日志加上request_id
這篇文章主要介紹了django利用request id便于定位及給日志加上request_id的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用django具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧2018-08-08