W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
RESTful Web服務在以下幫助下實現(xiàn)CherryPy架構(gòu)的每個部分 -
身份驗證有助于驗證與我們交互的用戶。 CherryPy包含處理每種身份驗證方法的工具。
def authenticate():
if not hasattr(cherrypy.request, 'user') or cherrypy.request.user is None:
# < Do stuff to look up your users >
cherrypy.request.authorized = False # This only authenticates.
Authz must be handled separately.
cherrypy.request.unauthorized_reasons = []
cherrypy.request.authorization_queries = []
cherrypy.tools.authenticate = \
cherrypy.Tool('before_handler', authenticate, priority=10)
上述函數(shù)authenticate()將有助于驗證客戶端或用戶的存在。 內(nèi)置工具有助于系統(tǒng)地完成該過程。
授權(quán)有助于通過URI維護流程的健全性。 該過程還有助于通過用戶令牌引線變形對象。
def authorize_all():
cherrypy.request.authorized = 'authorize_all'
cherrypy.tools.authorize_all = cherrypy.Tool('before_handler', authorize_all, priority=11)
def is_authorized():
if not cherrypy.request.authorized:
raise cherrypy.HTTPError("403 Forbidden",
','.join(cherrypy.request.unauthorized_reasons))
cherrypy.tools.is_authorized = cherrypy.Tool('before_handler', is_authorized,
priority = 49)
cherrypy.config.update({
'tools.is_authorized.on': True,
'tools.authorize_all.on': True
})
內(nèi)置的授權(quán)工具有助于系統(tǒng)地處理例程,如前面的示例所述。
維護API結(jié)構(gòu)有助于減少映射應用程序URI的工作量。 始終需要保持API可被發(fā)現(xiàn)和清潔。 CherryPy框架的API的基本結(jié)構(gòu)應該如下 -
封裝有助于創(chuàng)建輕量級,人類可讀且可供各種客戶端訪問的API。 項目列表以及創(chuàng)建,檢索,更新和刪除需要封裝API。
如果API無法以特定的本能執(zhí)行,此過程將管理錯誤(如果有)。 例如,400表示錯誤請求,403表示未授權(quán)請求。
請考慮以下內(nèi)容作為數(shù)據(jù)庫,驗證或應用程序錯誤的示例。
import cherrypy
import json
def error_page_default(status, message, traceback, version):
ret = {
'status': status,
'version': version,
'message': [message],
'traceback': traceback
}
return json.dumps(ret)
class Root:
_cp_config = {'error_page.default': error_page_default}
@cherrypy.expose
def index(self):
raise cherrypy.HTTPError(500, "Internal Sever Error")
cherrypy.quickstart(Root())
上面的代碼將產(chǎn)生以下輸出 -
由于內(nèi)置的??訪問工具,通過CherryPy可以輕松管理API(應用程序編程接口)。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: