Flask是一個基於Python開發而且依賴jinja2模板和Werkzeug WSGI服務的一個微型框架,對於Werkzeug本質是Socket服務端,其用於接收http請求並對請求進行預處理,而後觸發Flask框架,開發人員基於Flask框架提供的功能對請求進行相應的處理,並返回給用戶,若是要返回給用戶複雜的內容時,須要藉助jinja2模板來實現對模板的處理,即:將模板和數據進行渲染,將渲染後的字符串返回給用戶瀏覽器。html
「微」(micro) 並不表示你須要把整個 Web 應用塞進單個 Python 文件(雖然確實能夠 ),也不意味着 Flask 在功能上有所欠缺。微框架中的「微」意味着 Flask 旨在保持核心簡單而易於擴展。Flask 不會替你作出太多決策——好比使用何種數據庫。而那些 Flask 所選擇的——好比使用何種模板引擎——則很容易替換。除此以外的一切都由可由你掌握。如此,Flask 能夠與您珠聯璧合。前端
默認狀況下,Flask 不包含數據庫抽象層、表單驗證,或是其它任何已有多種庫能夠勝任的功能。然而,Flask 支持用擴展來給應用添加這些功能,如同是 Flask 自己實現的同樣。衆多的擴展提供了數據庫集成、表單驗證、上傳處理、各類各樣的開放認證技術等功能。Flask 也許是「微小」的,但它已準備好在需求繁雜的生產環境中投入使用。python
flask的安裝
mac python3.5 -m pip install flask windows cmd 命令行 pip install flask
Flask依賴一個實現了WSGI(Web服務網關接口)協議的模塊:werkzeugmysql
from werkzeug.wrappers import Request, Response @Request.application def hello(request): return Response('Hello World!') if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('localhost', 4000, hello)
框架依賴於這個協議,協議不依賴與框架,也就是說,框架不能本身作請求和轉發,而這個協議能夠本身作個簡單的請求轉發,由於它自己就是作這個正則表達式
1. 基本使用redis
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
經過源碼來解釋一下各個步驟作了些什麼事情sql
from flask import Flask # 實例化Flask對象 app = Flask(__name__) # 生成路由關係,並把關係保存到某個地方,app對象的 url_map字段中 @app.route('/xxxx') # @decorator == decorator(index) == decorator(f) == f == index == app.add_url_rule('/xxx', "n1", index) def index(): return "Index" # 本質就是將rule封裝成對象添加到map中去 # rule = self.url_rule_class(rule, methods=methods, **options) url 函數 將路由關係封裝成一個對象 rule # self.url_map.add(rule) 將路由關係添加到列表裏面 # class Rule(RuleFactory): # url_map = Map([ # Rule('/all/', defaults={'page': 1}, endpoint='all_entries'), # Rule('/all/page/<int:page>', endpoint='all_entries') # ]) url 視圖函數 對應了 # def index(): # return "Index" # app.add_url_rule('/xxx', "n1", index) 第二種方法 n1 反向url name index 函數名 if __name__ == '__main__': # 啓動程序,監聽用戶請求 # 一旦請求到來,執行 app.__call__方法 # 封裝用戶請求 # 進行路由匹配 app.run()
from flask import Flask, session, current_app # current_app 就是app這個對象 # 建立配置 app = Flask(__name__) app.secret_key = 'sdfsdfsdf' # 方式一: # app.config['SESSION_COOKIE_NAME'] = 'session_lvning' # # 方式二: # app.config.from_pyfile('settings.py') # print(app.config['NNN']) # 方式三:變量 import os # os.environ['FLAKS-SETTINGS'] = 'settings.py' # app.config.from_envvar('FLAKS-SETTINGS') # print(app.config['NNN']) # 方式四:類 # app.config.from_object('settings.DevConfig') # print(app.config['NNN']) @app.route('/index', endpoint='xx') def index(): return "xxx" if __name__ == '__main__': app.run()
NNN = 123 # 其餘引入方式 class BaseConfig(object): # 公用 DB = '120.0.1.11' class TestConfig(BaseConfig): # 測試用 DB = '127.0.0.1' class DevConfig(BaseConfig): DB = '192.168.1.1' class ProConfig(BaseConfig): DB = '47.18.1.1'
flask中的配置文件是一個flask.config.Config對象(繼承字典),默認配置爲: { 'DEBUG': get_debug_flag(default=False), 是否開啓Debug模式 'TESTING': False, 是否開啓測試模式 '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對象本質上是字典,因此還可使用app.config.update(...) 方式二: app.config.from_pyfile("python文件名稱") 如: settings.py DEBUG = True app.config.from_pyfile("settings.py") app.config.from_envvar("環境變量名稱") 環境變量的值爲python文件名稱名稱,內部調用from_pyfile方法 app.config.from_json("json文件名稱") JSON文件名稱,必須是json格式,由於內部會執行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中已經存在路徑開始寫 PS: settings.py文件默認路徑要放在程序root_path目錄,若是instance_relative_config爲True,則就是instance_path目錄
3. 路由系統數據庫
經常使用路由系統有以上五種,全部的路由系統都是基於一下對應關係來處理:django
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
def auth(func): def inner(*args, **kwargs): print('before') result = func(*args, **kwargs) print('after') return result return inner @app.route('/index.html',methods=['GET','POST'],endpoint='index') @auth def index(): return 'Index' 或 def index(): return "Index" self.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"]) or app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"]) app.view_functions['index'] = index 或 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.route和app.add_url_rule參數: rule, URL規則 view_func, 視圖函數名稱 defaults=None, 默認值,當URL中無參數,函數須要參數時,使用defaults={'k':'v'}爲函數提供參數 endpoint=None, 名稱,用於反向生成URL,即: url_for('名稱') methods=None, 容許的請求方式,如:["GET","POST"] strict_slashes=None, 對URL最後的 / 符號是否嚴格要求, 如: @app.route('/index',strict_slashes=False), 訪問 http://www.xx.com/index/ 或 http://www.xx.com/index都可 @app.route('/index',strict_slashes=True) 僅訪問 http://www.xx.com/index redirect_to=None, 重定向到指定地址 如: @app.route('/index/<int:nid>', redirect_to='/home/<nid>') 或 def func(adapter, nid): return "/home/888" @app.route('/index/<int:nid>', redirect_to=func) subdomain=None, 子域名訪問 from flask import Flask, views, url_for app = Flask(import_name=__name__) app.config['SERVER_NAME'] = 'wupeiqi.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" @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()
from flask import Flask, render_template, request, redirect, session, url_for app = Flask(__name__) # app.config['SERVER_NAME'] = 'bjg.com:5000' 子域名用 # @app.route('/index/<int:nid>',methods=['GET',"POST"]) # def index(nid): # URL傳參,指定數據類型 # return "xxxx" # @app.route('/index/<int:nid>',methods=['GET',"POST"],defaults={'cid':777},) # # URL傳參,默認值 # def index(nid,cid): # print(nid,cid) # return 'xxxx' # @app.route('/index/<int:nid>',methods=['GET',"POST"],endpoint='fff') # 反向生成URL # def index(nid): # v = url_for('fff',nid=888) # /index/888 # print(v) # return 'xxxx' # /old ---> /new # 重定向 # @app.route('/old',redirect_to='/new') # def old(): # return "Old" # /new # @app.route('/new') # def new(): # return 'New' # admin.bjg.com:5000/index 子域名訪問,須要HOST文件,有該域名和IP的對應關係, # 還須要配置,app.config['SERVER_NAME'] = 'bjg.com:5000',根域名 # @app.route("/index", subdomain="admin") # def admin_index(): # return "admin.bjg.com" # @app.route("/index",subdomain='www') # def index(): # return "www.bjg.com" # 動態 子域名 # @app.route("/index", subdomain='<xxxxx>') # def index(xxxxx): # return "%s.bjg.com" % (xxxxx,) if __name__ == '__main__': app.run()
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['xxx'] = RegexConverter # 進行使用 @app.route('/index/<xxx("\d+"):nid>', endpoint='xx') # 請求來了首先走這裏,而後會走本身定義的類執行to_python方法,轉化格式 def index(nid): url_for('xx', nid=123) return "Index" if __name__ == '__main__': app.run()
強插一個視圖模式json
from flask import Flask, url_for, views app = Flask(__name__) # FBV # @app.route('/index',endpoint='xx') # def index(nid): # url_for('xx',nid=123) # return "Index" # # app.add_url_rule('/index',index) # CBV def auth(func): def inner(*args, **kwargs): result = func(*args, **kwargs) return result return inner class IndexView(views.MethodView): # methods = ['POST'] # 限定類裏面能夠走哪些方法,若是打開,也就說沒有GET請求了 decorators = [auth, ] # 每一個請求來的時候都會先走裏面的AUTH方法 def get(self): v = url_for('index') # 反向生成 print(v) return "GET" def post(self): return "GET" app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name='index' 就是 endpoint if __name__ == '__main__': app.run()
cbv不能用裝飾器內種添加關係,只能用add_url_rule的方式
4. 模版
一、模板的使用
Flask使用的是Jinja2模板,因此其語法和Django無差異
from flask import Flask, render_template, request, redirect, session app = Flask(__name__, template_folder='templates', 模版目錄,默認static_url_path='/xxxxxx') print(app.root_path) # 根目錄 拼接模版,默認 @app.route('/login', methods=['GET', "POST"]) def login(): if request.method == 'GET': return render_template('login.html') else: user = request.form.get('user') pwd = request.form.get('pwd') if user == 'alex' and pwd == '123': session['user_info'] = user return redirect('/index') else: return render_template('login.html', msg='用戶名或密碼錯誤') @app.route('/index', methods=['GET']) def index(): if not session.get('user_info'): return redirect('/login') return "歡迎登陸" if __name__ == '__main__': app.run()
二、自定義模板方法
Flask中自定義模板方法的方式和Bottle類似,建立一個函數並經過參數的形式傳入render_template,如:
from flask import Flask, url_for, request, redirect, render_template, jsonify, make_response, Markup from urllib.parse import urlencode, quote, unquote app = Flask(__name__) def test(a1, a2): # 自定義標籤 return a1 + a2 @app.template_global() # 全局標籤 def sb(a1, a2): return a1 + a2 + 100 @app.template_filter() # 全局過濾器 def db(a1, a2, a3): return a1 + a2 + a3 @app.route('/index', endpoint='xx') def index(): v1 = "字符串" v2 = [11, 22, 33] # 前端循環跟DJANGO同樣 v3 = {'k1': 'v1', 'k2': 'v2'} # 循環須要加入(),相似PYTHON了 v4 = Markup("<input type='text' />") # 安全,前端也可使用SAFE過濾器 return render_template('index.html', v1=v1, v2=v2, v3=v3, v4=v4, test=test) if __name__ == '__main__': # app.__call__ app.run()
//繼承模版 {% extends 'layout.html'%} {%block body %} //字符串 {{v1}} // 列表 <ul> {% for item in v2 %} <li>{{item}}</li> {% endfor %} </ul> {{v2.1}} //字典取值 <ul> {% for k,v in v3.items() %} <li>{{k}} {{v}}</li> {% endfor %} </ul> {{v3.k1}} {{v3.get('k1')}} // 安全,MARKUP {{v4}} <!--{{v4|safe}}--> // 標籤 <h1>{{test(1,19)}}</h1> // 自定義全局標籤 {{sb(1,2)}} // 自定義全局過濾器 {{ 1|db(2,3)}} // 宏概念,建立多個INPUT框,瞭解便可,由於咱們能夠用循環來建立 {% 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') }} {%endblock%}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>模板</h1> {%block body %} {%endblock%} </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% macro input(name, type='text', value='') %} <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> {% endmacro %} {{ input('n1') }} {% include 'tp.html' %} <h1>asdf{{ v.k1}}</h1> </body> </html>
注意:Markup等價django的mark_safe
5. 請求與響應
from flask import Flask, url_for, request, redirect, render_template, jsonify, make_response from urllib.parse import urlencode, quote, unquote app = Flask(__name__) @app.route('/index',methods=['get','post']) def index(): #### 請求 from werkzeug.datastructures import ImmutableMultiDict get_data = request.args # 請求信息 ImmutableMultiDict([('b', '2'), ('a', '1')]) print(request.query_string) # 請求信息 {'a': '1', 'b': '2'} get_dict = get_data.to_dict() # 轉爲字典 {'b': '2', 'a': '1'} get_dict['xx'] = '18' # 添加鍵值對 {'b': '2', 'a': '1', 'xx': '18'} url = urlencode(get_dict) # 成字符串 b=2&a=1&xx=18 val = "%E6%88%91%E6%98%AF%E8%B0%81" # 請求數據是中文的時候,會進行轉碼 print(unquote(val)) # 轉成字符換 我是誰 pu = '我是誰' print(quote(pu)) # %E6%88%91%E6%98%AF%E8%B0%81 ##### 響應 # return "Index" # 字符串 # return redirect() # 重定向 # return render_template() # 模版返回 # return jsonify(name='alex',age='18') # 返回以下 # { # "age": "18", # "name": "alex" # } response = make_response('xxxxx') # 返回XXXXX字符產 response.headers['xxx'] = '123123' # 響應頭裏面有XXX=12121字段 return response # 返回這個RESPONS,封裝了多個信息 if __name__ == '__main__': # app.__call__ app.run()
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(): # 請求相關信息 # 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)) # 響應相關信息 # return "字符串" # return render_template('html模板路徑',**{}) # return redirect('/index.html') # 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 "內容" if __name__ == '__main__': app.run()
6. session
除請求對象以外,還有一個 session 對象。它容許你在不一樣請求間存儲特定用戶的信息。它是在 Cookies 的基礎上實現的,而且對 Cookies 進行密鑰簽名要使用會話,你須要設置一個密鑰。
設置:session['username'] = 'xxx'
from flask import Flask, render_template, request, redirect, session app = Flask(__name__, template_folder='templates', static_url_path='/xxxxxx') app.secret_key = "sdfasdfasdf3fsdf" # 由於用了sessino,就須要給瀏覽器發送個隨機字符串,加鹽的部分 @app.route('/login', methods=['GET', "POST"]) def login(): if request.method == 'GET': return render_template('login.html') else: user = request.form.get('user') pwd = request.form.get('pwd') if user == 'alex' and pwd == '123': session['user_info'] = user # 沒有放在數據庫,是放在瀏覽器裏面了,加鹽以後的隨機字符串 return redirect('/index') else: return render_template('login.html', msg='用戶名或密碼錯誤') @app.route('/index', methods=['GET']) def index(): if not session.get('user_info'): return redirect('/login') return "歡迎登陸" if __name__ == '__main__': app.run()
pip3 install Flask-Session run.py from flask import Flask from flask import session from pro_flask.utils.session import MySessionInterface app = Flask(__name__) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.session_interface = MySessionInterface() @app.route('/login.html', methods=['GET', "POST"]) def login(): print(session) session['user1'] = 'alex' session['user2'] = 'alex' del session['user2'] return "內容" if __name__ == '__main__': app.run() session.py #!/usr/bin/env python # -*- coding:utf-8 -*- import uuid import json from flask.sessions import SessionInterface from flask.sessions import SessionMixin from itsdangerous import Signer, BadSignature, want_bytes class MySession(dict, SessionMixin): def __init__(self, initial=None, sid=None): self.sid = sid self.initial = initial super(MySession, self).__init__(initial or ()) def __setitem__(self, key, value): super(MySession, self).__setitem__(key, value) def __getitem__(self, item): return super(MySession, self).__getitem__(item) def __delitem__(self, key): super(MySession, self).__delitem__(key) class MySessionInterface(SessionInterface): session_class = MySession container = {} def __init__(self): import redis self.redis = redis.Redis() def _generate_sid(self): return str(uuid.uuid4()) def _get_signer(self, app): if not app.secret_key: return None return Signer(app.secret_key, salt='flask-session', key_derivation='hmac') def open_session(self, app, request): """ 程序剛啓動時執行,須要返回一個session對象 """ sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid) signer = self._get_signer(app) try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid) # session保存在redis中 # val = self.redis.get(sid) # session保存在內存中 val = self.container.get(sid) if val is not None: try: data = json.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid) return self.session_class(sid=sid) def save_session(self, app, session, response): """ 程序結束前執行,能夠保存session中全部的值 如: 保存到resit 寫入到用戶cookie """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) # session保存在redis中 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) # session保存在內存中 self.container.setdefault(session.sid, val) session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
#!/usr/bin/env python # -*- coding:utf-8 -*- """ pip3 install redis pip3 install flask-session """ from flask import Flask, session, redirect from flask.ext.session import Session app = Flask(__name__) app.debug = True app.secret_key = 'asdfasdfasd' app.config['SESSION_TYPE'] = 'redis' from redis import Redis app.config['SESSION_REDIS'] = Redis(host='192.168.0.94',port='6379') Session(app) @app.route('/login') def login(): session['username'] = 'alex' return redirect('/index') @app.route('/index') def index(): name = session['username'] return name if __name__ == '__main__': app.run()
from flask import Flask, session, Session from urllib.parse import urlencode, quote, unquote from werkzeug.local import LocalProxy app = Flask(__name__) app.secret_key = 'sdfsdfsdf' # 必須有這個 app.config['SESSION_COOKIE_NAME'] = 'session_lvning' """ '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, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31) 超時時間 """ @app.route('/index', endpoint='xx') def index(): # session本質上操做的是字典,假設session保存在數據庫,這樣就會打開數據庫,而後操做數據庫,很是繁瑣 # 因此,FLASK將SESSION放在了內存裏面,操做最後一個SESSION # session['xxx'] = 123 # session['xx1'] = 123 # session['xx2'] = 123 # session['xx3'] = 123 # del session['xx2'] session['xx3'] = 123 return "xxx" if __name__ == '__main__': # app.__call__ app.run()
from flask import Flask, render_template, request, redirect, session # 都是靠導入拿的request,堆棧實現的,因此是有序的 app = Flask(__name__, template_folder='templates', static_url_path='/xxxxxx') pring(app.static_url_path) # 執行靜態文件的前綴是什麼,跟目錄沒有關係 print(app.root_path) # 根目錄 拼接模版 # static_url_path 靜態文件前綴,影響頁面前綴 app.secret_key = "sdfasdfasdf3fsdf" # 由於用了sessino,就須要給瀏覽器發送個隨機字符串,加鹽的部分 @app.route('/login', methods=['GET', "POST"]) # 須要加入methods支持哪一種寫法,默認只有一個get def login(): if request.method == 'GET': return render_template('login.html') else: user = request.form.get('user') pwd = request.form.get('pwd') if user == 'alex' and pwd == '123': session['user_info'] = user # 沒有放在數據庫,是放在瀏覽器裏面了,加密以後的隨機字符串 return redirect('/index') else: return render_template('login.html', msg='用戶名或密碼錯誤') # return render_template('login.html',**{'msg':'用戶名或密碼錯誤'}) # values是get post的值,form是表單的值,query_string是get的值 @app.route('/index', methods=['GET']) def index(): if not session.get('user_info'): return redirect('/login') return "歡迎登陸" if __name__ == '__main__': app.run()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>登陸</h1> <form method="post"> <input type="text" name="user"> <input type="text" name="pwd"> <input type="submit" />{{msg}} </form> SRC 是經過APP裏面static_url_path指定的前綴 <img src="/xxxxxx/111.jpg" alt=""> </body> </html>
7. 藍圖
藍圖用於爲應用提供目錄劃分:
小型應用程序:示例
大型應用程序:示例
其餘:
8. message,閃現
message是一個基於Session實現的用於保存數據的集合,其特色是:使用一次就刪除。
from flask import Flask, session, Session, flash, get_flashed_messages, redirect, render_template, request # 其目的就是,添加後跳轉到列表,顯示添加成功 app = Flask(__name__) app.secret_key = 'sdfsdfsdf' @app.route('/users') def users(): # 第一種,經過URL傳遞 # msg = request.args.get('msg','') # 第二種,經過SESSION # msg = session.get('msg') # if msg: # del session['msg'] # 第三種,FLASH實現 v = get_flashed_messages() print(v) msg = '' return render_template('users.html', msg=msg) @app.route('/useradd') def user_add(): # 在數據庫中添加一條數據 # 假設添加成功,在跳轉到列表頁面時,顯示添加成功 # 方式一 ,URL傳遞 # return redirect('/users?msg=添加成功') # 方式二:閃現 # session['msg'] = '添加成功' # 方式三,閃現 flash('添加成功') return redirect('/users') if __name__ == '__main__': app.run()
9. 中間鍵
from flask import Flask, flash, redirect, render_template, request app = Flask(__name__) app.secret_key = 'some_secret' @app.route('/') def index1(): return render_template('index.html') @app.route('/set') def index2(): v = request.args.get('p') flash(v) return 'ok' class MiddleWare: def __init__(self,wsgi_app): self.wsgi_app = wsgi_app def __call__(self, *args, **kwargs): return self.wsgi_app(*args, **kwargs) if __name__ == "__main__": app.wsgi_app = MiddleWare(app.wsgi_app) app.run(port=9999)
10. 請求擴展
from flask import Flask, session, Session, flash, get_flashed_messages, redirect, render_template, request app = Flask(__name__) app.secret_key = 'sdfsdfsdf' @app.before_request # @app.before_first_request 表示運行一次,也就是說第一次請求來運行一次,第二次請求就不會走了 def process_request1(): print('process_request1') return '截胡' # 加了RETURN就不會往下面走了,跟DJANGO同樣的爲NONE的時候才往下面的中間鍵走 @app.after_request def process_response1(response): # 必須有參數 print('process_response1') return response # 必須有返回值,返回值就是這個參數 @app.before_request def process_request2(): print('process_request2') @app.after_request def process_response2(response): print('process_response2') return response @app.route('/index') def index(): print('index') return 'Index' @app.route('/order') def order(): print('order') return 'order' @app.route('/test') def test(): print('test') return 'test' if __name__ == '__main__': app.run()
額外補充:虛擬環境
虛擬環境 python3.5 -m pip install virtualenv # 建立虛擬環境 virtualenv env1 # 進入虛擬環境 Scripts/activate # 退出虛擬換金 Scripts/deactivate