公司中使用SQL的種方式:html
1. 寫Django:ORM(關係對象映射), python
2. 寫Flask和其餘:有兩種方式:mysql
(1) 原生SQL:使用原生SQL有兩種選擇:redis
A. pymysql (python2 和 python3均支持)sql
B. MySQLDB (僅python2支持)數據庫
(2) SQLAchemy (也是一種ORM框架,與Django的ORM相似)json
ORM的內部又會調用pymysql或者MySQLdb,因此其本質仍是要會pymysql 和 MySQLdbflask
(1)請求剛到來:獲取隨機字符串,檢測字符串是否存在,若存在則去「數據庫」中獲取原來的我的數據;若是不存在,就在內存裏建立一個空容器(對象)供用戶使用,該對象包括兩項內容:隨機字符串,{放置數據的容器}cookie
(2)接下來走視圖函數,或者業務處理(如登陸),應該要讀取session了:操做內存中的對象(隨機字符串,{放置數據的容器})session
(3)操做完畢即響應終止了,該給什麼返回就給了,即響應:對內存中的對象(隨機字符串,{放置數據的容器})進行兩步操做:
1) 將將數據保存到數據庫
2) 把隨機字符串寫在用戶cookie中
# 1. obj = 建立SecureCookieSessionInterface() # 2. obj = open_session(self.request) = SecureCookieSession() # self.session = SecureCookieSession()對象。 # self.session = self.app.open_session(self.request)
對於Flask的 內置session,是將session保存在加密cookie中實現
請求剛到來: # 建立特殊字典,並添加到Local中。 # 調用關係: # self.session_interface.open_session(self, request) # 因爲默認app中的session_interface=SecureCookieSessionInterface() # SecureCookieSessionInterface().open_session(self, request) # 因爲默認app中的session_interface=MySessionInterFace() # MySessionInterFace().open_session(self, request) self.session = self.app.open_session(self.request) 調用: session -> LocalProxy -> 偏函數 -> LocalStack -> Local 請求終止: # 因爲默認app中的session_interface=SecureCookieSessionInterface() # SecureCookieSessionInterface().save_session(self, app, session, response) # 因爲默認app中的session_interface=MySessionInterFace() # MySessionInterFace().save_session(self, app, session, response)
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' 基本使用
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) 自定義Session
#!/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() 第三方session
1. 回顧:
metaclass:說明當前類是由哪一個基類建立的
class MyType(type): def __init__(self,*args,**kwargs): print('init') super(MyType,self).__init__(*args,**kwargs) def __call__(self, *args, **kwargs): print('call本質:調用類的__new__,再調用類的__init__') return super(MyType,self).__call__( *args, **kwargs) # 建立Foo類的時候,調用MyType的__init__ class Foo(metaclass=MyType): print('foo') # 建立Bar類的時候,調用MyType的__init__ class Bar(Foo): print("--") # 調用Bar的時候才執行__call__ obj = Bar()
class MyType(type): def __init__(self, *args, **kwargs): super(MyType, self).__init__(*args, **kwargs) def __call__(cls, *args, **kwargs): print('xxxx') return super(MyType, cls).__call__(*args, **kwargs) # Base = MyType('Base', (object,), {}) # MyType('Base', (object,), {}) 是由MyType建立; 至關於 metaclass=MyType # 1. type能夠建立類metaclass=type;MyType也能夠建立類metaclass=MyType # 2. Base = MyType('Base', (object,), {}) 等價於 # metaclass的第一種寫法 # class Base(metaclass=MyType): # pass # class Foo(Base): # pass # metaclass的第二種寫法 class Foo(MyType('Base', (object,), {})): pass obj = Foo()
class MyType(type): def __init__(self, *args, **kwargs): super(MyType,self).__init__(*args, **kwargs) def __call__(self, *args, **kwargs): return super(MyType,self).__call__(*args, **kwargs) # 函數,函數的返回值 def with_metaclass(base): return MyType('xx',(base,),{}) # MyType('xx',(base,),{}) 也是建立了一個類,只不過被封裝到了函數裏去了 class Foo(with_metaclass(object)): pass
2.若是簡單使用WTForms
(1) 安裝:pip install wtforms
3.WTForms如何實現的?
三.