最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python 裝飾器實(shí)現(xiàn)DRY(不重復(fù)代碼)原則

 更新時(shí)間:2018年03月05日 11:04:31   投稿:mrr  
python的裝飾器就是一種代碼簡(jiǎn)潔的手段,在函數(shù)和方法有改動(dòng)時(shí),使得改動(dòng)量最小。這篇文章給大家介紹了Python 裝飾器實(shí)現(xiàn)DRY(不重復(fù)代碼)原則,感興趣的朋友一起看看吧

Python裝飾器是一個(gè)消除冗余的強(qiáng)大工具。隨著將功能模塊化為大小合適的方法,即使是最復(fù)雜的工作流,裝飾器也能使它變成簡(jiǎn)潔的功能。

例如讓我們看看Django web框架,該框架處理請(qǐng)求的方法接收一個(gè)方法對(duì)象,返回一個(gè)響應(yīng)對(duì)象:

def handle_request(request):
  return HttpResponse("Hello, World")

我最近遇到一個(gè)案例,需要編寫幾個(gè)滿足下述條件的api方法:

  • 返回json響應(yīng)
  • 如果是GET請(qǐng)求,那么返回錯(cuò)誤碼

做為一個(gè)注冊(cè)api端點(diǎn)例子,我將會(huì)像這樣編寫:

def register(request):
  result = None
  # check for post only
  if request.method != 'POST':
    result = {"error": "this method only accepts posts!"}
  else:
    try:
      user = User.objects.create_user(request.POST['username'],
                      request.POST['email'],
                      request.POST['password'])
      # optional fields
      for field in ['first_name', 'last_name']:
        if field in request.POST:
          setattr(user, field, request.POST[field])
      user.save()
      result = {"success": True}
    except KeyError as e:
      result = {"error": str(e) }
  response = HttpResponse(json.dumps(result))
  if "error" in result:
    response.status_code = 500
  return response

然而這樣我將會(huì)在每個(gè)api方法中編寫json響應(yīng)和錯(cuò)誤返回的代碼。這將會(huì)導(dǎo)致大量的邏輯重復(fù)。所以讓我們嘗試用裝飾器實(shí)現(xiàn)DRY原則吧。

裝飾器簡(jiǎn)介

如果你不熟悉裝飾器,我可以簡(jiǎn)單解釋一下,實(shí)際上裝飾器就是有效的函數(shù)包裝器,python解釋器加載函數(shù)的時(shí)候就會(huì)執(zhí)行包裝器,包裝器可以修改函數(shù)的接收參數(shù)和返回值。舉例來說,如果我想要總是返回比實(shí)際返回值大一的整數(shù)結(jié)果,我可以這樣寫裝飾器:

# a decorator receives the method it's wrapping as a variable 'f'
def increment(f):
  # we use arbitrary args and keywords to
  # ensure we grab all the input arguments.
  def wrapped_f(*args, **kw):
    # note we call f against the variables passed into the wrapper,
    # and cast the result to an int and increment .
    return int(f(*args, **kw)) + 1
  return wrapped_f # the wrapped function gets returned.

現(xiàn)在我們就可以用@符號(hào)和這個(gè)裝飾器去裝飾另外一個(gè)函數(shù)了:

@increment
def plus(a, b):
  return a + b
 result = plus(4, 6)
assert(result == 11, "We wrote our decorator wrong!")

裝飾器修改了存在的函數(shù),將裝飾器返回的結(jié)果賦值給了變量。在這個(gè)例子中,'plus'的結(jié)果實(shí)際指向increment(plus)的結(jié)果。

對(duì)于非post請(qǐng)求返回錯(cuò)誤

現(xiàn)在讓我們?cè)谝恍└杏玫膱?chǎng)景下應(yīng)用裝飾器。如果在django中接收的不是POST請(qǐng)求,我們用裝飾器返回一個(gè)錯(cuò)誤響應(yīng)。

def post_only(f):
  """ Ensures a method is post only """
  def wrapped_f(request):
    if request.method != "POST":
      response = HttpResponse(json.dumps(
        {"error": "this method only accepts posts!"}))
      response.status_code = 500
      return response
    return f(request)
  return wrapped_f

現(xiàn)在我們可以在上述注冊(cè)api中應(yīng)用這個(gè)裝飾器:

@post_only
def register(request):
  result = None
  try:
    user = User.objects.create_user(request.POST['username'],
                    request.POST['email'],
                    request.POST['password'])
    # optional fields
    for field in ['first_name', 'last_name']:
      if field in request.POST:
        setattr(user, field, request.POST[field])
    user.save()
    result = {"success": True}
  except KeyError as e:
    result = {"error": str(e) }
  response = HttpResponse(json.dumps(result))
  if "error" in result:
    response.status_code = 500
  return response

