Flask 进阶

OOP 面向对象反射

# __call__方法
# class Foo(object):
# 	def __call__(self, *args, **kwargs):
# 		return "i am call"
#
#
# f = Foo()  # f 是Foo的对象
# print(f())  # f() 对象加括号执行当前对象下__call__ 函数


# __setattr__ , def __getattr__ 属性的创建  赋值  提取
# class Foo(object):
#   # 属性赋值
# 	def __setattr__(self, key, value):
# 		print(f'{key},{value}')
#
# 	# def __getattr__(self, key, value):
# 	# 	print(key)
#   # 获取属性名
# 	def __getattribute__(self, item):
# 		print(item)

# f = Foo()
# 调用__setattr__ 方法;属性的创建及赋值
# f.name = "anwen"  # 对象.name  对象打点调属性
# 调用__getattribute__ 方法
# f.name


# __setitem__  __getitem__
class Foo(object):
	# 字典的键值
	def __setitem__(self, key, value):
		# name anwen
		print(key, value)

	# 字典的键
	def __getitem__(self, item):
		print(item)

f = Foo()
# 调用 __setitem__ 方法;
f["name"] = "anwen"
# 调用__getitem__ 方法;获取的是字典的键
print(f["name"])

偏函数

from functools import partial

# def abfunc(a, b):
# 	print("a:", a)
# 	print("b:", b)
# 	return a + b
#
# # 将原函数和原函数接收的参数一并存放,返回新函数 在执行新函数时 将参数传入原函数中一并执行
# new_ab = partial(abfunc, a=2, b=3)
# print(new_ab)
# print(new_ab())


# 传入 x ,等待计算
def abfunc(a, b, x):
	print("a:", a)
	print("b:", b)
	return a + b + x


# 将原函数和原函数接收的参数一并存放,返回新函数, 在执行新函数时 将参数传入原函数中一并执行
new_ab = partial(abfunc, x=4)
print(new_ab)
print(new_ab(2, 3))

线程安全

import time
import copy
from copy import deepcopy
from threading import Thread, get_ident


class Foo(object):
	pass


f = Foo()
f.num = 0
local_dic = {}
# {
# 	get_ident():{f.num:1},
# 	get_ident():{f.num:2},
# 	get_ident():{f.num:3},
# }

def add(i):
	# print(get_ident())
	# 极快解决阻塞问题,保证公共对象的安全性;但是浪费了很多内存,空间换时间
	local_dic[get_ident()] = deepcopy(f)
	local_dic[get_ident()].num = i
	f.num = i
	time.sleep(1)
	print(local_dic[get_ident()].num)


for i in range(20):
	# 多线程操作同一个对象, 出现线程不安全
	task = Thread(target=add, args=(i,))
	# add(i)
	task.start()

线程安全 local

import time
from threading import Thread, local

# 继承local 解决线程安全问题,还不浪费资源
class Foo(local):
	pass

f = Foo()
f.num = 0

def add(i):
	f.num = i
	time.sleep(1)
	print(f.num)

for i in range(20):
	# 多线程操作同一个对象, 出现线程不安全
	task = Thread(target=add, args=(i,))
	# add(i)
	task.start()

请求上下文 阅读源码

# 请求是如何到达Flask应用的
from werkzeug.wrappers import Request, Response
from werkzeug import run_simple

@Request.application
def app(env):
	print(env, type(env))
	return Response("200 ok")   # 函数+()运行

run_simple("127.0.0.1", 5000, app)
posted @ 2019-09-28 08:15  爱文飞翔  阅读(302)  评论(0编辑  收藏  举报