在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