日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【Python】【Flask】

發布時間:2024/7/5 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python】【Flask】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

【快速開始】

from flask import Flask, url_for, render_template, redirect
app = Flask(__name__)


"""
# kaishi
@app.route('/')
def index():
return 'Index Page'

@app.route('/hello')
def hello():
return 'Hello Flask World!!'

# param
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % (username)

@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % (post_id)

# 重定向
@app.route('/projects/')
def projects():
return 'The projects page'

@app.route('/about')
def about():
return 'The about page'



# eg.. url_for 1
@app.route('/')
def index():
return 'hello'

@app.route('/login')
def login():
return 'login'

@app.route('/user/<username>')
def profile(username):
return 'profile %s' % username


with app.test_request_context():
print (url_for('index'))
print (url_for('login'))
print (url_for('login', ui='/'))
print (url_for('profile', username='Jone'))
'''
/
/login
/login?ui=%2F
/user/Jone
'''


# eg.. url_for 2
@app.route('/')
def index():
return 'hello'

@app.route('/login')
def Login():
return 'login'

@app.route('/user/<username>')
def profile(username):
return 'profile %s' % username


with app.test_request_context():
print (url_for('index'))
print (url_for('login'))
print (url_for('login', ui='/'))
print (url_for('profile', username='Jone'))

'''
werkzeug.routing.BuildError: Could not build url for endpoint 'login'. Did you mean 'Login' instead?
'''


#eg..
@app.route('/user/<username>/<userid>')
def user_index(username, userid):
return render_template('index.html', username=username)


@app.route('/')
def index():
return redirect(url_for('user_index', username='default', userid=99))

'''
網站輸入http://localhost:5000/
自動指向http://localhost:5000/user/default/99
網頁內容是test_one.html內容
<index.html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
LOGIN IN!!
</body>
</html>

【注意】模版的位置放在templates文件夾下,一般是html文件
'''


@app.route('/')
def index():
list1 = list(range(10))
my_list = [{'id': 1, 'value': '我愛工作'},
{'id': 2, 'value': '工作使人快樂'},
{'id': 3, 'value': '沉迷于工作無法自拔'},
{'id': 4, 'value': '日漸消瘦'},
{'id': 5, 'value': '以夢為馬,越騎越瘦'}]
return render_template(
#渲染模版語言
'index.html',
title = 'hello flask world',
list2 = list1,
my_list = my_list
)

#step1 定義過濾器
def do_listreverse(li):
temp_li = list(li)
temp_li.reverse()
return temp_li

#step2 添加自定義過濾器
app.add_template_filter(do_listreverse, 'listreverse')

'''
網站輸入http://localhost:5000/

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{title|reverse|upper}}</h1>
<br>
{{list2 | listreverse}}
<br>
<ul>
{% for item in my_list %}
<li>{{item.id}}---{{item.value}}</li>
{% endfor %}
</ul>

{% for item in my_list %}
{% if loop.index==1 %}
<li style="">{{loop.index}}--{{item.get('value')}}</li>
{% elif loop.index==2 %}
<li style="">{{loop.index}}--{{item.value}}</li>
{% elif loop.index==3 %}
<li style="">{{item.id}}--{{item.value}}</li>
{% else %}
<li style="">{{item.id}}--{{item.value}}</li>
{% endif %}
{% endfor %}
</body>
</html>

【備注】
常見內建過濾器
字符串操作
safe:禁用轉義

<p>{{ '<em>hello</em>' | safe }}</p>

capitalize:把變量值的首字母轉成大寫,其余字母轉小寫

<p>{{ 'hello' | capitalize }}</p>

lower:把值轉成小寫

<p>{{ 'HELLO' | lower }}</p>

upper:把值轉成大寫

<p>{{ 'hello' | upper }}</p>

title:把值中的每個單詞的首字母都轉成大寫

<p>{{ 'hello' | title }}</p>

reverse:字符串反轉

<p>{{ 'olleh' | reverse }}</p>

format:格式化輸出

<p>{{ '%s is %d' | format('name',17) }}</p>

striptags:渲染之前把值中所有的HTML標簽都刪掉

<p>{{ '<em>hello</em>' | striptags }}</p>

truncate: 字符串截斷

<p>{{ 'hello every one' | truncate(9)}}</p>

列表操作
first:取第一個元素

<p>{{ [1,2,3,4,5,6] | first }}</p>

last:取最后一個元素

<p>{{ [1,2,3,4,5,6] | last }}</p>

length:獲取列表長度

<p>{{ [1,2,3,4,5,6] | length }}</p>

sum:列表求和

<p>{{ [1,2,3,4,5,6] | sum }}</p>

sort:列表排序

<p>{{ [6,2,3,1,5,4] | sort }}</p>

語句塊操作
{% filter upper %}
#一大堆文字#
{% endfilter %}
'''


# egg.. 靜態文件
@app.route('/')
def template1():
democss = url_for('static', filename='css/demo.css')
print (democss)
return render_template('index.html', democss=democss)

'''
【/templates/index.html】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--
這是第一種方式
<link href="/static/css/demo.css" rel="stylesheet" type="text/css"/>
這是第二種方式
-->
<link href="{{democss}}" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>Hello Flask World!!</h1>
</body>
</html>

【/static/css/demo.css】
body{
color:red;
}

【執行】
瀏覽器訪問http://localhost:5000

'''




# egg.. GET POST request
from flask import Flask,request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
return '<h1>Home</h1>'

@app.route('/signin', methods=['GET'])
def signin_form():
return '''
<form action="/signin" method="post">
<p><input name="username"></p>
<p><input name="password" type="password"></p>
<p><button type="submit">Sign in</button></p>
</form>
'''

@app.route('/signin', methods=['POST'])
def signin():
#需要從request對象讀取表單內容
if request.form['username']=='admin' and request.form['password']=='password':
return '<h3>Hello , admin!!</h3>'
return '<h3>Bad username or password .</h3>'



'''
wang xue, [14.05.19 11:44]
運行python app.py,Flask自帶的Server在端口5000上監聽:

$ python app.py
* Running on http://127.0.0.1:5000/
打開瀏覽器,輸入首頁地址http://localhost:5000/:

首頁顯示正確!

再在瀏覽器地址欄輸入http://localhost:5000/signin,會顯示登錄表單:

輸入預設的用戶名admin和口令password,登錄成功:

輸入其他錯誤的用戶名和口令,登錄失敗:

'''



# egg.. 廖雪峰模版的例子

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
return render_template('home.html')

@app.route('/signin', methods=['GET'])
def signin_form():
return render_template('form.html')

@app.route('/signin', methods=['POST'])
def signin():
username = request.form['username']
password = request.form['password']
if username=='admin' and password=='password':
return render_template('signin-ok.html', username=username)
return render_template('form.html', message='Bad username or password', username=username)

'''
【/templates/home.html】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1 style="font-style: italic">Home</h1>
</body>
</html>

【/templates/form.html】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Please Sign In</title>
</head>
<body>
{% if message %}
<p style="color:red">{{ message }}</p>
{% endif %}
<form action="/signin" method="post">
<legend>Please sign in:</legend>
<p><input name="username" placeholder="Username" value="{{ username }}"></p>
<p><input name="password" placeholder="Password" type="password"></p>
<p><button type="submit">Sign In</button></p>

</form>
</body>
</html>

【/templates/sign-ok.html】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome, {{ username }}</title>
</head>
<body>
<p>Welcome, {{ username }}</p>

</body>
</html>

'''


# egg .. 上下文
'''
https://www.cnblogs.com/Erick-L/p/6991079.html

Flask Markup 上下文,request
在模板渲染中,使用Markup轉換變量中的特殊字符

from flask import Markup

Markup函數對字符串進行轉移處理再傳遞給render_template()函數

在瀏覽器中顯示標簽代碼

路由地址的反響生成

通過函數名獲得與其綁定的Url地址

需要使用url_for函數進行反向解析

with app.text_request_context()
print(url_for('f_root')) # 輸出:/
app.text_request_context()方法告訴解釋器為在其作用域中的代碼模擬一個HTTP請求上下文,使其好像被一個HTTP請求所調用

使用Context上下文
他是服務器端獲得應用及請求相關信息的對象
1、會話上下文
會話(session)是一種客戶端與服務器端保持狀態的解決方案,會話上下文是用來實現這種解決方案的存儲結構
復制代碼
from flask import Flask,session
from datetime import datetime

app = Flask(__name__)

app.secret_key = 'SET_ME_BEFORE_USE_SESSION'


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

@app.route('/write_session')
def wirteSession():
session['key_time']=datetime.now().strftime('%Y-%m-%d %H:%M:%S')# 將當前時間保存在Session中
return session['key_time'] # 返回當前時間
@app.route('/read_session')
def readSession():
return session.get('key_time')# 獲取上次調用wirteSession時寫入的時間并返回
復制代碼
除了正常的數據保存和讀取,flask.session對象還維護自身的狀態,通過

new 判斷本次請求的Session是否時新建的

modified 判斷本次請求中是否修改過Session鍵值

@app.route('/write_session')
def wirteSession():
session['key_time']=time.time() # 將當前時間保存在Session中
return session.modified # 因為之前進行了Session設置,所以判斷本次請求是否被修改過(modified)返回TRUE
應用全局對象

復制代碼
from flask import Flask,g

class MYDB():
def __init__(self):
print('一個數據庫鏈接已經建立')

def close(self):
print('數據庫已經關閉')

def connect_to_database():
return MYDB()

def get_db():
db = getattr(g,'_database',None)
if db is None:
db = connect_to_database()
g._database = db # 存入Flask.g對象中
return db

@app.teardown_request # 在請求結束時自動被Flask框架調用
def teardown_db(response):
db = getattr(g,'_database',None)# 從Flask.g對象中獲取對象,檢查是否有鏈接數據庫對象,如果有則關閉
if db is not None:
db.close()
復制代碼
可以在請求處理函數的任何地方調用get_db()
復制代碼
class MYDB():
def __init__(self):
print('一個數據庫鏈接已經建立')

def close(self):
print('數據庫已經關閉')

def connect_to_database():
return MYDB()

def get_db():
db = getattr(g,'_database',None)
if db is None:
db = connect_to_database()
g._database = db # 存入Flask.g對象中
return db

@app.teardown_request
def teardown_db(response):
db = getattr(g,'_database',None)# 從Flask.g對象中獲取對象
if db is not None:
db.close()
def login():
db=get_db() # 第一次調用getdb 創建數據庫鏈接
session['has_login']=True
# 使用db檢查數據庫中的用戶名和密碼
def view_list():
if 'has_login' not in session:
login()
db = get_db() # 第二次調用get_db()# 直接復用之前建立的鏈接
# 使用db 從數據庫查詢數據,返回teardown_db()將會被自動調用
復制代碼
請求上下文生命周期

復制代碼
from flask import Flask, g, request

app = Flask(__name__)

@app.before_request
def before_request():
print 'before request started'
print request.url

@app.before_request
def before_request2():
print 'before request started 2'
print request.url
g.name="SampleApp"

@app.after_request
def after_request(response):
print 'after request finished'
print request.url
response.headers['key'] = 'value'
return response

@app.teardown_request
def teardown_request(exception):
print 'teardown request'
print request.url

@app.route('/')
def index():
return 'Hello, %s!' % g.name

if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
復制代碼
訪問”http://localhost:5000/”后,會在控制臺輸出:

復制代碼
before request started
http://localhost:5000/
before request started 2
http://localhost:5000/
after request finished
http://localhost:5000/
teardown request
http://localhost:5000/
復制代碼
request對象只有在請求上下文的生命周期內才可以訪問。離開了請求的生命周期,其上下文環境也就不存在了,自然也無法獲取request對象。而上面介紹的幾個由上下文裝飾器修飾的Hook函數,會掛載在請求生命周期內的不同階段,所以其內部可以訪問request對象。

構建請求上下文環境

我們使用Flask的內部方法”request_context()”來構建一個客戶端請求上下文。

復制代碼
from werkzeug.test import EnvironBuilder

ctx = app.request_context(EnvironBuilder('/','http://localhost/').get_environ())
ctx.push()
try:
print request.url
finally:
ctx.pop()
復制代碼
“request_context()”會創建一個請求上下文”RequestContext”類型的對象,其需接收”werkzeug”中的”environ”對象為參數。”werkzeug”是Flask所依賴的WSGI函數庫

我們可以在客戶端的請求之外訪問request對象,其實此時的request對象即是剛創建的請求上下文中的一個屬性”request == ctx.request”。啟動Flask時,控制臺仍然可以打印出訪問地址”http://localhost/”。上面的代碼可以用with語句來簡化:

from werkzeug.test import EnvironBuilder

with app.request_context(EnvironBuilder('/','http://localhost/').get_environ()):
print request.url
請求上下文的實現方式

對于Flask Web應用來說,每個請求就是一個獨立的線程。請求之間的信息要完全隔離,避免沖突,這就需要使用本地線程環境(ThreadLocal),

”ctx.push()”方法,會將當前請求上下文,壓入”flask._request_ctx_stack”的棧中,同時這個”_request_ctx_stack”棧是個ThreadLocal對象,也就是”flask._request_ctx_stack”看似全局對象,其實每個線程的都不一樣。請求上下文壓入棧后,再次訪問其都會從這個棧的頂端通過”_request_ctx_stack.top”來獲取,所以取到的永遠是只屬于本線程中的對象,這樣不同請求之間的上下文就做到了完全隔離。請求結束后,線程退出,ThreadLocal線程本地變量也隨即銷毀,”ctx.pop()”用來將請求上下文從棧里彈出,避免內存無法回收。

——————————————————————————————————————————————————————————————————————

主要是在服務端獲得從客戶端提交的數據,包括url參數,表單數據,cookies等

復制代碼
from flask import Flask,request,url_for,redirect

app = Flask(__name__)

@app.route('/redirect_url')
def redirect_url():
next = request.args.get('next') or url_for('index')
return redirect(next)

@app.route('/echo_url')
def echo_url():
return request.base_url
復制代碼
自定義上下文變量和函數

自定義變量

from flask import current_app

@app.context_processor
def appinfo():
return dict(appname=current_app.name)
函數返回的是一個字典,里面有一個屬性”appname”,值為當前應用的名稱。我們曾經介紹過,這里的”current_app”對象是一個定義在應用上下文中的代理。函數用”@app.context_processor”裝飾器修飾,它是一個上下文處理器,它的作用是在模板被渲染前運行其所修飾的函數,并將函數返回的字典導入到模板上下文環境中,與模板上下文合并。然后,在模板中”appname”成為了可訪問的上下文對象。我們可以在模板中將其輸出:

<p>Current App is: {{ appname }}</p>
自定義函數

同理我們可以自定義上下文函數,只需將上例中返回字典的屬性指向一個函數即可,下面我們就來定義一個上下文函數來獲取系統當前時間:

復制代碼
import time

@app.context_processor
def get_current_time():
def get_time(timeFormat="%b %d, %Y - %H:%M:%S"):
return time.strftime(timeFormat)
return dict(current_time=get_time)
復制代碼
<p>Current Time is: {{ current_time() }}</p>
<p>Current Day is: {{ current_time("%Y-%m-%d") }}</p>


應用上下文環境

current_app代理

復制代碼
from flask import Flask, current_app

app = Flask('SampleApp')

@app.route('/')
def index():
return 'Hello, %s!' % current_app.name
復制代碼
我們可以通過”current_app.name”來獲取當前應用的名稱,也就是”SampleApp”。”current_app”是一個本地代理,它的類型是”werkzeug.local. LocalProxy”,它所代理的即是我們的app對象,也就是說”current_app == LocalProxy(app)”。使用”current_app”是因為它也是一個ThreadLocal變量,對它的改動不會影響到其他線程。你可以通過”current_app._get_current_object()”方法來獲取app對象。

既然是ThreadLocal對象,那它就只在請求線程內存在,它的生命周期就是在應用上下文里。離開了應用上下文,”current_app”一樣無法使用

構建應用上下文環境

同請求上下文一樣,我們也可以手動構建應用上下文環境:

with app.app_context():
print current_app.name
“app_context()”方法會創建一個”AppContext”類型對象,即應用上下文對象,此后我們就可以在應用上下文中,訪問”current_app”對象了。

應用上下文Hook函數

應用上下文也提供了裝飾器來修飾Hook函數,不過只有一個”@app.teardown_appcontext”。它會在應用上下文生命周期結束前,也就是從”_app_ctx_stack”出棧時被調用。我們可以加入下面的代碼,順便也驗證下,是否應用上下文在每個請求結束時會被銷毀。

@app.teardown_appcontext
def teardown_db(exception):
print 'teardown application'


request的屬性

下面是request可使用的屬性,其中黑體是比較常用的。

form
一個從POST和PUT請求解析的 MultiDict(一鍵多值字典)。

args
MultiDict,要操作 URL (如 ?key=value )中提交的參數可以使用 args 屬性:

searchword = request.args.get('key', '')
values
CombinedMultiDict,內容是form和args。
可以使用values替代form和args。

cookies
顧名思義,請求的cookies,類型是dict。

stream
在可知的mimetype下,如果進來的表單數據無法解碼,會沒有任何改動的保存到這個·stream·以供使用。很多時候,當請求的數據轉換為string時,使用data是最好的方式。這個stream只返回數據一次。

headers
請求頭,字典類型。

data
包含了請求的數據,并轉換為字符串,除非是一個Flask無法處理的mimetype。

files
MultiDict,帶有通過POST或PUT請求上傳的文件。

environ
WSGI隱含的環境配置。

method
請求方法,比如POST、GET。

path

script_root
url
base_url
url_root
如果用戶請求如下URL:
http://www.example.com/myapplication/page.html?x=y
以上的參數內容如下:
名稱 內容
path /page.html
script_root /myapplication
base_url http://www.example.com/myapplication/page.html
url http://www.example.com/myapplication/page.html?x=y
url_root http://www.example.com/myapplication/
is_xhr
如果請求是一個來自JavaScript XMLHttpRequest的觸發,則返回True,這個只工作在支持X-Requested-With頭的庫并且設置了XMLHttpRequest。

blurprint
藍本名字。

endpoint
endpoint匹配請求,這個與view_args相結合,可是用于重構相同或修改URL。當匹配的時候發生異常,會返回None。

get_json(force=False, silent=False, cache=True)

json
如果mimetype是application/json,這個參數將會解析JSON數據,如果不是則返回None。
可以使用這個替代get_json()方法。

max_content_length
只讀,返回MAX_CONTENT_LENGTH的配置鍵。

module
如果請求是發送到一個實際的模塊,則該參數返回當前模塊的名稱。這是棄用的功能,使用blueprints替代。

on_json_loading_failed(e)
routing_exception = None
如果匹配URL失敗,這個異常將會/已經拋出作為請求處理的一部分。這通常用于NotFound異常或類似的情況。

url_rule = None
內部規則匹配請求的URL。這可用于在URL之前/之后檢查方法是否允許(request.url_rule.methods) 等等。
默認情況下,在處理請求函數中寫下
print('request.url_rule.methods', request.url_rule.methods)
會打印:

request.url_rule.methods {‘GET’, ‘OPTIONS’, ‘HEAD’}

view_args = None
一個匹配請求的view參數的字典,當匹配的時候發生異常,會返回None。


'''




# egg. Cookies
from flask import request, make_response

app = Flask(__name__)

@app.route('/')
def index():
resp = make_response(render_template('index.html'))
resp.set_cookie('username', 'wangxue')
return resp

@app.route('/en')
def en():
username = request.cookies.get('username')
return username


'''
【index.html】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Hello Flask !!
</body>
</html>

首先訪問localhost:5000 : 頁面顯示"Hello Flask"
再次訪問localhost:5000/en: 頁面顯示"wangxue"
'''



# egg.. 重定向和錯誤

from flask import Flask, abort, redirect, url_for, render_template

app = Flask(__name__)

@app.route('/')
def index():
return redirect(url_for('login'))

@app.route('/login')
def login():
abort(401)
this_is_never_executed()

def this_is_never_executed():
print ('*********************')


'''
訪問 localhost:5000
頁面顯示:
Unauthorized

The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.

如果再加上下面代碼,則頁面顯示制定html內容
@app.errorhandler(401)
def page_not_auth(error):
return render_template('page_not_auth.html'), 401
'''



# egg.. 響應

一個視圖函數的返回值會被自動轉換為一個響應對象。如果返回值是一個字符串,它被轉換成一個響應主體是該字符串,錯誤代碼為 200 OK ,媒體類型為 text/html 的響應對象。 Flask 把返回值轉換成響應對象的邏輯如下:

如果返回的是一個合法的響應對象,它會被從視圖直接返回。
如果返回的是一個字符串,響應對象會用字符串數據和默認參數創建。
如果返回的是一個元組而且元組中元素能夠提供額外的信息。這樣的元組必須是 (response, status, headers) 形式且至少含有一個元素。 status 值將會覆蓋狀態代碼,headers 可以是一個列表或額外的消息頭值字典。
如果上述條件均不滿足,Flask 會假設返回值是一個合法的 WSGI 應用程序,并轉換為一個請求對象。
如果你想要獲取在視圖中得到的響應對象,你可以用函數 make_response() 。

想象你有這樣一個視圖:

@app.errorhandler(404)
def not_found(error):
return render_template('error.html'), 404
你只需要用 make_response() 封裝返回表達式,獲取結果對象并修改,然后返回它:

@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
return resp








# egg... 會話
除了請求對象,還有第二個稱為 session 對象允許你在不同請求間存儲特定用戶的信息。 這是在 cookies 的基礎上實現的,并且在 cookies 中使用加密的簽名。這意味著用戶可以查看 cookie 的內容, 但是不能修改它,除非它知道簽名的密鑰。

要使用會話,你需要設置一個密鑰。這里介紹會話如何工作:

from flask import Flask, session, redirect, url_for, escape, request

app = Flask(__name__)

@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''

@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))

# set the secret key. keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
這里提到的 escape() 可以在你不使用模板引擎的時候做轉義(如同本例)。

怎樣產生一個好的密鑰
隨機的問題在于很難判斷什么是真隨機。一個密鑰應該足夠隨機。你的操作系統可以基于一個密碼隨機生成器來生成漂亮的隨機值,這個值可以用來做密鑰:

>>> import os
>>> os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
把這個值復制粘貼到你的代碼,你就搞定了密鑰。
使用基于 cookie 的會話需注意: Flask 會將你放進會話對象的值序列化到 cookie。如果你試圖尋找一個跨請求不能存留的值, cookies 確實是啟用的,并且你不會獲得明確的錯誤信息,檢查你頁面請求中 cookie 的大小,并與 web 瀏覽器所支持的大小對比。


"""








if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0')

轉載于:https://www.cnblogs.com/suren2017/p/10874592.html

總結

以上是生活随笔為你收集整理的【Python】【Flask】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。