- CherryPy 教程
- CherryPy - 首頁
- CherryPy - 簡介
- CherryPy - 環境設定
- CherryPy - 詞彙表
- 內建 HTTP 伺服器
- CherryPy - 工具箱
- CherryPy - 一個工作應用程式
- CherryPy - Web 服務
- CherryPy - 表示層
- CherryPy - Ajax 的使用
- CherryPy - 演示應用程式
- CherryPy - 測試
- 應用程式的部署
- CherryPy 有用資源
- CherryPy - 快速指南
- CherryPy - 有用資源
- CherryPy - 討論
CherryPy - 工具箱
在 CherryPy 中,內建工具提供了一個單一的介面來呼叫 CherryPy 庫。CherryPy 中定義的工具可以透過以下方式實現:
- 從配置設定
- 作為 Python 裝飾器或透過頁面處理程式的特殊 _cp_config 屬性
- 作為可以在任何函式內部應用的 Python 可呼叫物件
基本身份驗證工具
此工具的目的是為應用程式中設計的應用程式提供基本身份驗證。
引數
此工具使用以下引數:
| 名稱 | 預設值 | 描述 |
|---|---|---|
| 領域 | N/A | 定義領域值的字串。 |
| 使用者 | N/A | 表單為 username:password 的字典或返回此類字典的 Python 可呼叫函式。 |
| 加密 | 無 | 用於加密客戶端返回的密碼並將其與使用者字典中提供的加密密碼進行比較的 Python 可呼叫物件。 |
示例
讓我們舉一個例子來了解它是如何工作的:
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。
基本身份驗證工具實際上並不安全,因為密碼可以被入侵者編碼和解碼。
快取工具
此工具的目的是提供 CherryPy 生成的內容的記憶體快取。
引數
此工具使用以下引數:
| 名稱 | 預設值 | 描述 |
|---|---|---|
| 無效方法 | ("POST", "PUT", "DELETE") | 不應快取的 HTTP 方法的字串元組。這些方法還將使資源的任何快取副本失效(刪除)。 |
| 快取類 | MemoryCache | 用於快取的類物件 |
解碼工具
此工具的目的是解碼傳入的請求引數。
引數
此工具使用以下引數:
| 名稱 | 預設值 | 描述 |
|---|---|---|
| 編碼 | 無 | 它查詢內容型別標頭 |
| 預設編碼 | "UTF-8" | 當未提供或找到任何編碼時使用的預設編碼。 |
示例
讓我們舉一個例子來了解它是如何工作的:
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
廣告