developer.google.com 的示例实际上使用 Python,所以这是一个很好的起点。
但是,API 似乎太小了,以至于官方文档也只是选择使用urllib 和httplib Python 内置模块。将该逻辑推广到一个或两个辅助函数中似乎是一项微不足道的任务。
...
params = urllib.urlencode([
('js_code', sys.argv[1]),
('compilation_level', 'WHITESPACE_ONLY'),
('output_format', 'text'),
('output_info', 'compiled_code'),
])
# Always use the following value for the Content-type header.
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPConnection('closure-compiler.appspot.com')
conn.request('POST', '/compile', params, headers)
...
见https://developers.google.com/closure/compiler/docs/api-tutorial1
P.S.您还可以查看https://github.com/danielfm/closure-compiler-cli——它是一个命令行工具,但源代码展示了 API 的真正简单性。
所以把上面的变成 Pythonic API:
import httplib
import sys
import urllib
from contextlib import closing
def call_closure_api(**kwargs):
with closing(httplib.HTTPConnection('closure-compiler.appspot.com')) as conn:
conn.request(
'POST', '/compile',
urllib.urlencode(kwargs.items()),
headers={"Content-type": "application/x-www-form-urlencoded"}
)
return conn.getresponse().read()
call_closure_api(
js_code=sys.argv[1],
# feel free to introduce named constants for these
compilation_level='WHITESPACE_ONLY',
output_format='text',
output_info='compiled_code'
)