現(xiàn)在我們就有了一個(gè)可以在每個(gè)api方法中重用的裝飾器。

發(fā)送json響應(yīng)

為了發(fā)送json響應(yīng)(同時(shí)處理500狀態(tài)碼),我們可以新建另外一個(gè)裝飾器:

def json_response(f):
  """ Return the response as json, and return a 500 error code if an error exists """
  def wrapped(*args, **kwargs):
    result = f(*args, **kwargs)
    response = HttpResponse(json.dumps(result))
    if type(result) == dict and 'error' in result:
      response.status_code = 500
    return response

現(xiàn)在我們就可以在原方法中去除json相關(guān)的代碼,添加一個(gè)裝飾器做為代替:

@post_only
@json_response
def register(request):
  try:
    user = User.objects.create_user(request.POST['username'],
                    request.POST['email'],
                    request.POST['password'])
    # optional fields
    for field in ['first_name', 'last_name']:
      if field in request.POST:
        setattr(user, field, request.POST[field])
    user.save()
    return {"success": True}
  except KeyError as e:
    return {"error": str(e) }

現(xiàn)在,如果我需要編寫新的方法,那么我就可以使用裝飾器做冗余的工作。如果我要寫登錄方法,我只需要寫真正相關(guān)的代碼:

@post_only
@json_response
def login(request):
  if request.user is not None:
    return {"error": "User is already authenticated!"}
  user = auth.authenticate(request.POST['username'], request.POST['password'])
  if user is not None:
    if not user.is_active:
      return {"error": "User is inactive"}
    auth.login(request, user)
    return {"success": True, "id": user.pk}
  else:
    return {"error": "User does not exist with those credentials"}

BONUS: 參數(shù)化你的請(qǐng)求方法

我曾經(jīng)使用過Tubogears框架,其中請(qǐng)求參數(shù)直接解釋轉(zhuǎn)遞給方法這一點(diǎn)我很喜歡。所以要怎樣在Django中模仿這一特性呢?嗯,裝飾器就是一種解決方案!

例如:

