Cherrypy-toolbox

提供:Dev Guides
移動先:案内検索

CherryPy-ツールボックス

CherryPy内では、組み込みツールはCherryPyライブラリを呼び出すための単一のインターフェースを提供します。 CherryPyで定義されたツールは、次の方法で実装することができます-

  • 構成設定から
  • Pythonデコレータとして、またはページハンドラの特別な_cp_config属性を介して
  • 任意の関数内から適用できるPython呼び出し可能オブジェクトとして

基本認証ツール

このツールの目的は、アプリケーションで設計されたアプリケーションに基本認証を提供することです。

引数

このツールは、次の引数を使用します-

Name Default Description
realm N/A String defining the realm value.
users N/A Dictionary of the form − username:password or a Python callable function returning such a dictionary.
encrypt None Python callable used to encrypt the password returned by the client and compare it with the encrypted password provided in the users dictionary.

それがどのように機能するかを理解するために例を挙げましょう-

import sha
import cherrypy

class Root:
@cherrypy.expose
def index(self):

return """
<html>
   <head></head>
   <body>
      <a href = "admin">Admin </a>
   </body>
</html>
"""

class Admin:

@cherrypy.expose
def index(self):
return "This is a private area"

if __name__ == '__main__':
def get_users():
# 'test': 'test'
return {'test': 'b110ba61c4c0873d3101e10871082fbbfd3'}
def encrypt_pwd(token):

return sha.new(token).hexdigest()
   conf = {'/admin': {'tools.basic_auth.on': True,
      tools.basic_auth.realm': 'Website name',
      'tools.basic_auth.users': get_users,
      'tools.basic_auth.encrypt': encrypt_pwd}}
   root = Root()
root.admin = Admin()
cherrypy.quickstart(root, '/', config=conf)
*get_users* 関数は、ハードコーディングされた辞書を返しますが、データベースまたはその他の場所から値をフェッチします。 クラス管理者には、CherryPyの認証組み込みツールを使用するこの関数が含まれています。 認証により、パスワードとユーザーIDが暗号化されます。

基本的な認証ツールは、パスワードが侵入者によってエンコードおよびデコードされる可能性があるため、実際には安全ではありません。

キャッシングツール

このツールの目的は、CherryPyで生成されたコンテンツのメモリキャッシュを提供することです。

引数

このツールは、次の引数を使用します-

Name Default Description
invalid_methods ("POST", "PUT", "DELETE") Tuples of strings of HTTP methods not to be cached. These methods will also invalidate (delete) any cached copy of the resource.
cache_Class MemoryCache Class object to be used for caching

デコードツール

このツールの目的は、着信要求パラメーターをデコードすることです。

引数

このツールは、次の引数を使用します-

Name Default Description
encoding None It looks for the content-type header
Default_encoding "UTF-8" Default encoding to be used when none is provided or found.

それがどのように機能するかを理解するために例を挙げましょう-

import cherrypy
from cherrypy import tools

class Root:
@cherrypy.expose
def index(self):

return """
<html>
   <head></head>
   <body>
      <form action = "hellol" method = "post">
         <input type = "text" name = "name" value = ""/>
         <input type = ”submit” name = "submit"/>
      </form>
   </body>
</html>
"""

@cherrypy.expose
@tools.decode(encoding='ISO-88510-1')
def hello(self, name):
return "Hello %s" % (name, )
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/')

上記のコードは、ユーザーから文字列を取得し、ユーザーを "hellol"ページにリダイレクトします。このページでは、指定された名前の "Hello"として表示されます。

上記のコードの出力は次のとおりです-

デコードツール

hellol

デコードツールの出力