Falsk
flask:
1.配置文件的幾種方式:
??? 1.app.config['DEBUG'] =True
??? 2.app.config.from_pyfile("setting.py")
??? 3.app.config.from_envvar("環境變量名稱") #環境變量值為Python文件名稱,因為內部會調用from_pyfile
??? 4.app.config.from_json("json文件名")#內部會執行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
???????
??? 另外:裝飾器必須緊貼著函數,在路由的裝飾器之下。
3.路由參數:
??? view_func? 視圖函數名稱
??? defaults=None?? 當URL中無參數,函數需要參數時,使用defaule的默認值
??? endpoint=None?? 用于反向生成URL ,url_for('index')
??? strict_slashes=None 對URL最后 / 符號是否嚴格要求
??? redirect_to=None 重定向到指定地址 @app.route('/index/<int:nid>', redirect_to='/home/<nid>') 注意重定向的url也需要參數,但是不需要類型
??? 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.請求和響應:
???? # 請求相關信息
??????? # 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))
?
??????? # 響應相關信息
??????? # return "字符串"
??????? # return render_template('html模板路徑',**{})
??????? # return redirect('/index.html')
??????? # return jsonify(name='alex',age='18')? #相當于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的基礎上實現的,并且對cookie進行密鑰簽名要使用session需要設置一個密鑰
??? app.secret_key = 'ASDFACASD241SDD/DDD'
??? session['username'] = 'xxx' 設置session
??? session.pop['username']? 刪除session
??? flask 默認的session 是存在瀏覽器上,并且是加密的,減輕服務器的壓力
???
7.閃現flash:
??? flash是基于session來實現的,使用一次后就被pop刪除
??? app.secret_key = '123154sdfsdc' #創建封裝cookie密碼
??? flash("build ok") #設置flash值
??? v=get_flashed_messages() #獲取flash的值
?
8.請求擴展:
??? @app.before_request?? #請求之前
??? @app.befor_first_request #第一次請求之前
??? @app.after_request #請求之后
??? @app.before_response #響應之前
??? @app.after_response #響應之后
?
9.藍圖:Blueprint
??? 實現多文件目錄結構,每個文件夾可以有自己的視圖,模板,靜態文件,并且可以避免相互導入的問題
??? 每一個文件夾可以設置路由的前綴,實現多app的功能,每個APP里面的請求擴展不會相互間影響。
???
10.信號:
??? Flask的信號基于blinker? pip3 install blinker
??? request_started = _signals.signal('request-started')??????????????? # 請求到來前執行
??? request_finished = _signals.signal('request-finished')????????????? # 請求結束后執行
?
??? before_render_template = _signals.signal('before-render-template')? # 模板渲染前執行
??? template_rendered = _signals.signal('template-rendered')??????????? # 模板渲染后執行
????
??? got_request_exception = _signals.signal('got-request-exception')??? # 請求執行出現異常時執行
????
??? request_tearing_down = _signals.signal('request-tearing-down')????? # 請求執行完畢后自動執行(無論成功與否)
??? appcontext_tearing_down = _signals.signal('appcontext-tearing-down')# 請求上下文執行完畢后自動執行(無論成功與否)
????
??? appcontext_pushed = _signals.signal('appcontext-pushed')??????????? # 請求上下文push時執行
??? appcontext_popped = _signals.signal('appcontext-popped')??????????? # 請求上下文pop時執行
??? message_flashed = _signals.signal('message-flashed')??????????????? # 調用flask在其中添加數據時,自動觸發
???
??? 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)
??? # 自定義信號中注冊函數
??? xxxxx.connect(func)
??? @app.route("/x")
??? def index():
??????? # 觸發信號
??????? xxxxx.send('123123', k1='v1')
??????? return 'Index'
??? if __name__ == '__main__':
??????? app.run()
???????
??? 自定義URL匹配正則表達式:
??????? from flask import Flask,url_for
??????? app = Flask(__name__)
??????? # 定義轉換的類
?? ?????from werkzeug.routing import BaseConverter
??????? class RegexConverter(BaseConverter):
??????????? """
??????????? 自定義URL匹配正則表達式
??????????? """
??????????? def __init__(self, map, regex):
??????????????? super(RegexConverter, self).__init__(map)
??????????????? self.regex = regex
??????????? def to_python(self, value):
??????????????? """
??????????????? 路由匹配時,匹配成功后傳遞給視圖函數中參數的值
??????????????? :param value:
??????????????? :return:
??????????????? """
??????????????? return int(value)
????????? ??def to_url(self, value):
??????????????? """
??????????????? 使用url_for反向生成URL時,傳遞的參數經過該方法處理,返回的值用于生成URL中的參數
??????????????? :param value:
??????????????? :return:
??????????????? """
??????????????? val = super(RegexConverter, self).to_url(value)
???? ???????????return val
??????? # 添加到converts中
??????? app.url_map.converters['regex'] = RegexConverter
??????? # 進行使用
??????? @app.route('/index/<regex("\d+"):nid>',endpoint='xx')
??????? def index(nid):
??????????? url_for('xx',nid=123)? #反向生成,就會去執行to_url方法
??????????? return "Index"
?
??????? if __name__ == '__main__':
??????????? app.run()
???
??? 上下文:
??????? 分析見PDF
???
??? Session:
??????? flask Session默認的設置是將用戶信息通過app.secret_key = 'xxxx'加密后,變成字符串返回給用戶
??????? 當用戶信息過多時,cookie的長度有限,并且不安全,如果需要將用戶信息保存在數據庫或者緩存中,引入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? # 如果設置為True,則關閉瀏覽器session就失效。
??????? app.config['SESSION_USE_SIGNER'] = False? # 是否對發送到瀏覽器上session的cookie值進行加密
??????? 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()
轉載于:https://www.cnblogs.com/mihon/p/8980980.html
總結
- 上一篇: Full_of_Boys训练3总结
- 下一篇: 两个有序数组合成一个有序数组