日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Falsk

發(fā)布時間:2025/7/14 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Falsk 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

flask:

1.配置文件的幾種方式:

??? 1.app.config['DEBUG'] =True

??? 2.app.config.from_pyfile("setting.py")

??? 3.app.config.from_envvar("環(huán)境變量名稱") #環(huán)境變量值為Python文件名稱,因為內(nèi)部會調(diào)用from_pyfile

??? 4.app.config.from_json("json文件名")#內(nèi)部會執(zhí)行json.loads

??? 5.app.config.from_mapping({"DEBUG":True}) #字典格式

??? 6.app.config.from_object("pro_flask.setting.Config")

??????? setting

??????????? class Config(object):

??????????????? DEBUG = False

2.視圖

??? fbv的兩種方式:

??????? 1.app = Flask(__name__)

??????????? @app.route('/index')

??????????? def index():

??????????????? return "Index"

???????????? if __name__ == '__main__':

??????????????? app.run()

???????? 2.def index():

??????????? return "Index"

?????????? app.add_url_rule("/index","student",index) #student是別名

??? cbv:

??????? class IndexView(view.ModeView):

??????????? method = ['GET']

??????????? decorators = [auth, ]

???????????

??????????? def dispath_request(self):

??????????????? return 'Index'

???????????????

??????????? def get(self,*args,**kwargs):

?????????? ?????url = url_for('index', nid=nid)? #反向生成url

??????????????? return redirect(url)

??????? app.add_url_rule('index',view_func=IndexView.as_view(name='index')) #name=endpoint

???????

??? 另外:裝飾器必須緊貼著函數(shù),在路由的裝飾器之下。

3.路由參數(shù):

??? view_func? 視圖函數(shù)名稱

??? defaults=None?? 當(dāng)URL中無參數(shù),函數(shù)需要參數(shù)時,使用defaule的默認(rèn)值

??? endpoint=None?? 用于反向生成URL ,url_for('index')

??? strict_slashes=None 對URL最后 / 符號是否嚴(yán)格要求

??? redirect_to=None 重定向到指定地址 @app.route('/index/<int:nid>', redirect_to='/home/<nid>') 注意重定向的url也需要參數(shù),但是不需要類型

??? subdomian=None? 子域名訪問 @app.route("/", subdomain="admin")

4.模板:

?? 1.@app.template_global()

??? def sb(a1,a2):

??????? return a1 + a2 + 100

???? #{{sb(1,2)}}

?

?? 2.@app.template_filter()

??? def db(a1, a2, a3):

??????? return a1 + a2 + a3

???? #{{1|db(2,3)}}

???

?? 3.{% macro xxxx(name, type='text', value='') %}

??????? <input type="{{ type }}" name="{{ name }}" value="{{ value }}">

??????? <input type="{{ type }}" name="{{ name }}" value="{{ value }}">

??????? <input type="{{ type }}" name="{{ name }}" value="{{ value }}">

??????? <input type="{{ type }}" name="{{ name }}" value="{{ value }}">

??? {% endmacro %}

?

??? {{ xxxx('n1') }}

???

??? 4.{{xss|safe}} Markup()

???

5.請求和響應(yīng):

???? # 請求相關(guān)信息

??????? # request.method

??????? # request.args??? #=request.GET 字典格式

??????? # request.querystring #=request.GET bytes格式

??????? # request.form??? #=request.POST

??????? # request.values? #=request.body

??????? # request.cookies

??????? # request.headers

??????? # request.path

??????? # request.full_path

??????? # request.script_root

??????? # request.url

??????? # request.base_url

??????? # request.url_root

??????? # request.host_url

??????? # request.host

??????? # request.files

??????? # obj = request.files['the_file_name']??? #文件上傳

??????? # obj.save('/var/www/uploads/' + secure_filename(f.filename))

?

??????? # 響應(yīng)相關(guān)信息

??????? # return "字符串"

??????? # return render_template('html模板路徑',**{})

??????? # return redirect('/index.html')

??????? # return jsonify(name='alex',age='18')? #相當(dāng)于JsonResponse

?

??????? # response = make_response(render_template('index.html'))?? #返回過個值

??????? # response是flask.wrappers.Response類型

??????? # response.delete_cookie('key')

??????? # response.set_cookie('key', 'value')

??????? # response.headers['X-Something'] = 'A value'

??????? # return response

???????

???????

6.Session:

??? 它是在cookie的基礎(chǔ)上實現(xiàn)的,并且對cookie進(jìn)行密鑰簽名要使用session需要設(shè)置一個密鑰

??? app.secret_key = 'ASDFACASD241SDD/DDD'

??? session['username'] = 'xxx' 設(shè)置session

??? session.pop['username']? 刪除session

??? flask 默認(rèn)的session 是存在瀏覽器上,并且是加密的,減輕服務(wù)器的壓力

???

7.閃現(xiàn)flash:

??? flash是基于session來實現(xiàn)的,使用一次后就被pop刪除

??? app.secret_key = '123154sdfsdc' #創(chuàng)建封裝cookie密碼

??? flash("build ok") #設(shè)置flash值

??? v=get_flashed_messages() #獲取flash的值

?

8.請求擴展:

??? @app.before_request?? #請求之前

??? @app.befor_first_request #第一次請求之前

??? @app.after_request #請求之后

??? @app.before_response #響應(yīng)之前

??? @app.after_response #響應(yīng)之后

?

9.藍(lán)圖:Blueprint

