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)
相關文章
相關標籤/搜索