def parameterize_request(types=("POST",)):
  """
  Parameterize the request instead of parsing the request directly.
  Only the types specified will be added to the query parameters.
  e.g. convert a=test

注意這是一個(gè)參數(shù)化裝飾器的例子。在這個(gè)例子中,函數(shù)的結(jié)果是實(shí)際的裝飾器。

現(xiàn)在我就可以用參數(shù)化裝飾器編寫方法了!我甚至可以選擇是否允許GET和POST,或者僅僅一種請(qǐng)求參數(shù)類型。

@post_only
@json_response
@parameterize_request(["POST"])
def register(request, username, email, password,
       first_name=None, last_name=None):
  user = User.objects.create_user(username, email, password)
  user.first_name=first_name
  user.last_name=last_name
  user.save()
  return {"success": True}

現(xiàn)在我們有了一個(gè)簡(jiǎn)潔的、易于理解的api。

BONUS #2: 使用functools.wraps保存docstrings和函數(shù)名

很不幸,使用裝飾器的一個(gè)副作用是沒有保存方法名(name)和docstring(doc)值:

def increment(f):
  """ Increment a function result """
  wrapped_f(a, b):
    return f(a, b) + 1
  return wrapped_f
@increment
def plus(a, b)
  """ Add two things together """
  return a + b
plus.__name__ # this is now 'wrapped_f' instead of 'plus'
plus.__doc__  # this now returns 'Increment a function result' instead of 'Add two things together'

這將對(duì)使用反射的應(yīng)用造成麻煩,比如Sphinx,一個(gè) 自動(dòng)生成文檔的應(yīng)用。

為了解決這個(gè)問題,我們可以使用'wraps'裝飾器附加上名字和docstring:

from functools import wraps
def increment(f):
  """ Increment a function result """
  @wraps(f)
  wrapped_f(a, b):
    return f(a, b) + 1
  return wrapped_f
@increment
def plus(a, b)
  """ Add two things together """
  return a + b
 
plus.__name__ # this returns 'plus'
plus.__doc__  # this returns 'Add two things together'

BONUS #3: 使用'decorator'裝飾器

如果仔細(xì)看看上述使用裝飾器的方式,在包裝器聲明和返回的地方也有不少重復(fù)。

你可以安裝python egg ‘decorator',其中包含一個(gè)提供裝飾器模板的'decorator'裝飾器!

使用easy_install:

$ sudo easy_install decorator

或者Pip:

$ pip install decorator

然后你可以簡(jiǎn)單的編寫:

from decorator import decorator
@decorator
def post_only(f, request):
  """ Ensures a method is post only """
  if request.method != "POST":
    response = HttpResponse(json.dumps(
      {"error": "this method only accepts posts!"}))
    response.status_code = 500
    return response
  return f(request)

這個(gè)裝飾器更牛逼的一點(diǎn)是保存了name和doc的返回值,也就是它封裝了

functools.wraps的功能!

相關(guān)文章

  • 用Python3通過PyCharm上傳代碼到Git服務(wù)器的詳細(xì)過程

    用Python3通過PyCharm上傳代碼到Git服務(wù)器的詳細(xì)過程

    上傳代碼到服務(wù)器,如果不知道的情況下還用傳統(tǒng)的方式上傳很麻煩,現(xiàn)在很多IDE都提供上傳代碼的功能,例如:VSCode,PyCharm等等,本文講解的是PyCharm,需要的朋友可以參考下
    2024-03-03
  • Python獲取網(wǎng)頁數(shù)據(jù)詳解流程

    Python獲取網(wǎng)頁數(shù)據(jù)詳解流程

    讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Python來獲取網(wǎng)頁的數(shù)據(jù),主要應(yīng)用了Requests庫,大家可以在過程中查缺補(bǔ)漏,提升水平
    2021-10-10
  • python sqlobject(mysql)中文亂碼解決方法

    python sqlobject(mysql)中文亂碼解決方法

    在使用python寫項(xiàng)目的時(shí)候,用到了sqlobject庫函數(shù)connectionForURI連接mysql,但是遇到了中文顯示亂碼的問題,在添加記錄的時(shí)候還拋出異常
    2008-11-11
  • Python中的Pydantic序列化詳解

    Python中的Pydantic序列化詳解

    這篇文章主要介紹了Python中的Pydantic序列化詳解,Pydantic 是 Python 中一個(gè)高性能的數(shù)據(jù)驗(yàn)證和序列化庫,它提供了一個(gè)簡(jiǎn)單而強(qiáng)大的方式來定義結(jié)構(gòu)化的數(shù)據(jù),并在應(yīng)用程序的各個(gè)層次中使用這些數(shù)據(jù),需要的朋友可以參考下
    2023-10-10
  • 基于Python編寫詞云軟件并顯示分詞結(jié)果

    基于Python編寫詞云軟件并顯示分詞結(jié)果

    這篇文章主要為大家詳細(xì)介紹了如何基于Python編寫一個(gè)簡(jiǎn)單的詞云制作軟件并顯示分詞結(jié)果,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解一下
    2023-10-10
  • Python設(shè)置Word頁面紙張方向?yàn)闄M向

    Python設(shè)置Word頁面紙張方向?yàn)闄M向

    這篇文章主要為大家詳細(xì)介紹了Python設(shè)置Word頁面紙張方向?yàn)闄M向的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起
    2024-02-02
  • Python中?*?號(hào)的用法總結(jié)

    Python中?*?號(hào)的用法總結(jié)

    Python中的?*號(hào)是一個(gè)特殊的符號(hào),在其他編程語言中,它最廣為人知的用途就是作為乘法運(yùn)算的符號(hào),本文總結(jié)了Python中*號(hào)的所有用途,希望對(duì)大家有所幫助
    2023-11-11
  • python處理二進(jìn)制數(shù)據(jù)的方法

    python處理二進(jìn)制數(shù)據(jù)的方法

    這篇文章主要介紹了python處理二進(jìn)制數(shù)據(jù)的方法,涉及Python針對(duì)二進(jìn)制數(shù)據(jù)的相關(guān)操作技巧,需要的朋友可以參考下
    2015-06-06
  • 詳解Python 3D引擎Ursina如何繪制立體圖形

    詳解Python 3D引擎Ursina如何繪制立體圖形

    Python有一個(gè)不錯(cuò)的3D引擎——Ursina。本文就來手把手教你認(rèn)識(shí)Ursina并學(xué)會(huì)繪制立體圖形,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-01-01
  • pytest配置文件pytest.ini的詳細(xì)使用

    pytest配置文件pytest.ini的詳細(xì)使用

    這篇文章主要介紹了pytest配置文件pytest.ini的詳細(xì)使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04

最新評(píng)論

崇仁县| 庆安县| 富宁县| 桦甸市| 牙克石市| 沅陵县| 阳西县| 松桃| 兴文县| 安溪县| 木兰县| 东源县| 革吉县| 北海市| 紫金县| 泸定县| 江北区| 阿克陶县| 天气| 遂宁市| 三门峡市| 南漳县| 丹凤县| 织金县| 洛南县| 皋兰县| 申扎县| 伊宁市| 那曲县| 东兴市| 临江市| 台江县| 济阳县| 翁牛特旗| 万山特区| 临武县| 玉山县| 巍山| 固镇县| 太白县| 沁源县|