| 導航:起始頁 > Dive Into Python > SOAP Web 服務 | << >> | ||||
深入 Python :Dive Into Python 中文版Python 從新手到專家 [Dip_5.4b_CPyUG_Release] |
|||||
第 11 章 關注 HTTP 上面向文檔的web 服務。“輸入參數” 是 URL,“返回值” 是需要你來解析的一個實際的 XML 文檔。
本章將關注更加結構化的 SOAP web 服務。SOAP 不需要你直接與 HTTP 請求和 XML 文檔打交道,而是允許你模擬返回原始數據類型的函數調用。正像你將要看到的,這個描述恰如其份;你可以使用標準 Python 調用語法通過 SOAP 庫去調用一個函數,這個函數也自然會返回 Python 對象和值。但揭開這層面紗,SOAP 庫實際上執行了一個多個 XML 文檔和遠程服務器參與的復雜處理過程。
SOAP 的貼切定義很復雜,不要誤認為 SOAP 就是用于調用遠程函數。有些人覺得應該補充上:SOAP 還允許單向異步的信息通過,以及面向文檔的 Web 服務。有這樣想法的人是正確的,SOAP 的確是這樣,但卻不止于此。但這一章的重點在于所謂的 “RPC-style” SOAP――調用遠程函數獲得返回結果。
你用 Google,對吧?它是一個很流行的搜索引擎。你是否希望能以程序化的方式訪問 Google 的搜索結果呢?現在你能做到了。下面是一個用 Python 搜索 Google 的程序。
from SOAPpy import WSDL # you'll need to configure these two values; # see http://www.google.com/apis/ WSDLFILE = '/path/to/copy/of/GoogleSearch.wsdl' APIKEY = 'YOUR_GOOGLE_API_KEY' _server = WSDL.Proxy(WSDLFILE) def search(q): """Search Google and return list of {title, link, description}""" results = _server.doGoogleSearch( APIKEY, q, 0, 10, False, "", False, "", "utf-8", "utf-8") return [{"title": r.title.encode("utf-8"), "link": r.URL.encode("utf-8"), "description": r.snippet.encode("utf-8")} for r in results.resultElements] if __name__ == '__main__': import sys for r in search(sys.argv[1])[:5]: print r['title'] print r['link'] print r['description'] print
你可以在較大的程序中以模塊導入并使用它,也可以在命令行上運行這個腳本。在命令行上,需要把查詢字符串作為命令行參數使用,之后就會打印出最前面的五個 Google 查詢結果,包括:URL、標題和描述信息。
下面是以 “python” 作為命令行參數的查詢結果。
C:\diveintopython\common\py> python search.py "python" <b>Python</b> Programming Language http://www.python.org/ Home page for <b>Python</b>, an interpreted, interactive, object-oriented, extensible<br> programming language. <b>...</b> <b>Python</b> is OSI Certified Open Source: OSI Certified. <b>Python</b> Documentation Index http://www.python.org/doc/ <b>...</b> New-style classes (aka descrintro). Regular expressions. Database API. Email Us.<br> docs@<b>python</b>.org. (c) 2004. <b>Python</b> Software Foundation. <b>Python</b> Documentation. <b>...</b> Download <b>Python</b> Software http://www.python.org/download/ Download Standard <b>Python</b> Software. <b>Python</b> 2.3.3 is the current production<br> version of <b>Python</b>. <b>...</b> <b>Python</b> is OSI Certified Open Source: Pythonline http://www.pythonline.com/ Dive Into <b>Python</b> http://diveintopython.org/ Dive Into <b>Python</b>. <b>Python</b> from novice to pro. Find: <b>...</b> It is also available in multiple<br> languages. Read Dive Into <b>Python</b>. This book is still being written. <b>...</b>
<< 小結 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
安裝 SOAP 庫 >> |