??? 實現(xiàn)多文件目錄結(jié)構(gòu),每個文件夾可以有自己的視圖,模板,靜態(tài)文件,并且可以避免相互導(dǎo)入的問題

??? 每一個文件夾可以設(shè)置路由的前綴,實現(xiàn)多app的功能,每個APP里面的請求擴展不會相互間影響。

???

10.信號:

??? Flask的信號基于blinker? pip3 install blinker

??? request_started = _signals.signal('request-started')??????????????? # 請求到來前執(zhí)行

??? request_finished = _signals.signal('request-finished')????????????? # 請求結(jié)束后執(zhí)行

?

??? before_render_template = _signals.signal('before-render-template')? # 模板渲染前執(zhí)行

??? template_rendered = _signals.signal('template-rendered')??????????? # 模板渲染后執(zhí)行

????

??? got_request_exception = _signals.signal('got-request-exception')??? # 請求執(zhí)行出現(xiàn)異常時執(zhí)行

????

??? request_tearing_down = _signals.signal('request-tearing-down')????? # 請求執(zhí)行完畢后自動執(zhí)行(無論成功與否)

??? appcontext_tearing_down = _signals.signal('appcontext-tearing-down')# 請求上下文執(zhí)行完畢后自動執(zhí)行(無論成功與否)

????

??? appcontext_pushed = _signals.signal('appcontext-pushed')??????????? # 請求上下文push時執(zhí)行

??? appcontext_popped = _signals.signal('appcontext-popped')??????????? # 請求上下文pop時執(zhí)行

??? message_flashed = _signals.signal('message-flashed')??????????????? # 調(diào)用flask在其中添加數(shù)據(jù)時,自動觸發(fā)

???

??? eg:

??? rom flask import Flask, current_app, flash, render_template

??? from flask.signals import _signals

??? app = Flask(import_name=__name__)

??? # 自定義信號

??? xxxxx = _signals.signal('xxxxx')

??? def func(sender, *args, **kwargs):

??????? print(sender)

??? # 自定義信號中注冊函數(shù)

??? xxxxx.connect(func)

??? @app.route("/x")

??? def index():

??????? # 觸發(fā)信號

??????? xxxxx.send('123123', k1='v1')

??????? return 'Index'

??? if __name__ == '__main__':

??????? app.run()

???????

??? 自定義URL匹配正則表達(dá)式:

??????? from flask import Flask,url_for

??????? app = Flask(__name__)

??????? # 定義轉(zhuǎn)換的類

?? ?????from werkzeug.routing import BaseConverter

??????? class RegexConverter(BaseConverter):

??????????? """

??????????? 自定義URL匹配正則表達(dá)式

??????????? """

??????????? def __init__(self, map, regex):

??????????????? super(RegexConverter, self).__init__(map)

??????????????? self.regex = regex

??????????? def to_python(self, value):

??????????????? """

??????????????? 路由匹配時,匹配成功后傳遞給視圖函數(shù)中參數(shù)的值

??????????????? :param value:

??????????????? :return:

??????????????? """

??????????????? return int(value)

????????? ??def to_url(self, value):

??????????????? """

??????????????? 使用url_for反向生成URL時,傳遞的參數(shù)經(jīng)過該方法處理,返回的值用于生成URL中的參數(shù)

??????????????? :param value:

??????????????? :return:

??????????????? """

??????????????? val = super(RegexConverter, self).to_url(value)

???? ???????????return val

??????? # 添加到converts中

??????? app.url_map.converters['regex'] = RegexConverter

??????? # 進(jìn)行使用

??????? @app.route('/index/<regex("\d+"):nid>',endpoint='xx')

??????? def index(nid):

??????????? url_for('xx',nid=123)? #反向生成,就會去執(zhí)行to_url方法

??????????? return "Index"

?

??????? if __name__ == '__main__':

??????????? app.run()

???

??? 上下文:

??????? 分析見PDF

???

??? Session:

??????? flask Session默認(rèn)的設(shè)置是將用戶信息通過app.secret_key = 'xxxx'加密后,變成字符串返回給用戶

??????? 當(dāng)用戶信息過多時,cookie的長度有限,并且不安全,如果需要將用戶信息保存在數(shù)據(jù)庫或者緩存中,引入session的插件

??????? flask_session:

??? 保存到redis: pip3 install flask-session

??????? import redis

??????? from flask import Flask, session

??????? from flask_session import Session

???????

??????? app = Flask(__name__)

??????? app.debug = True

??????? app.secret_key = 'xxxx'

???????

??????? app.config['SESSION_TYPE'] = 'redis'? # session類型為redis

??????? app.config['SESSION_PERMANENT'] = False? # 如果設(shè)置為True,則關(guān)閉瀏覽器session就失效。

??????? app.config['SESSION_USE_SIGNER'] = False? # 是否對發(fā)送到瀏覽器上session的cookie值進(jìn)行加密

??????? app.config['SESSION_KEY_PREFIX'] = 'session:'? # 保存到session中的值的前綴

??????? app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port='6379', password='123123')? # 用于連接redis的配置

??????? Session(app)

?

??????? @app.route('/index')

??????? def index():

??????????? session['k1'] = 'v1'

??????????? return 'xx'

?

??????? if __name__ == '__main__':

??????????? app.run()

轉(zhuǎn)載于:https://www.cnblogs.com/mihon/p/8980980.html

總結(jié)

以上是生活随笔為你收集整理的Falsk的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。