第 12 章:SOAP Web 服务

第 11 章 侧重于基于 HTTP 的面向文档的 Web 服务。“输入参数”是 URL,“返回值”是一个实际的 XML 文档,您需要负责解析。

本章将重点介绍 SOAP Web 服务,它采用更结构化的方式。 SOAP 允许您模拟调用返回原生数据类型的函数,而不是直接处理 HTTP 请求和 XML 文档。正如您将看到的,这种模拟几乎是完美的;您可以使用标准的 Python 调用语法通过 SOAP 库“调用”函数,并且该函数似乎返回 Python 对象和值。但在幕后,SOAP 库实际上执行了一个涉及多个 XML 文档和远程服务器的复杂事务。

SOAP 是一个复杂的规范,说 SOAP 完全是关于调用远程函数的说法有点误导。有些人会插话说 SOAP 允许单向异步消息传递和面向文档的 Web 服务。这些人是正确的;SOAP 可以以这种方式使用,并且可以使用许多不同的方式。但本章将重点介绍所谓的“RPC 风格SOAP——调用远程函数并获取结果。

12.1. 初探究竟

您使用 Google,对吧?这是一个流行的搜索引擎。您是否曾希望以编程方式访问 Google 搜索结果?现在您可以了。这是一个从 Python 搜索 Google 的程序。

示例 12.1. search.py

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”的示例输出。

示例 12.2. search.py 的使用示例

C:\diveintopython\common\py> python search.py "python"
<b>Python</b> Programming Language
https://pythonlang.cn/
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
https://pythonlang.cn/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
https://pythonlang.cn/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>
https://diveintopythonbook.pythonlang.cn/
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>

SOAP 扩展阅读