CherryPy REST接口通过CherryPy

2023-12-31 21:57 更新

RESTful Web服务在以下帮助下实现CherryPy架构的每个部分 -

  • Authentication
  • Authorization
  • Structure
  • Encapsulation
  • 错误处理

身份验证 (Authentication)

身份验证有助于验证与我们交互的用户。 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)

上述函数authenticate()将有助于验证客户端或用户的存在。 内置工具有助于系统地完成该过程。

授权 (Authorization)

授权有助于通过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
})

内置的授权工具有助于系统地处理例程,如前面的示例所述。

结构 Structure

维护API结构有助于减少映射应用程序URI的工作量。 始终需要保持API可被发现和清洁。 CherryPy框架的API的基本结构应该如下 -

  • 帐户和用户
  • Autoresponder
  • Contact
  • File
  • Folder
  • 列表和字段
  • Message and Batch

封装 (Encapsulation)

封装有助于创建轻量级,人类可读且可供各种客户端访问的API。 项目列表以及创建,检索,更新和删除需要封装API。

错误处理

如果API无法以特定的本能执行,此过程将管理错误(如果有)。 例如,400表示错误请求,403表示未授权请求。

例子 (Example)

请考虑以下内容作为数据库,验证或应用程序错误的示例。

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())

上面的代码将产生以下输出 -

错误处理

由于内置的​​访问工具,通过CherryPy可以轻松管理API(应用程序编程接口)。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号