在CherryPy中,內置工具提供一個調用CherryPy庫的接口。CherryPy中定義的工具可以通過以下方式實現&負;
- From the configuration settings
- As a Python decorator or via the special _cp_config attribute of a page handler
- As a Python callable that can be applied from within any function
Basic Authentication Tool
此工具的目的是爲應用程式中設計的應用程式提供基本身份驗證。
Arguments
此工具使用以下參數−
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. |
Example
讓我們舉一個例子來了解它是如何工作的;
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函數返回一個硬編碼字典,但也從資料庫或其他任何地方獲取值。類admin包括這個函數,它使用CherryPy的一個內置認證工具。身份驗證對密碼和用戶Id進行加密。
基本的身份驗證工具並不真正安全,因爲密碼可以被入侵者編碼和解碼。
Caching Tool
這個工具的目的是爲CherryPy生成的內容提供內存緩存。
Arguments
此工具使用以下參數−
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 |
Decoding Tool
此工具的目的是解碼傳入的請求參數。
Arguments
此工具使用以下參數−
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. |
Example
讓我們舉一個例子來了解它是如何工作的;
import cherrypy from cherrypy import tools class Root: @cherrypy.expose def index(self): return """ <html> <head></head> <body> <form action = "hello.html" 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(), '/')
上面的代碼從用戶那裡獲取一個字符串,並將用戶重定向到「hello.html」頁面,在該頁面上,它將以給定的名稱顯示爲「hello」。
上述代碼的輸出如下所示&負;
hello.html