一、flask配置
創(chuàng)新互聯(lián)建站公司2013年成立,先為墨玉等服務(wù)建站,墨玉等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為墨玉企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
flask中的配置文件是一個(gè)flask.config.Config對(duì)象(繼承字典),默認(rèn)配置為:
{ 'DEBUG': get_debug_flag(default=False), 是否開啟Debug模式 'TESTING': False, 是否開啟測(cè)試模式 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 'USE_X_SENDFILE': False, 'LOGGER_NAME': None, 'LOGGER_HANDLER_POLICY': 'always', 'SERVER_NAME': None, 'APPLICATION_ROOT': None, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), 'TRAP_BAD_REQUEST_ERRORS': False, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': True, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, }
方式一:
app.config['DEBUG'] = True PS: 由于Config對(duì)象本質(zhì)上是字典,所以還可以使用app.config.update(...)
方式二:
#通過(guò)py文件配置 app.config.from_pyfile("python文件名稱") 如: settings.py DEBUG = True app.config.from_pyfile("settings.py") #通過(guò)環(huán)境變量配置 app.config.from_envvar("環(huán)境變量名稱") #app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) 環(huán)境變量的值為python文件名稱名稱,內(nèi)部調(diào)用from_pyfile方法 app.config.from_json("json文件名稱") JSON文件名稱,必須是json格式,因?yàn)閮?nèi)部會(huì)執(zhí)行json.loads app.config.from_mapping({'DEBUG': True}) 字典格式 app.config.from_object("python類或類的路徑") app.config.from_object('pro_flask.settings.TestingConfig') settings.py class Config(object): DEBUG = False TESTING = False DATABASE_URI = 'sqlite://:memory:' class ProductionConfig(Config): DATABASE_URI = 'MySQL://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True PS: 從sys.path中已經(jīng)存在路徑開始寫 PS: settings.py文件默認(rèn)路徑要放在程序root_path目錄,如果instance_relative_config為True,則就是instance_path目錄(Flask對(duì)象init方法的參數(shù))
二、路由系統(tǒng)
經(jīng)典寫法:
@app.route('/detail/<int:nid>',methods=['GET'],endpoint='detail')
默認(rèn)轉(zhuǎn)換器:
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
路由系統(tǒng)本質(zhì)
""" 1. decorator = app.route('/',methods=['GET','POST'],endpoint='n1') def route(self, rule, **options): # app對(duì)象 # rule= / # options = {methods=['GET','POST'],endpoint='n1'} def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator 2. @decorator decorator(index) """ #同理 def login(): return '登錄' app.add_url_rule('/login', 'n2', login, methods=['GET',"POST"]) #與django路由類似 #django與flask路由:flask路由基于裝飾器,本質(zhì)是基于:add_url_rule #add_url_rule 源碼中,endpoint如果為空,endpoint = _endpoint_from_view_func(view_func),最終取view_func.__name__(函數(shù)名)
def auth(func): def inner(*args, **kwargs): print('before') result = func(*args, **kwargs) print('after') return result return inner class IndexView(views.View): methods = ['GET'] decorators = [auth, ] def dispatch_request(self): print('Index') return 'Index!' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint #或者,通常用此方式 class IndexView(views.MethodView): methods = ['GET'] decorators = [auth, ] def get(self): return 'Index.GET' def post(self): return 'Index.POST' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint
app.add_url_rule參數(shù)
@app.route和app.add_url_rule參數(shù): rule, URL規(guī)則 view_func, 視圖函數(shù)名稱 defaults = None, 默認(rèn)值, 當(dāng)URL中無(wú)參數(shù),函數(shù)需要參數(shù)時(shí),使用defaults = {'k': 'v'} 為函數(shù)提供參數(shù) endpoint = None, 名稱,用于反向生成URL,即: url_for('名稱') methods = None, 允許的請(qǐng)求方式,如:["GET", "POST"] #對(duì)URL最后的 / 符號(hào)是否嚴(yán)格要求 strict_slashes = None ''' @app.route('/index', strict_slashes=False) #訪問(wèn)http://www.xx.com/index/ 或http://www.xx.com/index均可 @app.route('/index', strict_slashes=True) #僅訪問(wèn)http://www.xx.com/index ''' #重定向到指定地址 redirect_to = None, ''' @app.route('/index/<int:nid>', redirect_to='/home/<nid>') ''' #子域名訪問(wèn) subdomain = None, ''' #C:\Windows\System32\drivers\etc\hosts 127.0.0.1 www.liuqingzheng.com 127.0.0.1 admin.liuqingzheng.com 127.0.0.1 buy.liuqingzheng.com from flask import Flask, views, url_for app = Flask(import_name=__name__) app.config['SERVER_NAME'] = 'liuqingzheng.com:5000' @app.route("/", subdomain="admin") def static_index(): """Flask supports static subdomains This is available at static.your-domain.tld""" return "static.your-domain.tld" #可以傳入任意的字符串,如傳入的字符串為aa,顯示為 aa.liuqingzheng.com @app.route("/dynamic", subdomain="<username>") def username_index(username): """Dynamic subdomains are also supported Try going to user1.your-domain.tld/dynamic""" return username + ".your-domain.tld" if __name__ == '__main__': app.run() 訪問(wèn): http://www.liuqingzheng.com:5000/dynamic http://admin.liuqingzheng.com:5000/dynamic http://buy.liuqingzheng.com:5000/dynamic '''
支持正則
#1 寫類,繼承BaseConverter #2 注冊(cè):app.url_map.converters['regex'] = RegexConverter # 3 使用:@app.route('/index/<regex("\d+"):nid>') 正則表達(dá)式會(huì)當(dāng)作第二個(gè)參數(shù)傳遞到類中 from flask import Flask, views, url_for from werkzeug.routing import BaseConverter app = Flask(import_name=__name__) 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ù)中參數(shù)的值 """ return int(value) def to_url(self, value): """ 使用url_for反向生成URL時(shí),傳遞的參數(shù)經(jīng)過(guò)該方法處理,返回的值用于生成URL中的參數(shù) """ val = super(RegexConverter, self).to_url(value) return val # 添加到flask中 app.url_map.converters['regex'] = RegexConverter @app.route('/index/<regex("\d+"):nid>') def index(nid): print(url_for('index', nid='888')) return 'Index' if __name__ == '__main__': app.run()
三、模板
比django中多可以加括號(hào),執(zhí)行函數(shù),傳參數(shù)
-支持函數(shù)加括號(hào)執(zhí)行,支持傳參
-flask處理了xss***,如果想顯示原生html
-safe:模板中
-Markup:后臺(tái)處理
from flask import Flask,render_template,Markup,jsonify,make_response app = Flask(__name__) def func1(arg): return Markup("<input type='text' value='%s' />" %(arg,)) @app.route('/') def index(): return render_template('index.html',ff = func1) if __name__ == '__main__': app.run()
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ff('六五')}} {{ff('六五')|safe}} </body> </html>
注意:
1.Markup等價(jià)django的mark_safe ,
2.extends,include一模一樣
四、請(qǐng)求響應(yīng)
from flask import Flask from flask import request from flask import render_template from flask import redirect from flask import make_response app = Flask(__name__) @app.route('/login.html', methods=['GET', "POST"]) def login(): # 請(qǐng)求相關(guān)信息 # request.method # request.args # request.form # request.values # 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({'k1':'v1'}) # 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 return "內(nèi)容" if __name__ == '__main__': app.run()
五、session
除請(qǐng)求對(duì)象之外,還有一個(gè) session 對(duì)象。它允許你在不同請(qǐng)求間存儲(chǔ)特定用戶的信息。它是在 Cookies 的基礎(chǔ)上實(shí)現(xiàn)的,并且對(duì) Cookies 進(jìn)行密鑰簽名要使用會(huì)話,你需要設(shè)置一個(gè)密鑰。 (app.session_interface對(duì)象)
設(shè)置:session['username'] = 'xxx' 刪除:session.pop('username', None) del ession['user'] 取值:session['user']
六、閃現(xiàn)
-設(shè)置:flash('aaa') -取值:get_flashed_message() -假設(shè)在a頁(yè)面操作出錯(cuò),跳轉(zhuǎn)到b頁(yè)面,在b頁(yè)面顯示a頁(yè)面的錯(cuò)誤信息 -分類存 flash('你的名字不是lqz是%s',category='aa') -分類取 get_flashed_messages(category_filter=['aa',])
示例:
from flask import Flask,flash,get_flashed_messages,request,redirect app = Flask(__name__) app.secret_key = 'asdfasdf' @app.route('/index') def index(): # 從某個(gè)地方獲取設(shè)置過(guò)的所有值,并清除。 val = request.args.get('v') if val == 'oldboy': return 'Hello World!' flash('超時(shí)錯(cuò)誤',category="x1") return "ssdsdsdfsd" # return redirect('/error') @app.route('/error') def error(): """ 展示錯(cuò)誤信息 :return: """ data = get_flashed_messages(category_filter=['x1']) if data: msg = data[0] else: msg = "..." return "錯(cuò)誤信息:%s" %(msg,) if __name__ == '__main__': app.run()
message_test.py
from flask import Flask, render_template, render_template_string, Markup, request, session, redirect, flash, \ get_flashed_messages app = Flask(__name__) app.secret_key='s' app.config["DEBUG"] = True @app.route('/index') def index(): name = request.args.get('name') if name == 'lqz': return 'ok' else: flash('名字錯(cuò)誤',category='a') flash('ddddadf',category='bb') return '寫入錯(cuò)誤' # return redirect('/order') @app.route('/order') def order(): message = get_flashed_messages(category_filter=['a']) print(message) return 'order---%s' %message[0] if __name__ == '__main__': app.run()
七、請(qǐng)求資源
類比django中間件中的process_request,在請(qǐng)求收到之前綁定一個(gè)函數(shù)做一些事情
from flask import Flask, render_template, render_template_string, Markup, request, session, redirect, flash, \ get_flashed_messages app = Flask(__name__) app.secret_key='s' app.config["DEBUG"] = True @app.route('/index') def index(): print("index") return '寫入錯(cuò)誤' @app.route('/order') def order(): print('order') return 'order' @app.before_request def process_request(): print('before_request') if __name__ == '__main__': app.run() ----------------------------------------- 訪問(wèn): http://127.0.0.1:5000/index 頁(yè)面返回:寫入錯(cuò)誤 pycharm返回: 127.0.0.1 - - [20/Feb/2019 19:22:11] "GET /index HTTP/1.1" 200 - before_request index -------------------------------------------------------------------------- 返回:http://127.0.0.1:5000/order 頁(yè)面返回: order pycharm返回: before_request 127.0.0.1 - - [20/Feb/2019 19:23:50] "GET /order HTTP/1.1" 200 - order
類比django中間件中的process_response,每一個(gè)請(qǐng)求之后綁定一個(gè)函數(shù),如果請(qǐng)求沒有異常
from flask import Flask, render_template, render_template_string, Markup, request, session, redirect, flash, \ get_flashed_messages app = Flask(__name__) app.secret_key='s' app.config["DEBUG"] = True @app.route('/order') def order(): print('order') return 'order' @app.after_request def process_response(response): print(response) print('response') return response if __name__ == '__main__': app.run() ---------------------------------------------------------------- 訪問(wèn):http://127.0.0.1:5000/order 頁(yè)面返回: order pycharm 返回: 127.0.0.1 - - [20/Feb/2019 19:32:01] "GET /order HTTP/1.1" 200 - order <Response 5 bytes [200 OK]> response
第一次請(qǐng)求時(shí),跟瀏覽器無(wú)關(guān)
from flask import Flask, render_template, render_template_string, Markup, request, session, redirect, flash, \ get_flashed_messages app = Flask(__name__) app.secret_key='s' app.config["DEBUG"] = True @app.route('/order') def order(): print('order') return 'order' @app.after_request def process_response(response): print(response) print('response') return response @app.before_first_request def first(): print('第一次訪問(wèn)記錄') if __name__ == '__main__': app.run() ------------------------------------------- 連續(xù)兩次訪問(wèn):http://127.0.0.1:5000/order pycharm: 第一次訪問(wèn)記錄 127.0.0.1 - - [20/Feb/2019 19:40:08] "GET /order HTTP/1.1" 200 - order <Response 5 bytes [200 OK]> response order <Response 5 bytes [200 OK]> response 127.0.0.1 - - [20/Feb/2019 19:40:26] "GET /order HTTP/1.1" 200 -
文章標(biāo)題:二、flask配置與應(yīng)用-flask
文章轉(zhuǎn)載:http://muchs.cn/article22/igesjc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗(yàn)、定制開發(fā)、服務(wù)器托管、商城網(wǎng)站、移動(dòng)網(wǎng)站建設(shè)、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)