flask学习笔记2
- 内容回顾
1 你怎么看面相对象?
a 三大特性:封装,继承,多态
封装:1 对处理同一类问题的函数进行封装 (模块封装,类封装)
2 对数据进行封装:多个形参封装到类中;对形参进行加工。
继承:多个类中有相同的代码,减少代码的冗余
多态:多种形态
class C1(object): def send(self): pass class C2(object): def send(self): pass #把C1和C2的两个类的实例当做形参传入 def f1(arg): arg.send() #只要能有send方法执行 就是多态,不管对象是实例化的什么类
b:常用的双下划线的方法
__init__ #类加括号 实例化对象时执行
__call__ #对象加括号时执行 __str__ #把实例变成一个str时候 __dict__ #是用来存储对象属性的一个字典,其键为属性名,值为属性的值 __enter__ #with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单 __exit__ #处理with后的关闭操作,处理异常 __del__ #析构函数 __new__ #__new__方法接受的参数虽然也是和__init__一样,但__init__是在类实例创建之后调用,而 __new__方法正是创建这个类实例的方法 __name__ #类的名字 __setattr__ #obj.name = value __setitem__ #obj['name'] __doc__ #"""this is XXX""" 注释部分
#!/usr/bin/env python class Sample: def __enter__(self): print "In __enter__()" return "Foo" def __exit__(self, type, value, trace): print "In __exit__()" def get_sample(): return Sample() with get_sample() as sample: print "sample:", sample
c:metaclass 类是由type创建的
#创建类的两种方式 class Myobj(object): def __init__(self): pass #创建类的方式2 Myobj2=type('Myobj2',(object,),{}) print(Myobj) print(Myobj2) ##################### class MyType(type): def __init__(self,*args,**kwargs): print('this is mytype init.') super(MyType,self).__init__(*args,**kwargs) #metaclass 默认为type class Foo(metaclass=MyType): pass
2 根据字符串导入模块
import importlib importlib.import_module()
3装饰器 被装饰装饰的函数,它的函数名会发生改变,保留被装饰的函数的函数名的方法
#测试装饰器 import functools def outer(func): @functools.wraps(func) def inner(*args,**kwargs): return func(*args,**kwargs) return inner @outer def index(args): print('this is index') @outer def login(args): print('this is login.') print(index.__name__) print(login.__name__)
flask 把session设置放到redis缓存中
pip3 install flask-session
pip3 install redis
1 from flask import Flask,session 2 3 app = Flask(__name__) 4 app.secret_key = "adfasdf" 5 6 7 # 将session放置到redis中 8 from flask.ext.session import Session 9 from redis import Redis 10 app.config['SESSION_TYPE'] = 'redis' 11 app.config['SESSION_REDIS'] = Redis(host='192.168.0.94',port='6379',password='xxxx') 12 Session(app) 13 14 # app.session_interface = SecureCookieSessionInterface()() # open_session(self, request) 15 # app.session_interface = RedisSessionInterface() # open_session(self, request) 16 17 18 @app.route('/login') 19 def login(): 20 # {sid: 'sefw3rsdfsdf','user_info':xxxxxx } 21 session['user_info'] = 'xxxxx' 22 return 'login' 23 24 @app.route('/index') 25 def index(): 26 print(session['user_info']) 27 return 'index' 28 29 30 31 if __name__ == '__main__': 32 app.run()
flask blueprint
目录结构
1 创建一个和项目名称一样的package
2 manage.py 为启动项目的run() 方法
3 __init__.py 中实例化Flask对象,引入并注册实例化blueprint的对象。
4 views为blueprint的实例对象目录
5 templates 为模板目录
6 static为静态文件目录
1 from mypro_flask import myapp 2 if __name__ == '__main__': 3 myapp.run()
1 from flask import Flask 2 from mypro_flask.views import account 3 from mypro_flask.views import user 4 myapp=Flask(__name__,) 5 myapp.secret_key='sakula123aasdsad' 6 7 myapp.register_blueprint(account.ac) 8 myapp.register_blueprint(user.u)
1 from flask import Blueprint 2 u=Blueprint('u',__name__,url_prefix='/xx') 3 @u.route('/index') 4 def user(): 5 return 'this is index page.'
1 from flask import Blueprint,render_template,request,redirect,session 2 import functools 3 ac=Blueprint('ac',__name__) 4 5 @ac.route('/login',) 6 def login(): 7 return render_template('login.html')
flask 闪现
1 from flask import flash,Flask,session,get_flashed_messages 2 app=Flask(__name__) 3 app.secret_key='aa123' 4 @app.route('/login') 5 def login(): 6 session['lover']='sakula' 7 flash('this is flash1.',category='k1') 8 flash('this si flash2',category='k2') 9 return 'login' 10 @app.route('/index') 11 def index(): 12 data=get_flashed_messages(category_filter=['k1']) 13 data2=get_flashed_messages(category_filter=('k2')) 14 print(data) 15 print(data2) 16 #print(session.get('lover')) 17 #print(session.pop('lover')) 18 return 'index' 19 if __name__ == '__main__': 20 app.run()
flask 中间件?
flask 上下文管理
a:threading.local 作用:可以为每个线程创建一个独立的空间,让它存放数据
1 import time 2 import threading 3 4 def f1(arg): 5 obj1=threading.local() 6 obj1.value=arg 7 time.sleep(2) 8 print(obj1.value) 9 for i in range(10): 10 t=threading.Thread(target=f1,args=(i,)) 11 t.start()
b:偏函数 flask中多处应用偏函数
1 import functools 2 3 def func(a1,a2,a3): 4 return a1 + a2 + a3 5 6 f1 = functools.partial(func,111) 7 print(f1(22,33)) 8 9 # ########################### 10 import functools 11 class RequestContext(object): 12 def __init__(self): 13 self.request = "xxxxx" 14 self.session = "iusdkfjlskdf" 15 16 obj = RequestContext() 17 # obj.request 18 # obj.session 19 20 21 22 def get_data(name): 23 return getattr(obj,name) 24 25 request_proxy = functools.partial(get_data,'request') 26 session_proxy = functools.partial(get_data,'session') 27 28 request = request_proxy() 29 print(request) 30 31 session = session_proxy() 32 print(session)
c:flask中的__setattr__,__getattr__,threading.get_ident 即线程的唯一标识的应用
1 __setattr__和object.__setattr__(self,'__storage__',{}) 2 from threading import get_ident 3 4 class Local(object): 5 def __init__(self): 6 object.__setattr__(self,'__storage__',{}) 7 8 def __setattr__(self, key, value): 9 ident = get_ident() 10 try: 11 self.__storage__[ident][key] = value 12 except KeyError as e: 13 self.__storage__[ident] = {key:value} 14 def __getattr__(self, item): 15 ident = get_ident() 16 return self.__storage__[ident][item] 17 18 obj = Local() 19 obj.stack = []
d: 1 flask中管理上下文的的push() 中的 __setattr__,__getattr__的利用代理,往字典中的列表注入数据
1 from threading import get_ident 2 3 class Local(object): 4 """ 5 存数据 6 """ 7 def __init__(self): 8 object.__setattr__(self,'__storage__',{}) 9 def __setattr__(self, key, value): 10 ident = get_ident() 11 try: 12 self.__storage__[ident][key] = value 13 except KeyError as e: 14 self.__storage__[ident] = {key:value} 15 def __getattr__(self, item): 16 ident = get_ident() 17 try: 18 return self.self.__storage__[ident][item] 19 except Exception as e: 20 return None 21 22 class LocalStack(object): 23 def __init__(self): 24 self._local = Local() 25 26 def push(self,data): 27 stack = self._local.stack 28 if not stack: 29 self._local.stack = [] 30 self._local.stack.append(data) 31 32 33 stack1 = LocalStack() 34 stack2 = LocalStack() 35 36 37 stack1.push('x1') 38 stack2.push('xxxx') 39 40 41 """ 42 local1 = { 43 "sdfsdfsdf": { stack: ['x1',] } 44 } 45 46 local2 = { 47 "sdfsdfsdf": { stack: ['xxxxxx',] } 48 } 49 """
d: 2 flask中管理上下文的的push() 中的 __setattr__,__getattr__的利用代理,往字典中的列表注入数据(数据被封装到对象中)
1 from threading import get_ident 2 3 class Local(object): 4 """ 5 存数据 6 """ 7 def __init__(self): 8 object.__setattr__(self,'__storage__',{}) 9 def __setattr__(self, key, value): 10 ident = get_ident() 11 try: 12 self.__storage__[ident][key] = value 13 except KeyError as e: 14 self.__storage__[ident] = {key:value} 15 def __getattr__(self, item): 16 ident = get_ident() 17 try: 18 return self.self.__storage__[ident][item] 19 except Exception as e: 20 return None 21 22 class LocalStack(object): 23 def __init__(self): 24 self._local = Local() 25 26 def push(self,data): 27 stack = self._local.stack 28 if not stack: 29 self._local.stack = [] 30 self._local.stack.append(data) 31 32 33 stack1 = LocalStack() 34 stack2 = LocalStack() 35 36 """ 37 local1 = { 38 39 } 40 41 local2 = { 42 43 } 44 """ 45 46 class RequestContext(object): 47 def __init__(self): 48 self.request = '666' 49 self.session = '999' 50 51 ctx = RequestContext() 52 stack1.push(ctx) 53 """ 54 local1 = { 55 'adfasdfasdf': { stack: [ctx(request,session) ] } 56 } 57 58 local2 = { 59 60 } 61 """ 62 63 64 stack2.push('app') 65 66 """ 67 local1 = { 68 'adfasdfasdf': { stack: [ctx(request,session) ] } 69 } 70 71 local2 = { 72 'adfasdfasdf': { stack: ["app" ] } 73 } 74 """