﻿<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>奋斗足迹&#124;崔玉松 &#187; Python</title>
	<atom:link href="http://fendou.org/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://fendou.org</link>
	<description>为家人，为自己，为生活~~</description>
	<lastBuildDate>Fri, 24 Feb 2012 15:21:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Python Web Server Gateway Interface v1.0.1 不完整翻译</title>
		<link>http://fendou.org/2011/11/23/python-web-server-gateway-interface-v1-0-1/</link>
		<comments>http://fendou.org/2011/11/23/python-web-server-gateway-interface-v1-0-1/#comments</comments>
		<pubDate>Wed, 23 Nov 2011 03:07:34 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Excellence Article]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[译文]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=860</guid>
		<description><![CDATA[Contents 简介 基本原理与目标 概述 应用接口 服务器接口 中间件 : 同时扮演两种角色的组件 详细说明 environ 变量 输入和错误流 start_response() 可调用者 Handling the Content-Length Header Buffering and Streaming Middleware Handling of Block Boundaries The write() Callable Unicode Issues Error Handling HTTP 1.1 Expect/Continue Other HTTP Features Thread Support Implementation/Application Notes Server Extension APIs Application Configuration URL Reconstruction Supporting Older (<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python和其他语言数据类型比较" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2009%2F03%2F16%2Fpython-and-programming%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python和其他语言数据类型比较</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Httpsqs Python Client" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Httpsqs Python Client</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python Queue 的多线程(multi thread)死锁问题" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python Queue 的多线程(multi thread)死锁问题</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>Contents</p>
<p>简介<br />
基本原理与目标<br />
概述<br />
应用接口<br />
服务器接口<br />
中间件 : 同时扮演两种角色的组件<br />
详细说明<br />
environ 变量<br />
输入和错误流<br />
start_response() 可调用者<br />
Handling the Content-Length Header<br />
Buffering and Streaming<br />
Middleware Handling of Block Boundaries<br />
The write() Callable<br />
Unicode Issues<br />
Error Handling<br />
HTTP 1.1 Expect/Continue<br />
Other HTTP Features<br />
Thread Support<br />
Implementation/Application Notes<br />
Server Extension APIs<br />
Application Configuration<br />
URL Reconstruction<br />
Supporting Older (<2.2) Versions of Python<br />
Optional Platform-Specific File Handling<br />
Questions and Answers<br />
Proposed/Under Discussion<br />
Acknowledgements<br />
References<br />
Copyright<br />
简介</p>
<p>本文档描述一份在web服务器与web应用/web框架之间的标准接口，此接口的目的是使得web应用在不同web服务器之间具有可移植性。</p>
<p>基本原理与目标</p>
<p>python目前拥有大量的web框架，比如 Zope, Quixote, Webware, SkunkWeb, PSO, 和Twisted Web。大量的选择使得新手无所适从，因为总得来说，框架的选择都会限制web服务器的选择。</p>
<p>对比之下，虽然java也拥有许多web框架，但是java的" servlet" API使得使用任何框架编写出来的应用程序可以在任何支持" servlet" API的web服务器上运行。 服务器中这种针对python的API（不管服务器是用python写的，还是内嵌python，还是通过一种协议来启动python）的使用和普及，将分离人们对web框架和对web服务器的选择，用户可以自由选择适合他们的组合，而web服务器和web框架的开发者也能够把精力集中到各自的领域。</p>
<p>因此，这份PEP建议在web服务器和web应用/web框架之间建立一种简单的通用的接口规范，Python Web Server Gateway Interface (WSGI).</p>
<p>但是光有这么一份规范对于改变web服务器和web应用/框架的现状是不够的，只有web服务器和web框架的作者们实现WSGI，他才能起应有的效果。</p>
<p>然而，既然还没有任何框架或服务器实现了WSGI，对实现WSGI也没有什么直接的奖励，那么WSGI必须容易实现，这样才能降低作者的初始投资。</p>
<p>服务器和框架两边接口的实现的简单性，对于WSGI的作用来说，绝对是非常重要的。所以这一点是任何设计决策的首要依据。</p>
<p>对于框架作者来说，实现的简单和使用的方便是不一样的。WSGI为框架作者展示一套绝对没有"frills"的接口，因为象response对象和对cookie的处理这些问题和框架现有的对这些问题的处理是矛盾的。再次重申一遍，WSGI的目的是使得web框架和web服务器之间轻松互连，而不是创建一套新的web框架。</p>
<p>同时也要注意到，这个目标使得WSGI不能依赖任何在当前已部署版本的python没有提供的任何功能，因此，也不会依赖于任何新的标准模块，并且WSGI并不需要2.2.2以上版本的python(当然，在以后的python标准库中内建支持这份接口的web服务器也是个不错的主意)</p>
<p>不光要让现有的或将要出现的框架和服务器容易实现，也应该容易创建请求预处理器、响应处理程序和其他基于WSGI的中间件组件，对于服务器来说他们是应用程序，而对于他们包含的应用程序来说他们是服务器。</p>
<p>如果中间件既简单又健壮，而且WSGI广泛得实现在服务器和框架中，那么就有可能出现全新的python web框架：整个框架都是由几个WSGI中间件组件组成。甚至现有框架的作者都会选择重构将以实现的服务以这种方式提供，变得更象一些和WSGI配合使用的库而不是一个独立的框架。这样web应用开发这就可以根据特定功能选择最适合的组件，而不是所有功能都由同一个框架提供。</p>
<p>当然，这一天无疑还要等很久，在这之间，一个合适的短期目标就是让任何框架在任何服务器上运行起来。</p>
<p>最后，需要指出的是当前版本的WSGI并没有规定一个应用具体以何种方式部署在web服务器或gateway上。目前，这个需要由服务器或gateway的具体实现来定义。如果足够多实现了WSGI的服务器或gateway通过领域实践产生了这个需求，也许可以产生另一份PEP来描述WSGI服务器和应用框架的部署标准。</p>
<p>概述</p>
<p>WSGI接口有两种形式：一个是针对服务器或gateway的，另一个针对应用程序或框架。服务器接口请求一个由应用接口提供的可调用的对象，至于该对象是如何被请求的取决与服务器或gateway。我们假定一些服务器或gateway会需要应用程序的部署人员编写一个简短的脚本来启动一个服务器或gateway的实例，并把应用程序对象提供得服务器，而其他的服务器或gateway需要配置文件或其他机制来指定从哪里导入或者或得应用程序对象。</p>
<p>除了纯粹的服务器/gateway和应用程序/框架，还可以创建实现了这份规格说明书的中间件组件，对于包含他们的服务器他们是应用程序，而对于他们包含的应用程序来说他们是服务器，他们可以用来提供可扩展的API，内容转换，导航和其他有用的功能。</p>
<p>在整个规格说明书中，我们使用短语"一个可调用者"意思是"一个函数，方法，类，或者拥有 __call__ 方法的一个对象实例",这取决与服务器，gateway，应用程序根据需要而选择的合适实现方式。相反服务器，gateway和请求一个可调用者的应用程序不可以依赖具体的实现方式，not introspected upon.</p>
<p>应用接口</p>
<p>一个应用程序对象是一个简单的接受两个参数的可调用对象，这里的对象并不是真的需要一个对象实例，一个函数、方法、类、或者带有 __call__ 方法的对象实例都可以用来做应用程序对象。应用程序对象必须可以多次被请求，实际上服务器/gateway(而非CGI)确实会产生这样的重复请求。</p>
<p>(注意：虽然我们把他叫做"应用程序"对象，但并不是说程序员要把WSGI当做API来调用，我们假定应用程序开发者仍然使用更高层面上的框架服务来开发应用程序，WSGI是提供给框架和服务器开发者使用的工具，并不打算直接对应用程序开发者提供支持)</p>
<p>这里有两个应用程序对象的示例，一个是函数，另一个是类:</p>
<p>def simple_app(environ, start_response):<br />
    """也许是最简单的应用程序对象"""<br />
    status = '200 OK'<br />
    response_headers = [('Content-type','text/plain')]<br />
    start_response(status, response_headers)<br />
    return ['Hello world!\n']</p>
<p>class AppClass:<br />
    """产生同样的输出，不过是使用一个类来实现</p>
<p>    (注意: 'AppClass' 在这里就是 "application" ,所以对它的调用会'AppClass'的一个实例,<br />
    这个实例做为迭代器再返回"application callable"应该返回的那些值)</p>
<p>    如果我们想使用 'AppClass' 的实例直接作为应用程序对象, 我们就必须实现 ``__call__`` 方法,<br />
    外部通过调用这个方法来执行应用程序, 并且我们需要创建一个实例给服务器或gateway使用.<br />
    """</p>
<p>    def __init__(self, environ, start_response):<br />
        self.environ = environ<br />
        self.start = start_response</p>
<p>    def __iter__(self):<br />
        status = '200 OK'<br />
        response_headers = [('Content-type','text/plain')]<br />
        self.start(status, response_headers)<br />
        yield "Hello world!\n"<br />
服务器接口</p>
<p>服务器/gateway为每一个http客户端发来的请求都会请求应用程序可调用者一次。为了说明这里有一个CGI gateway，以一个获取应用程序对象的函数实现，请注意，这个例子拥有有限的错误处理，因为默认情况下没有被捕获的异常都会被输出到sys.stderr并被服务器记录下来。</p>
<p>import os, sys</p>
<p>def run_with_cgi(application):</p>
<p>    environ = dict(os.environ.items())<br />
    environ['wsgi.input']        = sys.stdin<br />
    environ['wsgi.errors']       = sys.stderr<br />
    environ['wsgi.version']      = (1,0)<br />
    environ['wsgi.multithread']  = False<br />
    environ['wsgi.multiprocess'] = True<br />
    environ['wsgi.run_once']    = True</p>
<p>    if environ.get('HTTPS','off') in ('on','1'):<br />
        environ['wsgi.url_scheme'] = 'https'<br />
    else:<br />
        environ['wsgi.url_scheme'] = 'http'</p>
<p>    headers_set = []<br />
    headers_sent = []</p>
<p>    def write(data):<br />
        if not headers_set:<br />
             raise AssertionError("write() before start_response()")</p>
<p>        elif not headers_sent:<br />
             # Before the first output, send the stored headers<br />
             status, response_headers = headers_sent[:] = headers_set<br />
             sys.stdout.write('Status: %s\r\n' % status)<br />
             for header in response_headers:<br />
                 sys.stdout.write('%s: %s\r\n' % header)<br />
             sys.stdout.write('\r\n')</p>
<p>        sys.stdout.write(data)<br />
        sys.stdout.flush()</p>
<p>    def start_response(status,response_headers,exc_info=None):<br />
        if exc_info:<br />
            try:<br />
                if headers_sent:<br />
                    # Re-raise original exception if headers sent<br />
                    raise exc_info[0], exc_info[1], exc_info[2]<br />
            finally:<br />
                exc_info = None     # avoid dangling circular ref<br />
        elif headers_set:<br />
            raise AssertionError("Headers already set!")</p>
<p>        headers_set[:] = [status,response_headers]<br />
        return write</p>
<p>    result = application(environ, start_response)<br />
    try:<br />
        for data in result:<br />
            if data:    # body 出现以前不发送headers<br />
                write(data)<br />
        if not headers_sent:<br />
            write('')   # 如果这个时候body为空则发送header<br />
    finally:<br />
        if hasattr(result,'close'):<br />
            result.close()<br />
中间件 : 同时扮演两种角色的组件</p>
<p>注意到单个对象可以作为请求应用程序的服务器存在，也可以作为被服务器调用的应用程序存在。这样的中间件可以执行这样一些功能:</p>
<p>重写前面提到的 environ 之后，可以根据目标URL将请求传递到不同的应用程序对象<br />
允许多个应用程序和框架在同一个进程中运行<br />
通过在网络传递请求和响应，实现负载均衡和远程处理<br />
对内容进行后加工，比如附加xsl样式表<br />
中间件的存在对于服务器接口和应用接口来说都应该是透明的，并且不需要特别的支持。希望在应用程序中加入中间件的用户只需简单得把中间件当作应用提供给服务器，并配置中间件足见以服务器的身份来请求应用程序。</p>
<p>当然，中间件组件包裹的可能是包裹应用程序的另一个中间件组件，这样循环下去就构成了我们称为"中间件堆栈"的东西了。 for the most part,中间件要符合应用接口和服务器接口提出的一些限制和要求，有些时候这样的限制甚至比纯粹的服务器或应用程序还要严格，这些地方我们会特别指出。</p>
<p>这里有一个中间件组件的例子，他用Joe Strout的piglatin.py将text/plain的响应转换成pig latin（注意：真正的中间件应该使用更加安全的方式——应该检查内容的类型和内容的编码，同样这个简单的例子还忽略了一个单词might be split across a block boundary的可能性)。</p>
<p>from piglatin import piglatin</p>
<p>class LatinIter:</p>
<p>    """如果可以的话，将输出转换为piglatin格式</p>
<p>    Note that the "okayness" can change until the application yields<br />
    its first non-empty string, so 'transform_ok' has to be a mutable<br />
    truth value."""</p>
<p>    def __init__(self,result,transform_ok):<br />
        if hasattr(result,'close'):<br />
            self.close = result.close<br />
        self._next = iter(result).next<br />
        self.transform_ok = transform_ok</p>
<p>    def __iter__(self):<br />
        return self</p>
<p>    def next(self):<br />
        if self.transform_ok:<br />
            return piglatin(self._next())<br />
        else:<br />
            return self._next()</p>
<p>class Latinator:</p>
<p>    # by default, don't transform output<br />
    transform = False</p>
<p>    def __init__(self, application):<br />
        self.application = application</p>
<p>    def __call__(environ, start_response):</p>
<p>        transform_ok = []</p>
<p>        def start_latin(status,response_headers,exc_info=None):</p>
<p>            # Reset ok flag, in case this is a repeat call<br />
            transform_ok[:]=[]</p>
<p>            for name,value in response_headers:<br />
                if name.lower()=='content-type' and value=='text/plain':<br />
                    transform_ok.append(True)<br />
                    # Strip content-length if present, else it'll be wrong<br />
                    response_headers = [(name,value)<br />
                        for name,value in response_headers<br />
                            if name.lower()<>&#8216;content-length&#8217;<br />
                    ]<br />
                    break</p>
<p>            write = start_response(status,response_headers,exc_info)</p>
<p>            if transform_ok:<br />
                def write_latin(data):<br />
                    write(piglatin(data))<br />
                return write_latin<br />
            else:<br />
                return write</p>
<p>        return LatinIter(self.application(environ,start_latin),transform_ok)</p>
<p># Run foo_app under a Latinator&#8217;s control, using the example CGI gateway<br />
from foo_app import foo_app<br />
run_with_cgi(Latinator(foo_app))<br />
详细说明</p>
<p>应用程序对象必须接受两个参数，为了方便说明我们不妨分别命名为 environ 和 start_response ，但并非必须取这个名字。服务器或gateway必须用这两个参数请求应用程序对象(比如象上面展示的,这样调用 result = application(environ,start_response) )</p>
<p>参数 environ 是个字典对象，包含CGI风格的环境变量。这个对象必须是一个python内建的字典对象(不能是子类、UserDict或其他对字典对象的模仿)，应用程序可以以任何他愿意的方式修改这个字典， environ 还应该包含一些特定的WSGI需要的变量(在后面的节里会描述)，有可以包含一些服务器特定的扩展变量，通过下面提高的约定命名。</p>
<p>start_response 参数是一个接受两个必须参数和一个可选参数的可调用者。方便说明，我们分别把他们命名为 status,  response_headers ,和 exc_info 。应用程序必须用这些参数来请求可调用者 start_response (比如象这样 start_response(status,response_headers) )</p>
<p>参数 status 是一个形式象”999 Message here”的状态字符串。而 response_headers 参数是元组(header_name,header_value)的列表,描述http响应头。可选的 exc_info 参数会在下面的 `The start_response() Callable`_ 和 Error Handling 两节中描述，他只有在应用程序产生了错误并希望在浏览器上显示错误的时候才有用。</p>
<p>start_response 可调用者必须返回一个 write(body_data) 可调用者，他接受一个可选参数：一个将要被做为http响应体的一部分输出的字符串(注意：提供可调用者 write() 只是为了支持现有框架的必要的输出API，新的应用程序或框架尽量避免使用，详细情况请看 Buffering and Streaming 一节。)</p>
<p>当被服务器请求的时候，应用程序对象必须返回一个0或多个可迭代的字符串，这可以通过多种方法完成，比如返回一个字符串的列表，或者应用程序本身是一个生产字符串的函数，或者应用程序是一个类而他的实例是可迭代的，不管怎么完成，应用程序对象必须总是返回0或多个可迭代的字符串。</p>
<p>服务器必须将产生的字符串以一种无缓冲的方式传送到客户端，每次传完一个字符串再去获取下一个。(换句话说，应用程序应该实现自己的缓冲，更多关于应用程序输出必须如何处理的细节请阅读下面的 Buffering and Streaming 节。)</p>
<p>服务器或gateway应该把产生的字符串当字节流对待：特别地，他必须保证没修改行的结尾。应用程序负责确保字符串是以与客户端匹配的编码输出(服务器/gateway可能会附加HTTP传送编码，或者为了实现一些http的特性而进行一些转换比如byte-range transmission，更多细节请看下面的 Other HTTP Features )</p>
<p>如果调 len(iterable) 成功，服务器将认为结果是正确的。也就是说，应用程序返回的可迭代的字符串提供了一个有用 的__len__() 方法，么肯定返回了正确的结果(关于这个方法正常情况下如何被使用的请阅读 Handling the Content-Length Header )</p>
<p>如果应用程序返回的可迭代者有close()方法，则不管该请求是正常结束还是由于错误而终止，服务器/gateway都**必须**在结束该请求之前调用这个方法，（这是用来支持应用程序对资源的释放，This protocol is intended to complement PEP 325&#8242;s generator support, and other common iterables with close() methods.）</p>
<p>（注意：应用程序必须在可迭代者产生第一个字符串之间请求 start_response() 可调用者，这样服务器才能在发送任何主体内容之前发送响应头，然而这一步也可以在可迭代者第一次迭代的时候执行,所以服务器不能假定开始迭代之前 start_response() 已经被调用过了）</p>
<p>最后，服务器或gateway不能应用程序返回的可迭代者的任何其他属性，除非是针对服务器或gateway特定类型的实例，比如wsgi.file_wrapper返回的“file wrapper”（阅读 Optional Platform-Specific File Handling )。通常情况下，只有在这里指定的属性，或者通过PEP 234 iteration APIs才是可以访问的。</p>
<p>environ 变量</p>
<p>environ 字典被用来包含这些在Common Gateway Interface specification [2]_中定义了的CGI环境变量。 下面这些变量 必须 呈现出来, 除非其值是空字符串,这种情况下如果下面没有特别指出的话他们 可能 会被忽略</p>
<p>REQUEST_METHOD<br />
HTTP请求的方式, 比如 “GET” 或者 “POST”. 这个不可能是空字符串并且也是必须给出的。<br />
SCRIPT_NAME<br />
请求URL中路径的开始部分，对应应用程序对象，这样应用程序就知道它的虚拟位置。 如果该应用程序对应服务器的 根 的话， 它 可能 是为空字符串。<br />
PATH_INFO<br />
请求URL中路径的剩余部分，指定请求的目标在应用程序内部的虚拟位置。 如果请求的目标是应用程序跟并且没有trailing slash的话，可能为空字符串 。<br />
QUERY_STRING<br />
请求URL中跟在”?”后面的那部分,可能为空或不存在.<br />
CONTENT_TYPE<br />
HTTP请求中任何 Content-Type 域的内容。<br />
CONTENT_LENGTH<br />
HTTP请求中任何 Content-Length 域的内容。 可能为空或不存在.<br />
SERVER_NAME, SERVER_PORT<br />
这些变量可以和 SCRIPT_NAME、PATH_INFO 一起组成完整的URL。 然而要注意的是，重建请求URL的时候应该优先使用 HTTP_HOST 而非 SERVER_NAME 。 详细内容请阅读下面的 URL Reconstruction 。 SERVER_NAME 和 SERVER_PORT 永远 是空字符串，也总是必须存在的。<br />
SERVER_PROTOCOL<br />
客户端发送请求所使用协议的版本。通常是类似 “HTTP/1.0&#8243; 或 “HTTP/1.1&#8243; 的东西 可以被用来判断如何处理请求headers。(既然这个变量表示的是请求中使用的协议，而且和服 务器响应时使用的协议无关，也许它应该被叫做 REQUEST_PROTOCOL 。然后，为了保持和 CGI的兼容性，我们还是使用已有的名字。)<br />
HTTP_ 变量<br />
对应客户端提供的HTTP请求headers (也就是说名字以 “HTTP_” 开头的变量)。这些变量的 存在与否应该和请求中的合适的HTTP header一致。<br />
服务器或gateway 应该 尽可能提供其他可用的CGI变量。另外，如果用了SSL，服务器或 gateway也 应该 尽可能提供可用的Apache SSL环境变量 [5] ，比如 HTTPS=on 和 SSL_PROTOCOL“。不过要注意，使用了任何上面没有列出的变量的应用程序对不支持相关扩展 的服务器来说就有点necessarily non-portable。(比如，不发布文件的web服务器就不能提供一 个有意义的 “DOCUMENT_ROOT 或 PATH_TRANSLATED 。)</p>
<p>一个支持WSGI的服务器或gateway 应该 在描述它们自己的同时说明它们可以提供些什么变量 应用程序 应该 对所有他们需要的变量的存在性进行检查，并且在某变量不存在的时候有 备用的措施</p>
<p>注意: 不需要的变量 (比如在不需要验证的情况下的 REMOTE_USER ) 应该被移出 environ 字典。同样注意CGI定义的变量如果存在的话必须是字符串。任何 str 类型以外的CGI变量的 存在都是对本规范的违反</p>
<p>除了CGI定义的变量， environ 字典也可以包含任意操作系统的环境变量，并且 必须 包含下面这些WSGI定义的变量:</p>
<p>变量	值<br />
wsgi.version	元组 (1,0), 表明WSGI 版本 1.0.<br />
wsgi.url_scheme	A string representing the “scheme” portion of the URL at which the application is being invoked. Normally, this will have the value “http” or “https”, as appropriate.<br />
wsgi.input	An input stream (file-like object) from which the HTTP request body can be read. (The server or gateway may perform reads on-demand as requested by the application, or it may pre- read the client&#8217;s request body and buffer it in-memory or on disk, or use any other technique for providing such an input stream, according to its preference.)<br />
wsgi.errors<br />
An output stream (file-like object) to which error output can be written, for the purpose of recording program or other errors in a standardized and possibly centralized location. This should be a “text mode” stream; i.e., applications should use “\n” as a line ending, and assume that it will be converted to the correct line ending by the server/gateway.</p>
<p>For many servers, wsgi.errors will be the server&#8217;s main error log. Alternatively, this may be sys.stderr, or a log file of some sort. The server&#8217;s documentation should include an explanation of how to configure this or where to find the recorded output. A server or gateway may supply different error streams to different applications, if this is desired.<br />
wsgi.multithread	This value should evaluate true if the application object may be simultaneously invoked by another thread in the same process, and should evaluate false otherwise.<br />
wsgi.multiprocess	This value should evaluate true if an equivalent application object may be simultaneously invoked by another process, and should evaluate false otherwise.<br />
wsgi.run_once	This value should evaluate true if the server or gateway expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a gateway based on CGI (or something similar).<br />
最后 environ 字典也可以包含服务器定义的变量。这些变量的名字必须是小写字母、数字、点和下划线， 并且应该带一个能唯一代表服务器或gateway的前缀。比如， mod_python 可能会定义象这样的一些变量: mod_python.some_variable.</p>
<p>输入和错误流</p>
<p>服务器提供的输入和错误流必须提供以下方法:</p>
<p>方法	流	注解<br />
read(size)	input	1<br />
readline()	input	1,2<br />
readlines(hint)	input	1,3<br />
__iter__()	input<br />
flush()	errors	4<br />
write(str)	errors<br />
writelines(seq)	errors<br />
每个方法的语义如果上面没有特别指出均和Python Library Reference记载的一样:</p>
<p>The server is not required to read past the client&#8217;s specified Content-Length, and is allowed to simulate an end-of-file condition if the application attempts to read past that point. The application should not attempt to read more data than is specified by the CONTENT_LENGTH variable.<br />
The optional “size” argument to readline() is not supported, as it may be complex for server authors to implement, and is not often used in practice.<br />
Note that the hint argument to readlines() is optional for both caller and implementer. The application is free not to supply it, and the server or gateway is free to ignore it.<br />
Since the errors stream may not be rewound, servers and gateways are free to forward write operations immediately, without buffering. In this case, the flush() method may be a no-op. Portable applications, however, cannot assume that output is unbuffered or that flush() is a no-op. They must call flush() if they need to ensure that output has in fact been written. (For example, to minimize intermingling of data from multiple processes writing to the same error log.)<br />
The methods listed in the table above must be supported by all servers conforming to this specification. Applications conforming to this specification must not use any other methods or attributes of the input or errors objects. In particular, applications must not attempt to close these streams, even if they possess close() methods.</p>
<p>start_response() 可调用者</p>
<p>传给应用程序对象的第二个参数是一个形为 start_response(status,response_headers,exc_info=None) 的可调用者. (As with all WSGI callables, the arguments must be supplied positionally, not by keyword.)  start_response 可调用者是用来开始HTTP响应，它必须返回一个 write(body_data) 可调用者 (阅读下面的 Buffering and Streaming).</p>
<p>status“参数是一个HTTP “status” 字符串，比如 “”200 OK” 或 “404 Not Found”. 也就是说，他是一个由状态编号和具体信息组成的字符串，按这个顺序并用空格隔开，两头没有其他空格和其他字符。 (更多信息请阅读RFC 2616, Section 6.1.1) 该字符串 禁止 包含控制字符，也不允许以回车、换行或他们的 组合结束。</p>
<p>response_headers“参数是一个 “(header_name,header_value) 元组的列表。它必须是一个Python列表； 也就是说 type(response_headers) is ListType,并且服务器 可以 以任何方式改变其内容。 每一个 header_name 必须是一个没有冒号或其他标点符号的合法的HTTP header字段名 (在RFC 2616, Section 4.2中有详细定义).</p>
<p>每一个 header_value 禁止 包含 任何 控制字符,包括回车或换行。 (这些要求是要使得那些必须检查或修改响应头的服务器、gateway、响应处理中间件所必须执行的解析工作的 复杂性降到最低。)</p>
<p>In general, the server or gateway is responsible for ensuring that correct headers are sent to the client: if the application omits a header required by HTTP (or other relevant specifications that are in effect), the server or gateway must add it. For example, the HTTP Date: and Server: headers would normally be supplied by the server or gateway.</p>
<p>(A reminder for server/gateway authors: HTTP header names are case-insensitive, so be sure to take that into consideration when examining application-supplied headers!)</p>
<p>Applications and middleware are forbidden from using HTTP/1.1 “hop-by-hop” features or headers, any equivalent features in HTTP/1.0, or any headers that would affect the persistence of the client&#8217;s connection to the web server. These features are the exclusive province of the actual web server, and a server or gateway should consider it a fatal error for an application to attempt sending them, and raise an error if they are supplied to start_response(). (For more specifics on “hop-by-hop” features and headers, please see the Other HTTP Features section below.)</p>
<p>The start_response callable must not actually transmit the response headers. Instead, it must store them for the server or gateway to transmit only after the first iteration of the application return value that yields a non-empty string, or upon the application&#8217;s first invocation of the write() callable. In other words, response headers must not be sent until there is actual body data available, or until the application&#8217;s returned iterable is exhausted. (The only possible exception to this rule is if the response headers explicitly include a Content-Length of zero.)</p>
<p>This delaying of response header transmission is to ensure that buffered and asynchronous applications can replace their originally intended output with error output, up until the last possible moment. For example, the application may need to change the response status from “200 OK” to “500 Internal Error”, if an error occurs while the body is being generated within an application buffer.</p>
<p>The exc_info argument, if supplied, must be a Python sys.exc_info() tuple. This argument should be supplied by the application only if start_response is being called by an error handler. If exc_info is supplied, and no HTTP headers have been output yet, start_response should replace the currently-stored HTTP response headers with the newly-supplied ones, thus allowing the application to “change its mind” about the output when an error has occurred.</p>
<p>However, if exc_info is provided, and the HTTP headers have already been sent, start_response must raise an error, and should raise the exc_info tuple. That is:</p>
<p>raise exc_info[0],exc_info[1],exc_info[2]<br />
This will re-raise the exception trapped by the application, and in principle should abort the application. (It is not safe for the application to attempt error output to the browser once the HTTP headers have already been sent.) The application must not trap any exceptions raised by start_response, if it called start_response with exc_info. Instead, it should allow such exceptions to propagate back to the server or gateway. See Error Handling below, for more details.</p>
<p>The application may call start_response more than once, if and only if the exc_info argument is provided. More precisely, it is a fatal error to call start_response without the exc_info argument if start_response has already been called within the current invocation of the application. (See the example CGI gateway above for an illustration of the correct logic.)</p>
<p>Note: servers, gateways, or middleware implementing start_response should ensure that no reference is held to the exc_info parameter beyond the duration of the function&#8217;s execution, to avoid creating a circular reference through the traceback and frames involved. The simplest way to do this is something like:</p>
<p>def start_response(status,response_headers,exc_info=None):<br />
    if exc_info:<br />
         try:<br />
             # do stuff w/exc_info here<br />
         finally:<br />
             exc_info = None    # Avoid circular ref.<br />
The example CGI gateway provides another illustration of this technique.</p>
<p>Handling the Content-Length Header</p>
<p>If the application does not supply a Content-Length header, a server or gateway may choose one of several approaches to handling it. The simplest of these is to close the client connection when the response is completed.</p>
<p>Under some circumstances, however, the server or gateway may be able to either generate a Content-Length header, or at least avoid the need to close the client connection. If the application does not call the write() callable, and returns an iterable whose len() is 1, then the server can automatically determine Content-Length by taking the length of the first string yielded by the iterable.</p>
<p>And, if the server and client both support HTTP/1.1 “chunked encoding” [3], then the server may use chunked encoding to send a chunk for each write() call or string yielded by the iterable, thus generating a Content-Length header for each chunk. This allows the server to keep the client connection alive, if it wishes to do so. Note that the server must comply fully with RFC 2616 when doing this, or else fall back to one of the other strategies for dealing with the absence of Content-Length.</p>
<p>(Note: applications and middleware must not apply any kind of Transfer-Encoding to their output, such as chunking or gzipping; as “hop-by-hop” operations, these encodings are the province of the actual web server/gateway. See Other HTTP Features below, for more details.)</p>
<p>Buffering and Streaming</p>
<p>Generally speaking, applications will achieve the best throughput by buffering their (modestly-sized) output and sending it all at once. This is a common approach in existing frameworks such as Zope: the output is buffered in a StringIO or similar object, then transmitted all at once, along with the response headers.</p>
<p>The corresponding approach in WSGI is for the application to simply return a single-element iterable (such as a list) containing the response body as a single string. This is the recommended approach for the vast majority of application functions, that render HTML pages whose text easily fits in memory.</p>
<p>For large files, however, or for specialized uses of HTTP streaming (such as multipart “server push”), an application may need to provide output in smaller blocks (e.g. to avoid loading a large file into memory). It&#8217;s also sometimes the case that part of a response may be time-consuming to produce, but it would be useful to send ahead the portion of the response that precedes it.</p>
<p>In these cases, applications will usually return an iterator (often a generator-iterator) that produces the output in a block-by-block fashion. These blocks may be broken to coincide with mulitpart boundaries (for “server push”), or just before time-consuming tasks (such as reading another block of an on-disk file).</p>
<p>WSGI servers, gateways, and middleware must not delay the transmission of any block; they must either fully transmit the block to the client, or guarantee that they will continue transmission even while the application is producing its next block. A server/gateway or middleware may provide this guarantee in one of three ways:</p>
<p>Send the entire block to the operating system (and request that any O/S buffers be flushed) before returning control to the application, OR<br />
Use a different thread to ensure that the block continues to be transmitted while the application produces the next block.<br />
(Middleware only) send the entire block to its parent gateway/server<br />
By providing this guarantee, WSGI allows applications to ensure that transmission will not become stalled at an arbitrary point in their output data. This is critical for proper functioning of e.g. multipart “server push” streaming, where data between multipart boundaries should be transmitted in full to the client.</p>
<p>Middleware Handling of Block Boundaries</p>
<p>In order to better support asynchronous applications and servers, middleware components must not block iteration waiting for multiple values from an application iterable. If the middleware needs to accumulate more data from the application before it can produce any output, it must yield an empty string.</p>
<p>To put this requirement another way, a middleware component must yield at least one value each time its underlying application yields a value. If the middleware cannot yield any other value, it must yield an empty string.</p>
<p>This requirement ensures that asynchronous applications and servers can conspire to reduce the number of threads that are required to run a given number of application instances simultaneously.</p>
<p>Note also that this requirement means that middleware must return an iterable as soon as its underlying application returns an iterable. It is also forbidden for middleware to use the write() callable to transmit data that is yielded by an underlying application. Middleware may only use their parent server&#8217;s write() callable to transmit data that the underlying application sent using a middleware-provided write() callable.</p>
<p>The write() Callable</p>
<p>Some existing application framework APIs support unbuffered output in a different manner than WSGI. Specifically, they provide a “write” function or method of some kind to write an unbuffered block of data, or else they provide a buffered “write” function and a “flush” mechanism to flush the buffer.</p>
<p>Unfortunately, such APIs cannot be implemented in terms of WSGI&#8217;s “iterable” application return value, unless threads or other special mechanisms are used.</p>
<p>Therefore, to allow these frameworks to continue using an imperative API, WSGI includes a special write() callable, returned by the start_response callable.</p>
<p>New WSGI applications and frameworks should not use the write() callable if it is possible to avoid doing so. The write() callable is strictly a hack to support imperative streaming APIs. In general, applications should produce their output via their returned iterable, as this makes it possible for web servers to interleave other tasks in the same Python thread, potentially providing better throughput for the server as a whole.</p>
<p>The write() callable is returned by the start_response() callable, and it accepts a single parameter: a string to be written as part of the HTTP response body, that is treated exactly as though it had been yielded by the output iterable. In other words, before write() returns, it must guarantee that the passed-in string was either completely sent to the client, or that it is buffered for transmission while the application proceeds onward.</p>
<p>An application must return an iterable object, even if it uses write() to produce all or part of its response body. The returned iterable may be empty (i.e. yield no non-empty strings), but if it does yield non-empty strings, that output must be treated normally by the server or gateway (i.e., it must be sent or queued immediately). Applications must not invoke write() from within their return iterable, and therefore any strings yielded by the iterable are transmitted after all strings passed to write() have been sent to the client.</p>
<p>Unicode Issues</p>
<p>HTTP does not directly support Unicode, and neither does this interface. All encoding/decoding must be handled by the application; all strings passed to or from the server must be standard Python byte strings, not Unicode objects. The result of using a Unicode object where a string object is required, is undefined.</p>
<p>Note also that strings passed to start_response() as a status or as response headers must follow RFC 2616 with respect to encoding. That is, they must either be ISO-8859-1 characters, or use RFC 2047 MIME encoding.</p>
<p>On Python platforms where the str or StringType type is in fact Unicode-based (e.g. Jython, IronPython, Python 3000, etc.), all “strings” referred to in this specification must contain only code points representable in ISO-8859-1 encoding (\u0000 through \u00FF, inclusive). It is a fatal error for an application to supply strings containing any other Unicode character or code point. Similarly, servers and gateways must not supply strings to an application containing any other Unicode characters.</p>
<p>Again, all strings referred to in this specification must be of type str or StringType, and must not be of type unicode or UnicodeType. And, even if a given platform allows for more than 8 bits per character in str/StringType objects, only the lower 8 bits may be used, for any value referred to in this specification as a “string”.</p>
<p>Error Handling</p>
<p>In general, applications should try to trap their own, internal errors, and display a helpful message in the browser. (It is up to the application to decide what “helpful” means in this context.)</p>
<p>However, to display such a message, the application must not have actually sent any data to the browser yet, or else it risks corrupting the response. WSGI therefore provides a mechanism to either allow the application to send its error message, or be automatically aborted: the exc_info argument to start_response. Here is an example of its use:</p>
<p>try:<br />
    # regular application code here<br />
    status = “200 Froody”<br />
    response_headers = [("content-type","text/plain")]<br />
    start_response(status, response_headers)<br />
    return ["normal body goes here"]<br />
except:<br />
    # XXX should trap runtime issues like MemoryError, KeyboardInterrupt<br />
    #     in a separate handler before this bare &#8216;except:&#8217;&#8230;<br />
    status = “500 Oops”<br />
    response_headers = [("content-type","text/plain")]<br />
    start_response(status, response_headers, sys.exc_info())<br />
    return ["error body goes here"]<br />
If no output has been written when an exception occurs, the call to start_response will return normally, and the application will return an error body to be sent to the browser. However, if any output has already been sent to the browser, start_response will reraise the provided exception. This exception should not be trapped by the application, and so the application will abort. The server or gateway can then trap this (fatal) exception and abort the response.</p>
<p>Servers should trap and log any exception that aborts an application or the iteration of its return value. If a partial response has already been written to the browser when an application error occurs, the server or gateway may attempt to add an error message to the output, if the already-sent headers indicate a text/* content type that the server knows how to modify cleanly.</p>
<p>Some middleware may wish to provide additional exception handling services, or intercept and replace application error messages. In such cases, middleware may choose to not re-raise the exc_info supplied to start_response, but instead raise a middleware-specific exception, or simply return without an exception after storing the supplied arguments. This will then cause the application to return its error body iterable (or invoke write()), allowing the middleware to capture and modify the error output. These techniques will work as long as application authors:</p>
<p>Always provide exc_info when beginning an error response<br />
Never trap errors raised by start_response when exc_info is being provided<br />
HTTP 1.1 Expect/Continue</p>
<p>Servers and gateways that implement HTTP 1.1 must provide transparent support for HTTP 1.1&#8242;s “expect/continue” mechanism. This may be done in any of several ways:</p>
<p>Respond to requests containing an Expect: 100-continue request with an immediate “100 Continue” response, and proceed normally.<br />
Proceed with the request normally, but provide the application with a wsgi.input stream that will send the “100 Continue” response if/when the application first attempts to read from the input stream. The read request must then remain blocked until the client responds.<br />
Wait until the client decides that the server does not support expect/continue, and sends the request body on its own. (This is suboptimal, and is not recommended.)<br />
Note that these behavior restrictions do not apply for HTTP 1.0 requests, or for requests that are not directed to an application object. For more information on HTTP 1.1 Expect/Continue, see RFC 2616, sections 8.2.3 and 10.1.1.</p>
<p>Other HTTP Features</p>
<p>In general, servers and gateways should “play dumb” and allow the application complete control over its output. They should only make changes that do not alter the effective semantics of the application&#8217;s response. It is always possible for the application developer to add middleware components to supply additional features, so server/gateway developers should be conservative in their implementation. In a sense, a server should consider itself to be like an HTTP “gateway server”, with the application being an HTTP “origin server”. (See RFC 2616, section 1.3, for the definition of these terms.)</p>
<p>However, because WSGI servers and applications do not communicate via HTTP, what RFC 2616 calls “hop-by-hop” headers do not apply to WSGI internal communications. WSGI applications must not generate any “hop-by-hop” headers [4], attempt to use HTTP features that would require them to generate such headers, or rely on the content of any incoming “hop-by-hop” headers in the environ dictionary. WSGI servers must handle any supported inbound “hop-by-hop” headers on their own, such as by decoding any inbound Transfer-Encoding, including chunked encoding if applicable.</p>
<p>Applying these principles to a variety of HTTP features, it should be clear that a server may handle cache validation via the If-None-Match and If-Modified-Since request headers and the Last-Modified and ETag response headers. However, it is not required to do this, and the application should perform its own cache validation if it wants to support that feature, since the server/gateway is not required to do such validation.</p>
<p>Similarly, a server may re-encode or transport-encode an application&#8217;s response, but the application should use a suitable content encoding on its own, and must not apply a transport encoding. A server may transmit byte ranges of the application&#8217;s response if requested by the client, and the application doesn&#8217;t natively support byte ranges. Again, however, the application should perform this function on its own if desired.</p>
<p>Note that these restrictions on applications do not necessarily mean that every application must reimplement every HTTP feature; many HTTP features can be partially or fully implemented by middleware components, thus freeing both server and application authors from implementing the same features over and over again.</p>
<p>Thread Support</p>
<p>Thread support, or lack thereof, is also server-dependent. Servers that can run multiple requests in parallel, should also provide the option of running an application in a single-threaded fashion, so that applications or frameworks that are not thread-safe may still be used with that server.</p>
<p>Implementation/Application Notes</p>
<p>Server Extension APIs</p>
<p>Some server authors may wish to expose more advanced APIs, that application or framework authors can use for specialized purposes. For example, a gateway based on mod_python might wish to expose part of the Apache API as a WSGI extension.</p>
<p>In the simplest case, this requires nothing more than defining an environ variable, such as mod_python.some_api. But, in many cases, the possible presence of middleware can make this difficult. For example, an API that offers access to the same HTTP headers that are found in environ variables, might return different data if environ has been modified by middleware.</p>
<p>In general, any extension API that duplicates, supplants, or bypasses some portion of WSGI functionality runs the risk of being incompatible with middleware components. Server/gateway developers should not assume that nobody will use middleware, because some framework developers specifically intend to organize or reorganize their frameworks to function almost entirely as middleware of various kinds.</p>
<p>So, to provide maximum compatibility, servers and gateways that provide extension APIs that replace some WSGI functionality, must design those APIs so that they are invoked using the portion of the API that they replace. For example, an extension API to access HTTP request headers must require the application to pass in its current environ, so that the server/gateway may verify that HTTP headers accessible via the API have not been altered by middleware. If the extension API cannot guarantee that it will always agree with environ about the contents of HTTP headers, it must refuse service to the application, e.g. by raising an error, returning None instead of a header collection, or whatever is appropriate to the API.</p>
<p>Similarly, if an extension API provides an alternate means of writing response data or headers, it should require the start_response callable to be passed in, before the application can obtain the extended service. If the object passed in is not the same one that the server/gateway originally supplied to the application, it cannot guarantee correct operation and must refuse to provide the extended service to the application.</p>
<p>These guidelines also apply to middleware that adds information such as parsed cookies, form variables, sessions, and the like to environ. Specifically, such middleware should provide these features as functions which operate on environ, rather than simply stuffing values into environ. This helps ensure that information is calculated from environ after any middleware has done any URL rewrites or other environ modifications.</p>
<p>It is very important that these “safe extension” rules be followed by both server/gateway and middleware developers, in order to avoid a future in which middleware developers are forced to delete any and all extension APIs from environ to ensure that their mediation isn&#8217;t being bypassed by applications using those extensions!</p>
<p>Application Configuration</p>
<p>This specification does not define how a server selects or obtains an application to invoke. These and other configuration options are highly server-specific matters. It is expected that server/gateway authors will document how to configure the server to execute a particular application object, and with what options (such as threading options).</p>
<p>Framework authors, on the other hand, should document how to create an application object that wraps their framework&#8217;s functionality. The user, who has chosen both the server and the application framework, must connect the two together. However, since both the framework and the server now have a common interface, this should be merely a mechanical matter, rather than a significant engineering effort for each new server/framework pair.</p>
<p>Finally, some applications, frameworks, and middleware may wish to use the environ dictionary to receive simple string configuration options. Servers and gateways should support this by allowing an application&#8217;s deployer to specify name-value pairs to be placed in environ. In the simplest case, this support can consist merely of copying all operating system-supplied environment variables from os.environ into the environ dictionary, since the deployer in principle can configure these externally to the server, or in the CGI case they may be able to be set via the server&#8217;s configuration files.</p>
<p>Applications should try to keep such required variables to a minimum, since not all servers will support easy configuration of them. Of course, even in the worst case, persons deploying an application can create a script to supply the necessary configuration values:</p>
<p>from the_app import application</p>
<p>def new_app(environ,start_response):<br />
    environ['the_app.configval1'] = &#8216;something&#8217;<br />
    return application(environ,start_response)<br />
But, most existing applications and frameworks will probably only need a single configuration value from environ, to indicate the location of their application or framework-specific configuration file(s). (Of course, applications should cache such configuration, to avoid having to re-read it upon each invocation.)</p>
<p>URL Reconstruction</p>
<p>If an application wishes to reconstruct a request&#8217;s complete URL, it may do so using the following algorithm, contributed by Ian Bicking:</p>
<p>from urllib import quote<br />
url = environ['wsgi.url_scheme']+&#8217;://&#8217;</p>
<p>if environ.get(&#8216;HTTP_HOST&#8217;):<br />
    url += environ['HTTP_HOST']<br />
else:<br />
    url += environ['SERVER_NAME']</p>
<p>    if environ['wsgi.url_scheme'] == &#8216;https&#8217;:<br />
        if environ['SERVER_PORT'] != &#8217;443&#8242;:<br />
           url += &#8216;:&#8217; + environ['SERVER_PORT']<br />
    else:<br />
        if environ['SERVER_PORT'] != &#8217;80&#8242;:<br />
           url += &#8216;:&#8217; + environ['SERVER_PORT']</p>
<p>url += quote(environ.get(&#8216;SCRIPT_NAME&#8217;,”))<br />
url += quote(environ.get(&#8216;PATH_INFO&#8217;,”))<br />
if environ.get(&#8216;QUERY_STRING&#8217;):<br />
    url += &#8216;?&#8217; + environ['QUERY_STRING']<br />
Note that such a reconstructed URL may not be precisely the same URI as requested by the client. Server rewrite rules, for example, may have modified the client&#8217;s originally requested URL to place it in a canonical form.</p>
<p>Supporting Older (<2.2) Versions of Python</p>
<p>Some servers, gateways, or applications may wish to support older (<2.2) versions of Python. This is especially important if Jython is a target platform, since as of this writing a production-ready version of Jython 2.2 is not yet available.</p>
<p>For servers and gateways, this is relatively straightforward: servers and gateways targeting pre-2.2 versions of Python must simply restrict themselves to using only a standard “for” loop to iterate over any iterable returned by an application. This is the only way to ensure source-level compatibility with both the pre-2.2 iterator protocol (discussed further below) and “today&#8217;s” iterator protocol (see PEP 234).</p>
<p>(Note that this technique necessarily applies only to servers, gateways, or middleware that are written in Python. Discussion of how to use iterator protocol(s) correctly from other languages is outside the scope of this PEP.)</p>
<p>For applications, supporting pre-2.2 versions of Python is slightly more complex:</p>
<p>You may not return a file object and expect it to work as an iterable, since before Python 2.2, files were not iterable. (In general, you shouldn&#8217;t do this anyway, because it will peform quite poorly most of the time!) Use wsgi.file_wrapper or an application-specific file wrapper class. (See Optional Platform-Specific File Handling for more on wsgi.file_wrapper, and an example class you can use to wrap a file as an iterable.)<br />
If you return a custom iterable, it must implement the pre-2.2 iterator protocol. That is, provide a __getitem__ method that accepts an integer key, and raises IndexError when exhausted. (Note that built-in sequence types are also acceptable, since they also implement this protocol.)<br />
Finally, middleware that wishes to support pre-2.2 versions of Python, and iterates over application return values or itself returns an iterable (or both), must follow the appropriate recommendations above.</p>
<p>(Note: It should go without saying that to support pre-2.2 versions of Python, any server, gateway, application, or middleware must also use only language features available in the target version, use 1 and 0 instead of True and False, etc.)</p>
<p>Optional Platform-Specific File Handling</p>
<p>Some operating environments provide special high-performance file- transmission facilities, such as the Unix sendfile() call. Servers and gateways may expose this functionality via an optional wsgi.file_wrapper key in the environ. An application may use this “file wrapper” to convert a file or file-like object into an iterable that it then returns, e.g.:</p>
<p>if &#8216;wsgi.file_wrapper&#8217; in environ:<br />
    return environ['wsgi.file_wrapper'](filelike, block_size)<br />
else:<br />
    return iter(lambda: filelike.read(block_size), ”)<br />
If the server or gateway supplies wsgi.file_wrapper, it must be a callable that accepts one required positional parameter, and one optional positional parameter. The first parameter is the file-like object to be sent, and the second parameter is an optional block size “suggestion” (which the server/gateway need not use). The callable must return an iterable object, and must not perform any data transmission until and unless the server/gateway actually receives the iterable as a return value from the application. (To do otherwise would prevent middleware from being able to interpret or override the response data.)</p>
<p>To be considered “file-like”, the object supplied by the application must have a read() method that takes an optional size argument. It may have a close() method, and if so, the iterable returned by wsgi.file_wrapper must have a close() method that invokes the original file-like object&#8217;s close() method. If the “file-like” object has any other methods or attributes with names matching those of Python built-in file objects (e.g. fileno()), the wsgi.file_wrapper may assume that these methods or attributes have the same semantics as those of a built-in file object.</p>
<p>The actual implementation of any platform-specific file handling must occur after the application returns, and the server or gateway checks to see if a wrapper object was returned. (Again, because of the presence of middleware, error handlers, and the like, it is not guaranteed that any wrapper created will actually be used.)</p>
<p>Apart from the handling of close(), the semantics of returning a file wrapper from the application should be the same as if the application had returned iter(filelike.read, ”). In other words, transmission should begin at the current position within the “file” at the time that transmission begins, and continue until the end is reached.</p>
<p>Of course, platform-specific file transmission APIs don&#8217;t usually accept arbitrary “file-like” objects. Therefore, a wsgi.file_wrapper has to introspect the supplied object for things such as a fileno() (Unix-like OSes) or a java.nio.FileChannel (under Jython) in order to determine if the file-like object is suitable for use with the platform-specific API it supports.</p>
<p>Note that even if the object is not suitable for the platform API, the wsgi.file_wrapper must still return an iterable that wraps read() and close(), so that applications using file wrappers are portable across platforms. Here&#8217;s a simple platform-agnostic file wrapper class, suitable for old (pre 2.2) and new Pythons alike:</p>
<p>class FileWrapper:</p>
<p>    def __init__(self, filelike, blksize=8192):<br />
        self.filelike = filelike<br />
        self.blksize = blksize<br />
        if hasattr(filelike,&#8217;close&#8217;):<br />
            self.close = filelike.close</p>
<p>    def __getitem__(self,key):<br />
        data = self.filelike.read(self.blksize)<br />
        if data:<br />
            return data<br />
        raise IndexError<br />
and here is a snippet from a server/gateway that uses it to provide access to a platform-specific API:</p>
<p>environ['wsgi.file_wrapper'] = FileWrapper<br />
result = application(environ, start_response)</p>
<p>try:<br />
    if isinstance(result,FileWrapper):<br />
        # check if result.filelike is usable w/platform-specific<br />
        # API, and if so, use that API to transmit the result.<br />
        # If not, fall through to normal iterable handling<br />
        # loop below.</p>
<p>    for data in result:<br />
        # etc.</p>
<p>finally:<br />
    if hasattr(result,&#8217;close&#8217;):<br />
        result.close()<br />
Questions and Answers</p>
<p>Why must environ be a dictionary? What&#8217;s wrong with using a subclass?</p>
<p>The rationale for requiring a dictionary is to maximize portability between servers. The alternative would be to define some subset of a dictionary&#8217;s methods as being the standard and portable interface. In practice, however, most servers will probably find a dictionary adequate to their needs, and thus framework authors will come to expect the full set of dictionary features to be available, since they will be there more often than not. But, if some server chooses not to use a dictionary, then there will be interoperability problems despite that server&#8217;s “conformance” to spec. Therefore, making a dictionary mandatory simplifies the specification and guarantees interoperabilty.</p>
<p>Note that this does not prevent server or framework developers from offering specialized services as custom variables inside the environ dictionary. This is the recommended approach for offering any such value-added services.</p>
<p>Why can you call write() and yield strings/return an iterable? Shouldn&#8217;t we pick just one way?</p>
<p>If we supported only the iteration approach, then current frameworks that assume the availability of “push” suffer. But, if we only support pushing via write(), then server performance suffers for transmission of e.g. large files (if a worker thread can&#8217;t begin work on a new request until all of the output has been sent). Thus, this compromise allows an application framework to support both approaches, as appropriate, but with only a little more burden to the server implementor than a push-only approach would require.</p>
<p>What&#8217;s the close() for?</p>
<p>When writes are done during the execution of an application object, the application can ensure that resources are released using a try/finally block. But, if the application returns an iterable, any resources used will not be released until the iterable is garbage collected. The close() idiom allows an application to release critical resources at the end of a request, and it&#8217;s forward-compatible with the support for try/finally in generators that&#8217;s proposed by PEP 325.</p>
<p>Why is this interface so low-level? I want feature X! (e.g. cookies, sessions, persistence, &#8230;)</p>
<p>This isn&#8217;t Yet Another Python Web Framework. It&#8217;s just a way for frameworks to talk to web servers, and vice versa. If you want these features, you need to pick a web framework that provides the features you want. And if that framework lets you create a WSGI application, you should be able to run it in most WSGI-supporting servers. Also, some WSGI servers may offer additional services via objects provided in their environ dictionary; see the applicable server documentation for details. (Of course, applications that use such extensions will not be portable to other WSGI-based servers.)</p>
<p>Why use CGI variables instead of good old HTTP headers? And why mix them in with WSGI-defined variables?</p>
<p>Many existing web frameworks are built heavily upon the CGI spec, and existing web servers know how to generate CGI variables. In contrast, alternative ways of representing inbound HTTP information are fragmented and lack market share. Thus, using the CGI “standard” seems like a good way to leverage existing implementations. As for mixing them with WSGI variables, separating them would just require two dictionary arguments to be passed around, while providing no real benefits.</p>
<p>What about the status string? Can&#8217;t we just use the number, passing in 200 instead of “200 OK”?</p>
<p>Doing this would complicate the server or gateway, by requiring them to have a table of numeric statuses and corresponding messages. By contrast, it is easy for an application or framework author to type the extra text to go with the specific response code they are using, and existing frameworks often already have a table containing the needed messages. So, on balance it seems better to make the application/framework responsible, rather than the server or gateway.</p>
<p>Why is wsgi.run_once not guaranteed to run the app only once?</p>
<p>Because it&#8217;s merely a suggestion to the application that it should “rig for infrequent running”. This is intended for application frameworks that have multiple modes of operation for caching, sessions, and so forth. In a “multiple run” mode, such frameworks may preload caches, and may not write e.g. logs or session data to disk after each request. In “single run” mode, such frameworks avoid preloading and flush all necessary writes after each request.</p>
<p>However, in order to test an application or framework to verify correct operation in the latter mode, it may be necessary (or at least expedient) to invoke it more than once. Therefore, an application should not assume that it will definitely not be run again, just because it is called with wsgi.run_once set to True.</p>
<p>Feature X (dictionaries, callables, etc.) are ugly for use in application code; why don&#8217;t we use objects instead?</p>
<p>All of these implementation choices of WSGI are specifically intended to decouple features from one another; recombining these features into encapsulated objects makes it somewhat harder to write servers or gateways, and an order of magnitude harder to write middleware that replaces or modifies only small portions of the overall functionality.</p>
<p>In essence, middleware wants to have a “Chain of Responsibility” pattern, whereby it can act as a “handler” for some functions, while allowing others to remain unchanged. This is difficult to do with ordinary Python objects, if the interface is to remain extensible. For example, one must use __getattr__ or __getattribute__ overrides, to ensure that extensions (such as attributes defined by future WSGI versions) are passed through.</p>
<p>This type of code is notoriously difficult to get 100% correct, and few people will want to write it themselves. They will therefore copy other people&#8217;s implementations, but fail to update them when the person they copied from corrects yet another corner case.</p>
<p>Further, this necessary boilerplate would be pure excise, a developer tax paid by middleware developers to support a slightly prettier API for application framework developers. But, application framework developers will typically only be updating one framework to support WSGI, and in a very limited part of their framework as a whole. It will likely be their first (and maybe their only) WSGI implementation, and thus they will likely implement with this specification ready to hand. Thus, the effort of making the API “prettier” with object attributes and suchlike would likely be wasted for this audience.</p>
<p>We encourage those who want a prettier (or otherwise improved) WSGI interface for use in direct web application programming (as opposed to web framework development) to develop APIs or frameworks that wrap WSGI for convenient use by application developers. In this way, WSGI can remain conveniently low-level for server and middleware authors, while not being “ugly” for application developers.</p>
<p>Proposed/Under Discussion</p>
<p>These items are currently being discussed on the Web-SIG and elsewhere, or are on the PEP author&#8217;s “to-do” list:</p>
<p>Should wsgi.input be an iterator instead of a file? This would help for asynchronous applications and chunked-encoding input streams.<br />
Optional extensions are being discussed for pausing iteration of an application&#8217;s ouptut until input is available or until a callback occurs.<br />
Add a section about synchronous vs. asynchronous apps and servers, the relevant threading models, and issues/design goals in these areas.<br />
Acknowledgements</p>
<p>Thanks go to the many folks on the Web-SIG mailing list whose thoughtful feedback made this revised draft possible. Especially:</p>
<p>Gregory “Grisha” Trubetskoy, author of mod_python, who beat up on the first draft as not offering any advantages over “plain old CGI”, thus encouraging me to look for a better approach.<br />
Ian Bicking, who helped nag me into properly specifying the multithreading and multiprocess options, as well as badgering me to provide a mechanism for servers to supply custom extension data to an application.<br />
Tony Lownds, who came up with the concept of a start_response function that took the status and headers, returning a write function. His input also guided the design of the exception handling facilities, especially in the area of allowing for middleware that overrides application error messages.<br />
Alan Kennedy, whose courageous attempts to implement WSGI-on-Jython (well before the spec was finalized) helped to shape the “supporting older versions of Python” section, as well as the optional wsgi.file_wrapper facility.<br />
Mark Nottingham, who reviewed the spec extensively for issues with HTTP RFC compliance, especially with regard to HTTP/1.1 features that I didn&#8217;t even know existed until he pointed them out.<br />
References</p>
<p>[1]	The Python Wiki “Web Programming” topic (http://www.python.org/cgi-bin/moinmoin/WebProgramming)<br />
[2]	The Common Gateway Interface Specification, v 1.1, 3rd Draft (http://cgi-spec.golux.com/draft-coar-cgi-v11-03.txt)<br />
[3]	“Chunked Transfer Coding” &#8212; HTTP/1.1, section 3.6.1 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1)<br />
[4]	“End-to-end and Hop-by-hop Headers” &#8212; HTTP/1.1, Section 13.5.1 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1)<br />
[5]	mod_ssl Reference, “Environment Variables” (http://www.modssl.org/docs/2.8/ssl_reference.html#ToC25)<br />
Copyright</p>
<p>This document has been placed in the public domain.</p>
<p>Docutils System Messages</p>
<p>System Message: ERROR/3 (pep-0333_cn_temp.txt, line 259); backlink</p>
<p>Unknown target name: “the start_response() callable”.</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python和其他语言数据类型比较" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2009%2F03%2F16%2Fpython-and-programming%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python和其他语言数据类型比较</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Httpsqs Python Client" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Httpsqs Python Client</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python Queue 的多线程(multi thread)死锁问题" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F11%2F23%2Fpython-web-server-gateway-interface-v1-0-1%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python Queue 的多线程(multi thread)死锁问题</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/11/23/python-web-server-gateway-interface-v1-0-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>使用supervisor和nginx发布tornado程序</title>
		<link>http://fendou.org/2011/09/23/supervisor-nginx-tornado/</link>
		<comments>http://fendou.org/2011/09/23/supervisor-nginx-tornado/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 02:16:43 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Excellence Article]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=850</guid>
		<description><![CDATA[tornado先天对异步(no-bolocking)处理能力，非常适合作为Web服务。tornado在linux平台使用epoll来实现异步事件的处理，性能非常好。但是python做为一个脚步语言，单进程执行，无法利用多CPU，对当今的多核CPU是一个很大的浪费。为提高性能，提高CPU利用率，一般会将tornado程序允许cup*n个。 怎样才能放便启动多个tornado程序呢，我们可以用supervisor来管理多个tornado应用。supervisor安装非常方便，easy_install supervisord就可以。 以下是supervisor的配置，我在一台服务器上配置了四个tornado服务。 config ; supervisor. [group:gisapp] programs=gis-8001,gis-8002,gis-8003,gis-8004 [program:gis-8001] command=python /home/gis/gis/gisserver.py &#8211;port=8001 directory=/home/gis/gis/ autorestart=true redirect_stderr=true stdout_logfile=/home/gis/gis/logs/gis_server-8001.log stdout_logfile_maxbytes=500MB stdout_logfile_backups=50 stdout_capture_maxbytes=1MB stdout_events_enabled=false loglevel=warn [program:gis-8002] command=python /home/gis/gis/gisserver.py &#8211;port=8002 directory=/home/gis/gis/ autorestart=true redirect_stderr=true stdout_logfile=/home/gis/gis/gis_server-8002.log stdout_logfile_maxbytes=500MB stdout_logfile_backups=50 stdout_capture_maxbytes=1MB stdout_events_enabled=false loglevel=warn [program:gis-8003] command=python /home/gis/gis/gisserver.py &#8211;port=8003 directory=/home/gis/gis/ autorestart=true redirect_stderr=true stdout_logfile=/home/gis/gis/gis_server-8003.log stdout_logfile_maxbytes=500MB stdout_logfile_backups=50 stdout_capture_maxbytes=1MB stdout_events_enabled=false loglevel=warn [program:gis-8004] command=python /home/gis/gis/gisserver.py &#8211;port=8004 directory=/home/gis/gis/ autorestart=true redirect_stderr=true...  <a href="http://fendou.org/2011/09/23/supervisor-nginx-tornado/" class="more-link" title="Read 使用supervisor和nginx发布tornado程序">Read more &#187;</a><table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python 批量生成缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python 批量生成缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python中给urllib2设置超时时间" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="python满足你需要的50个模块" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">python满足你需要的50个模块</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>tornado先天对异步(no-bolocking)处理能力，非常适合作为Web服务。tornado在linux平台使用epoll来实现异步事件的处理，性能非常好。但是python做为一个脚步语言，单进程执行，无法利用多CPU，对当今的多核CPU是一个很大的浪费。为提高性能，提高CPU利用率，一般会将tornado程序允许cup*n个。<br />
怎样才能放便启动多个tornado程序呢，我们可以用supervisor来管理多个tornado应用。supervisor安装非常方便，easy_install supervisord就可以。<br />
以下是supervisor的配置，我在一台服务器上配置了四个tornado服务。</p>
<p>config</p>
<p>; supervisor.<br />
[group:gisapp]<br />
programs=gis-8001,gis-8002,gis-8003,gis-8004</p>
<p>[program:gis-8001]<br />
command=python /home/gis/gis/gisserver.py &#8211;port=8001<br />
directory=/home/gis/gis/<br />
autorestart=true<br />
redirect_stderr=true<br />
stdout_logfile=/home/gis/gis/logs/gis_server-8001.log<br />
stdout_logfile_maxbytes=500MB<br />
stdout_logfile_backups=50<br />
stdout_capture_maxbytes=1MB<br />
stdout_events_enabled=false<br />
loglevel=warn</p>
<p>[program:gis-8002]<br />
command=python /home/gis/gis/gisserver.py &#8211;port=8002<br />
directory=/home/gis/gis/<br />
autorestart=true<br />
redirect_stderr=true<br />
stdout_logfile=/home/gis/gis/gis_server-8002.log<br />
stdout_logfile_maxbytes=500MB<br />
stdout_logfile_backups=50<br />
stdout_capture_maxbytes=1MB<br />
stdout_events_enabled=false<br />
loglevel=warn<br />
[program:gis-8003]<br />
command=python /home/gis/gis/gisserver.py &#8211;port=8003<br />
directory=/home/gis/gis/<br />
autorestart=true<br />
redirect_stderr=true<br />
stdout_logfile=/home/gis/gis/gis_server-8003.log<br />
stdout_logfile_maxbytes=500MB<br />
stdout_logfile_backups=50<br />
stdout_capture_maxbytes=1MB<br />
stdout_events_enabled=false<br />
loglevel=warn<br />
[program:gis-8004]<br />
command=python /home/gis/gis/gisserver.py &#8211;port=8004<br />
directory=/home/gis/gis/<br />
autorestart=true<br />
redirect_stderr=true<br />
stdout_logfile=/home/gis/gis/gis_server-8004.log<br />
stdout_logfile_maxbytes=500MB<br />
stdout_logfile_backups=50<br />
stdout_capture_maxbytes=1MB<br />
stdout_events_enabled=false<br />
loglevel=warn<br />
怎么让四个端口同时提供服务呢？可以使用web服务神器nginx,nginx自带了负载平衡功能，<br />
可以让这4个服务同时提供服务。</p>
<p>nginx config</p>
<p>    upstream gisserver{<br />
            server 127.0.0.1:8001;<br />
            server 127.0.0.1:8002;<br />
            server 127.0.0.1:8003;<br />
            server 127.0.0.1:8004;<br />
    }<br />
location /tile/ {<br />
    proxy_pass        http://gisserver;<br />
    proxy_set_header  X-Real-IP  $remote_addr;<br />
    proxy_pass_header Set-Cookie;<br />
}<br />
更新：</p>
<p>上述配置可以精简，supervisord配置可以使用变量表示</p>
<p>; supervisor.<br />
[group:gisapp]<br />
programs=gis-web</p>
<p>[program:gis-web]<br />
command=python /home/gis/gis/gisserver.py &#8211;port=80%(process_num)02d<br />
directory=/home/gis/gis/<br />
autorestart=true<br />
redirect_stderr=true<br />
stdout_logfile=/home/gis/gis/logs/gis_server-80%(process_num)02d.log<br />
stdout_logfile_maxbytes=500MB<br />
stdout_logfile_backups=50<br />
stdout_capture_maxbytes=1MB<br />
stdout_events_enabled=false<br />
loglevel=warn<br />
numprocs-4<br />
numprocs_start=1<br />
对不同的服务器，之需要调整numprocs值就可以。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python 批量生成缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python 批量生成缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python中给urllib2设置超时时间" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="python满足你需要的50个模块" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F09%2F23%2Fsupervisor-nginx-tornado%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">python满足你需要的50个模块</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/09/23/supervisor-nginx-tornado/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python Web.py框架实现的简易REST服务原型</title>
		<link>http://fendou.org/2011/02/15/web-py-restful-service/</link>
		<comments>http://fendou.org/2011/02/15/web-py-restful-service/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 02:04:10 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=807</guid>
		<description><![CDATA[Web.py是python web框架中比较轻量级的，只实现了一些必要的组件，个人比较喜欢这样的框架，虽然功能并不完整，在我所做过的项目中，实际上并没有一款框架能够适合，或许是因为电子商务领域特殊性，也或许是因为公司太大，依赖的东西更多，直接导致了任何一款框架拿过来，写着写着就需要动框架本身的东西，不动它就实现不了业务，由于这个原因，我更偏爱简洁、轻量的框架，修改起来方便，至于组件，既然别的框架已经实现了，拿来改改就能用上了。当然，如果只是普通的CMS之类的开发，没有很多复杂的业务，我更推荐各位使用功能丰富，大而全的框架，比如Rails，比如Django，或者PHP里的很多类似的框架，可以省不少时间，至少分页类不用自己搞了。在复杂的项目中，这些时间是不能省的，否则会导致日后业务的灾难性后果或者需要更多的时间去修改框架。 废话多了，关于web.py可以参考官方网站，中文的入门文档也很全，写起来非常的简单，基本上不用改什么就可以迁移到Google App Engine上。下面上代码： import web import json from mimerender import mimerender &#160; render_xml = lambda message: '&#60;message&#62;%s&#60;/message&#62;'%message render_json = lambda **args: json.dumps&#40;args&#41; render_html = lambda message: '&#60;html&#62;&#60;body&#62;%s&#60;/body&#62;&#60;/html&#62;'%message render_txt = lambda message: message &#160; urls = &#40; '/(.*)', 'greet' &#41; app = web.application&#40;urls, globals&#40;&#41;&#41; &#160; class greet: @mimerender&#40; default = 'html', html = render_html,...  <a href="http://fendou.org/2011/02/15/web-py-restful-service/" class="more-link" title="Read Python Web.py框架实现的简易REST服务原型">Read more &#187;</a><table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Windows平台安装Python2.6 和 MySQL-Python" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python中给urllib2设置超时时间" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python和其他语言数据类型比较" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2009%2F03%2F16%2Fpython-and-programming%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python和其他语言数据类型比较</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>Web.py是python web框架中比较轻量级的，只实现了一些必要的组件，个人比较喜欢这样的框架，虽然功能并不完整，在我所做过的项目中，实际上并没有一款框架能够适合，或许是因为电子商务领域特殊性，也或许是因为公司太大，依赖的东西更多，直接导致了任何一款框架拿过来，写着写着就需要动框架本身的东西，不动它就实现不了业务，由于这个原因，我更偏爱简洁、轻量的框架，修改起来方便，至于组件，既然别的框架已经实现了，拿来改改就能用上了。当然，如果只是普通的CMS之类的开发，没有很多复杂的业务，我更推荐各位使用功能丰富，大而全的框架，比如Rails，比如Django，或者PHP里的很多类似的框架，可以省不少时间，至少分页类不用自己搞了。在复杂的项目中，这些时间是不能省的，否则会导致日后业务的灾难性后果或者需要更多的时间去修改框架。<br />
废话多了，关于<a href="http://webpy.org/">web.py</a>可以参考官方网站，中文的入门文档也很全，写起来非常的简单，基本上不用改什么就可以迁移到Google App Engine上。下面上代码：</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> web
<span style="color: #ff7700;font-weight:bold;">import</span> json
<span style="color: #ff7700;font-weight:bold;">from</span> mimerender <span style="color: #ff7700;font-weight:bold;">import</span> mimerender
&nbsp;
render_xml = <span style="color: #ff7700;font-weight:bold;">lambda</span> message: <span style="color: #483d8b;">'&lt;message&gt;%s&lt;/message&gt;'</span><span style="color: #66cc66;">%</span>message
render_json = <span style="color: #ff7700;font-weight:bold;">lambda</span> <span style="color: #66cc66;">**</span>args: json.<span style="color: black;">dumps</span><span style="color: black;">&#40;</span>args<span style="color: black;">&#41;</span>
render_html = <span style="color: #ff7700;font-weight:bold;">lambda</span> message: <span style="color: #483d8b;">'&lt;html&gt;&lt;body&gt;%s&lt;/body&gt;&lt;/html&gt;'</span><span style="color: #66cc66;">%</span>message
render_txt = <span style="color: #ff7700;font-weight:bold;">lambda</span> message: message
&nbsp;
urls = <span style="color: black;">&#40;</span>
    <span style="color: #483d8b;">'/(.*)'</span>, <span style="color: #483d8b;">'greet'</span>
<span style="color: black;">&#41;</span>
app = web.<span style="color: black;">application</span><span style="color: black;">&#40;</span>urls, <span style="color: #008000;">globals</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> greet:
    @mimerender<span style="color: black;">&#40;</span>
        default = <span style="color: #483d8b;">'html'</span>,
        html = render_html,
        <span style="color: #dc143c;">xml</span>  = render_xml,
        json = render_json,
        txt  = render_txt
    <span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> GET<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> name:
            name = <span style="color: #483d8b;">'world'</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#123;</span><span style="color: #483d8b;">'message'</span>: <span style="color: #483d8b;">'Hello, '</span> + name + <span style="color: #483d8b;">'!'</span><span style="color: black;">&#125;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    app.<span style="color: black;">run</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>最后使用CURL加模拟的header参数的输出是这样的：<br />
<img src="http://pic.yupoo.com/cuimuxi_v/AQJED8nr/I9w6E.jpg" alt="web.py output" /></p>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Windows平台安装Python2.6 和 MySQL-Python" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python中给urllib2设置超时时间" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python和其他语言数据类型比较" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2009%2F03%2F16%2Fpython-and-programming%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F02%2F15%2Fweb-py-restful-service%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python和其他语言数据类型比较</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/02/15/web-py-restful-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python PIL 生成带阴影的缩略图</title>
		<link>http://fendou.org/2011/01/31/python-pil-shadow-thumb/</link>
		<comments>http://fendou.org/2011/01/31/python-pil-shadow-thumb/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 07:10:58 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=802</guid>
		<description><![CDATA[iimport sys from PIL import Image, ImageFilter &#160; def dropShadow&#40; image, offset=&#40;5,5&#41;, background=0xffffff, shadow=0x444444, border=8, iterations=3&#41;: &#34;&#34;&#34; 把图像放在一个作了高斯模糊的背景上 &#160; image - 要放在背景上的原始图像 offset - 阴影相对图像的偏移，用(x,y)表示，可以为正数或者负数 background - 背景色 shadow - 阴影色 border - 图像边框，必须足够用来制作阴影模糊 iterations - 过滤器处理次数，次数越多越模糊，当然处理过程也越慢 &#34;&#34;&#34; &#160; # 创建背景块 totalWidth = image.size&#91;0&#93; + abs&#40;offset&#91;0&#93;&#41; + 2*border totalHeight = image.size&#91;1&#93; + abs&#40;offset&#91;1&#93;&#41; + 2*border...  <a href="http://fendou.org/2011/01/31/python-pil-shadow-thumb/" class="more-link" title="Read Python PIL 生成带阴影的缩略图">Read more &#187;</a><table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python 批量生成缩略图</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">python满足你需要的50个模块</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F19%2Fpython-multi-line-non-greedy-regular-expression-sample%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">python非贪婪、多行匹配正则表达式例子</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[
<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">iimport <span style="color: #dc143c;">sys</span>
<span style="color: #ff7700;font-weight:bold;">from</span> PIL <span style="color: #ff7700;font-weight:bold;">import</span> Image, ImageFilter
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> dropShadow<span style="color: black;">&#40;</span> image, offset=<span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span>,<span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>, background=0xffffff,
        shadow=0x444444, border=<span style="color: #ff4500;">8</span>, iterations=<span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot;
    把图像放在一个作了高斯模糊的背景上
&nbsp;
    image       - 要放在背景上的原始图像
    offset      - 阴影相对图像的偏移，用(x,y)表示，可以为正数或者负数
    background - 背景色
    shadow      - 阴影色
    border      - 图像边框，必须足够用来制作阴影模糊
    iterations - 过滤器处理次数，次数越多越模糊，当然处理过程也越慢
    &quot;&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># 创建背景块</span>
    totalWidth = image.<span style="color: black;">size</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span> + <span style="color: #008000;">abs</span><span style="color: black;">&#40;</span>offset<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span> + <span style="color: #ff4500;">2</span><span style="color: #66cc66;">*</span>border
    totalHeight = image.<span style="color: black;">size</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span> + <span style="color: #008000;">abs</span><span style="color: black;">&#40;</span>offset<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span> + <span style="color: #ff4500;">2</span><span style="color: #66cc66;">*</span>border
    back = Image.<span style="color: #dc143c;">new</span><span style="color: black;">&#40;</span>image.<span style="color: black;">mode</span>, <span style="color: black;">&#40;</span>totalWidth, totalHeight<span style="color: black;">&#41;</span>, background<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># 放置阴影块，考虑图像偏移</span>
    shadowLeft = border + <span style="color: #008000;">max</span><span style="color: black;">&#40;</span>offset<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
    shadowTop = border + <span style="color: #008000;">max</span><span style="color: black;">&#40;</span>offset<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
    back.<span style="color: black;">paste</span><span style="color: black;">&#40;</span>shadow, <span style="color: black;">&#91;</span>shadowLeft, shadowTop, shadowLeft + image.<span style="color: black;">size</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>,
        shadowTop + image.<span style="color: black;">size</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span> <span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># 处理阴影的边缘模糊</span>
    n = <span style="color: #ff4500;">0</span>
    <span style="color: #ff7700;font-weight:bold;">while</span> n <span style="color: #66cc66;">&amp;</span>lt<span style="color: #66cc66;">;</span> iterations:
        back = back.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>ImageFilter.<span style="color: black;">BLUR</span><span style="color: black;">&#41;</span>
        n += <span style="color: #ff4500;">1</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># 把图像粘贴到背景上</span>
    imageLeft = border - <span style="color: #008000;">min</span><span style="color: black;">&#40;</span>offset<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
    imageTop = border - <span style="color: #008000;">min</span><span style="color: black;">&#40;</span>offset<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
    back.<span style="color: black;">paste</span><span style="color: black;">&#40;</span>image, <span style="color: black;">&#40;</span>imageLeft, imageTop<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">return</span> back
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    pic=<span style="color: #483d8b;">&quot;BCEB4D33FC86DC647461670FFC23D260.jpg&quot;</span>
    image = Image.<span style="color: #008000;">open</span><span style="color: black;">&#40;</span>pic<span style="color: black;">&#41;</span>
    image.<span style="color: black;">thumbnail</span><span style="color: black;">&#40;</span> <span style="color: black;">&#40;</span><span style="color: #ff4500;">300</span>,<span style="color: #ff4500;">300</span><span style="color: black;">&#41;</span>, Image.<span style="color: black;">ANTIALIAS</span><span style="color: black;">&#41;</span>
&nbsp;
    dropShadow<span style="color: black;">&#40;</span>image<span style="color: black;">&#41;</span>.<span style="color: black;">show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    dropShadow<span style="color: black;">&#40;</span>image, background=0xeeeeee,
                  shadow=0x444444, offset=<span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>,<span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: black;">show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>生成前的原图：<br />
<img src="http://pic.yupoo.com/cuimuxi_v/AOu9YruG/NCl0D.jpg" alt="生成前的原图" /><br />
生成后的带阴影图：<br />
<img src="http://pic.yupoo.com/cuimuxi_v/AOu9YjyP/pGth5.jpg" alt="生成后带阴影图" /></p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python 批量生成缩略图</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">python满足你需要的50个模块</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F19%2Fpython-multi-line-non-greedy-regular-expression-sample%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">python非贪婪、多行匹配正则表达式例子</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/01/31/python-pil-shadow-thumb/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python 批量生成缩略图</title>
		<link>http://fendou.org/2011/01/31/python-thumb-image/</link>
		<comments>http://fendou.org/2011/01/31/python-thumb-image/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 02:14:33 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=796</guid>
		<description><![CDATA[首先上代码 # coding=utf-8 &#160; import os import Image &#160; # 字义缩放百分比 rate = 40 &#160; # 缩略图命名，在后面加上 resizedAddone = '_resized' &#160; # 支持格式 suportFormat = &#91;'bmp', 'gif', 'jpg', 'png'&#93; &#160; def process&#40;arg, dirs, files&#41;: for file in files: fileExt = os.path.splitext&#40;file&#41;&#91;1&#93;.lower&#40;&#41;&#91;1:&#93; if fileExt in suportFormat: img = Image.open&#40;file&#41; img.thumbnail&#40;&#40;img.size&#91;0&#93; * rate / 100, img.size&#91;1&#93; *...  <a href="http://fendou.org/2011/01/31/python-thumb-image/" class="more-link" title="Read Python 批量生成缩略图">Read more &#187;</a><table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python Queue 的多线程(multi thread)死锁问题" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python Queue 的多线程(multi thread)死锁问题</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Httpsqs Python Client" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Httpsqs Python Client</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="python非贪婪、多行匹配正则表达式例子" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F19%2Fpython-multi-line-non-greedy-regular-expression-sample%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">python非贪婪、多行匹配正则表达式例子</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>首先上代码</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># coding=utf-8</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #ff7700;font-weight:bold;">import</span> Image
&nbsp;
<span style="color: #808080; font-style: italic;"># 字义缩放百分比</span>
rate = <span style="color: #ff4500;">40</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># 缩略图命名，在后面加上</span>
resizedAddone = <span style="color: #483d8b;">'_resized'</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># 支持格式</span>
suportFormat = <span style="color: black;">&#91;</span><span style="color: #483d8b;">'bmp'</span>, <span style="color: #483d8b;">'gif'</span>, <span style="color: #483d8b;">'jpg'</span>, <span style="color: #483d8b;">'png'</span><span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> process<span style="color: black;">&#40;</span>arg, dirs, files<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">for</span> <span style="color: #008000;">file</span> <span style="color: #ff7700;font-weight:bold;">in</span> files:
        fileExt = <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">splitext</span><span style="color: black;">&#40;</span><span style="color: #008000;">file</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>:<span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> fileExt <span style="color: #ff7700;font-weight:bold;">in</span> suportFormat:
            img = Image.<span style="color: #008000;">open</span><span style="color: black;">&#40;</span><span style="color: #008000;">file</span><span style="color: black;">&#41;</span>
            img.<span style="color: black;">thumbnail</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>img.<span style="color: black;">size</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span> <span style="color: #66cc66;">*</span> rate / <span style="color: #ff4500;">100</span>,
                                img.<span style="color: black;">size</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span> <span style="color: #66cc66;">*</span> rate / <span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            img.<span style="color: black;">save</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">basename</span><span style="color: black;">&#40;</span><span style="color: #008000;">file</span><span style="color: black;">&#41;</span>  \
                               + resizedAddone    \
                               + <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>rate<span style="color: black;">&#41;</span> + <span style="color: #483d8b;">'.'</span> + fileExt<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">walk</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'.'</span>, process, <span style="color: #483d8b;">'123'</span><span style="color: black;">&#41;</span></pre></div></div>

<p>要运行此段代码需要安装<a href="http://www.pythonware.com/products/pil/">PIL</a>库，这是一个比较优秀的Python 图像处理库，使用的普及率类似PHP中的GD库，比较成熟和稳定，如果你需要更高的性能，<a href="http://www.imagemagick.org/script/api.php">image magick</a> 是个相当不错的选择，<a href="http://www.imagemagick.org/script/api.php">image magick</a> 的PHP扩展仍然有相当多的Bug，一般应用应该问题不大，至少在我的项目中应用还没出现过问题，我只是简单的应用到了缩略图的功能，仍然建议以命令行的形式调用，python 版本的还没试用过，从各方的使用反馈来看，似乎比PHP版本的口碑更好。</p>
<p>上面的代码是按照比例做缩略图，只需把源码放到你的图片目录下，然后运行就能批量生成缩略图了，如果你是需要固定尺寸的缩略图，只是需要 img.thumbnail()传递一个固定尺寸的tuple就好了，类似这样：img.thumbnail((120,100))，更多详细请查看<a href="http://www.pythonware.com/library/pil/handbook/index.htm">PIL文档</a>，不过这个<a href="http://www.pythonware.com/library/pil/handbook/index.htm">文档</a>相当的长，PDF版本有77页，非常的详细，当然也是因为PIL功能相当的完备和强大</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python Queue 的多线程(multi thread)死锁问题" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python Queue 的多线程(multi thread)死锁问题</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Httpsqs Python Client" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Httpsqs Python Client</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="python非贪婪、多行匹配正则表达式例子" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F19%2Fpython-multi-line-non-greedy-regular-expression-sample%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-thumb-image%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">python非贪婪、多行匹配正则表达式例子</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/01/31/python-thumb-image/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Httpsqs Python Client</title>
		<link>http://fendou.org/2011/01/25/httpsqs-python-client/</link>
		<comments>http://fendou.org/2011/01/25/httpsqs-python-client/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 03:51:05 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=788</guid>
		<description><![CDATA[Httpsqs 是张宴基于Tokyo Cabinet做的一个队列服务 前些日子项目中需要一个队列服务，因为配合Gearman做分发服务，因为之前的一些经历和教训，没有采用PHP作为脚本语言，当然并不是说PHP不行，只是懒得去折腾一些莫名其妙的问题，转而采用在更稳定更省心的Python做开发，之前其他的项目组中有使用Httpsqs的经历，我的leader强烈建议我使用这个，其实我更倾向memcacheQ 或者redis，Httpsqs没有Python版本的client，顺手写了一个，地址如下: http://code.google.com/p/httpsqs/source/browse/#svn%2Ftrunk%2Fclient%2Fpython 这个玩意是能正常的跑在我的项目中，不能保证能完全满足你的需求，如果你有任何建议或者意见，也欢迎联系我，特别附加一句：本人对此代码所带来的一切悲剧或者喜剧不承担任何责任，请慎重使用！ 贴一段关于httpsqs的介绍，怕有些人不知道，知道的请忽略。 TTPSQS（HTTP Simple Queue Service）是一款基于 HTTP GET/POST 协议的轻量级开源简单消息队列服务，使用 Tokyo Cabinet 的 B+Tree Key/Value 数据库来做数据的持久化存储。 　　项目网址：http://code.google.com/p/httpsqs/ 　　使用文档：http://blog.s135.com/httpsqs/ 　　使用环境：Linux（同时支持32位、64位操作系统，推荐使用64位操作系统） 　　软件作者：张宴 　　队列（Queue）又称先进先出表（First In First Out），即先进入队列的元素，先从队列中取出。加入元素的一头叫“队头”，取出元素的一头叫“队尾”。利用消息队列可以很好地异步处理数据传送和存储，当你频繁地向数据库中插入数据、频繁地向搜索引擎提交数据，就可采取消息队列来异步插入。另外，还可以将较慢的处理逻辑、有并发数量限制的处理逻辑，通过消息队列放在后台处理，例如FLV视频转换、发送手机短信、发送电子邮件等。 　　HTTPSQS 具有以下特征： 　　● 非常简单，基于 HTTP GET/POST 协议。PHP、Java、Perl、Shell、Python、Ruby等支持HTTP协议的编程语言均可调用。 　　● 非常快速，入队列、出队列速度超过10000次/秒。 　　● 高并发，支持上万的并发连接，C10K不成问题。 　　● 支持多队列。 　　● 单个队列支持的最大队列数量高达10亿条。 　　● 低内存消耗，海量数据存储，存储几十GB的数据只需不到100MB的物理内存缓冲区。 　　● 可以在不停止服务的情况下便捷地修改单个队列的最大队列数量。 　　● 可以实时查看队列状态（入队列位置、出队列位置、未读队列数量、最大队列数量）。 　　● 可以查看指定队列ID（队列点）的内容，包括未出、已出的队列内容。 　　● 查看队列内容时，支持多字符集编码。 　　●...  <a href="http://fendou.org/2011/01/25/httpsqs-python-client/" class="more-link" title="Read Httpsqs Python Client">Read more &#187;</a><table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Windows平台安装Python2.6 和 MySQL-Python" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="python非贪婪、多行匹配正则表达式例子" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F19%2Fpython-multi-line-non-greedy-regular-expression-sample%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">python非贪婪、多行匹配正则表达式例子</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python Queue 的多线程(multi thread)死锁问题" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python Queue 的多线程(multi thread)死锁问题</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>Httpsqs 是<a href="http://blog.s135.com">张宴</a>基于Tokyo Cabinet做的一个队列服务<br />
前些日子项目中需要一个队列服务，因为配合Gearman做分发服务，因为之前的一些经历和教训，没有采用PHP作为脚本语言，当然并不是说PHP不行，只是懒得去折腾一些莫名其妙的问题，转而采用在更稳定更省心的Python做开发，之前其他的项目组中有使用Httpsqs的经历，我的leader强烈建议我使用这个，其实我更倾向memcacheQ 或者redis，Httpsqs没有Python版本的client，顺手写了一个，地址如下:<br />
<a href="http://code.google.com/p/httpsqs/source/browse/#svn%2Ftrunk%2Fclient%2Fpython">http://code.google.com/p/httpsqs/source/browse/#svn%2Ftrunk%2Fclient%2Fpython</a></p>
<p>这个玩意是能正常的跑在我的项目中，不能保证能完全满足你的需求，如果你有任何建议或者意见，也欢迎<a href="http://fendou.org/contact/">联系我</a>，特别附加一句：本人对此代码所带来的一切悲剧或者喜剧不承担任何责任，请慎重使用！</p>
<p>贴一段关于httpsqs的介绍，怕有些人不知道，知道的请忽略。</p>
<blockquote>
<p>TTPSQS（HTTP Simple Queue Service）是一款基于 HTTP GET/POST 协议的轻量级开源简单消息队列服务，使用 Tokyo Cabinet 的 B+Tree Key/Value 数据库来做数据的持久化存储。</p>
<p>　　项目网址：http://code.google.com/p/httpsqs/<br />
　　使用文档：http://blog.s135.com/httpsqs/<br />
　　使用环境：Linux（同时支持32位、64位操作系统，推荐使用64位操作系统）<br />
　　软件作者：张宴</p>
<p>　　队列（Queue）又称先进先出表（First In First Out），即先进入队列的元素，先从队列中取出。加入元素的一头叫“队头”，取出元素的一头叫“队尾”。利用消息队列可以很好地异步处理数据传送和存储，当你频繁地向数据库中插入数据、频繁地向搜索引擎提交数据，就可采取消息队列来异步插入。另外，还可以将较慢的处理逻辑、有并发数量限制的处理逻辑，通过消息队列放在后台处理，例如FLV视频转换、发送手机短信、发送电子邮件等。</p>
<p>　　HTTPSQS 具有以下特征：</p>
<p>　　● 非常简单，基于 HTTP GET/POST 协议。PHP、Java、Perl、Shell、Python、Ruby等支持HTTP协议的编程语言均可调用。<br />
　　● 非常快速，入队列、出队列速度超过10000次/秒。<br />
　　● 高并发，支持上万的并发连接，C10K不成问题。<br />
　　● 支持多队列。<br />
　　● 单个队列支持的最大队列数量高达10亿条。<br />
　　● 低内存消耗，海量数据存储，存储几十GB的数据只需不到100MB的物理内存缓冲区。<br />
　　● 可以在不停止服务的情况下便捷地修改单个队列的最大队列数量。<br />
　　● 可以实时查看队列状态（入队列位置、出队列位置、未读队列数量、最大队列数量）。<br />
　　● 可以查看指定队列ID（队列点）的内容，包括未出、已出的队列内容。<br />
　　● 查看队列内容时，支持多字符集编码。<br />
　　● 源代码不超过800行，适合二次开发。
</p></blockquote>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Windows平台安装Python2.6 和 MySQL-Python" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="python非贪婪、多行匹配正则表达式例子" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F19%2Fpython-multi-line-non-greedy-regular-expression-sample%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">python非贪婪、多行匹配正则表达式例子</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python Queue 的多线程(multi thread)死锁问题" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python Queue 的多线程(multi thread)死锁问题</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/01/25/httpsqs-python-client/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python Queue 的多线程(multi thread)死锁问题</title>
		<link>http://fendou.org/2011/01/25/python-queue-lock/</link>
		<comments>http://fendou.org/2011/01/25/python-queue-lock/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 01:51:22 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=782</guid>
		<description><![CDATA[废话不多说，先上代码： #encoding=utf-8 import threading import random import time from Queue import Queue import mutex &#160; class Producer&#40;threading.Thread&#41;: &#160; def __init__&#40;self, threadname, queue, lock&#41;: threading.Thread.__init__&#40;self, name = threadname&#41; self.sharedata = queue self.lock = lock &#160; def run&#40;self&#41;: for i in range&#40;20&#41;: #---------------- self.lock.acquire&#40;&#41; print self.getName&#40;&#41;,'&#60;&#60; ',i self.lock.release&#40;&#41; #---------------- self.sharedata.put&#40;i&#41; time.sleep&#40;random.randrange&#40;10&#41;/50.0&#41; #time.sleep(1) print self.getName&#40;&#41;,'Finished' &#160; &#160; #...  <a href="http://fendou.org/2011/01/25/python-queue-lock/" class="more-link" title="Read Python Queue 的多线程(multi thread)死锁问题">Read more &#187;</a><table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Httpsqs Python Client</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python解析iso8601时间格式获得时间戳</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2009%2F03%2F16%2Fpython-and-programming%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python和其他语言数据类型比较</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>废话不多说，先上代码：</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#encoding=utf-8</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">threading</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">random</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">Queue</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">Queue</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">mutex</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Producer<span style="color: black;">&#40;</span><span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, threadname, queue, lock<span style="color: black;">&#41;</span>:
        <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name = threadname<span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">sharedata</span> = queue
        <span style="color: #008000;">self</span>.<span style="color: black;">lock</span> = lock
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> run<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">20</span><span style="color: black;">&#41;</span>:
            <span style="color: #808080; font-style: italic;">#----------------</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">lock</span>.<span style="color: black;">acquire</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">getName</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'&lt;&lt; '</span>,i
            <span style="color: #008000;">self</span>.<span style="color: black;">lock</span>.<span style="color: black;">release</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #808080; font-style: italic;">#----------------</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">sharedata</span>.<span style="color: black;">put</span><span style="color: black;">&#40;</span>i<span style="color: black;">&#41;</span>
            <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">random</span>.<span style="color: black;">randrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>/<span style="color: #ff4500;">50.0</span><span style="color: black;">&#41;</span>
            <span style="color: #808080; font-style: italic;">#time.sleep(1)</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">getName</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'Finished'</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;"># Consumer thread</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Consumer<span style="color: black;">&#40;</span><span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span><span style="color: black;">&#41;</span>:
&nbsp;
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">global</span> lock
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, threadname, queue, lock<span style="color: black;">&#41;</span>:
        <span style="color: #dc143c;">threading</span>.<span style="color: black;">Thread</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name = threadname<span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">sharedata</span> = queue
        <span style="color: #008000;">self</span>.<span style="color: black;">lock</span> = lock
&nbsp;
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> run<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">20</span><span style="color: black;">&#41;</span>:
            <span style="color: #808080; font-style: italic;">#----------------</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">lock</span>.<span style="color: black;">acquire</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">getName</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'        &gt;&gt; '</span>,<span style="color: #008000;">self</span>.<span style="color: black;">sharedata</span>.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">lock</span>.<span style="color: black;">release</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #808080; font-style: italic;">#----------------</span>
            <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">random</span>.<span style="color: black;">randrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>/<span style="color: #ff4500;">50.0</span><span style="color: black;">&#41;</span>
            <span style="color: #808080; font-style: italic;">#time.sleep(1)</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">getName</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'Finished'</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;"># Main thread</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
&nbsp;
    lock = <span style="color: #dc143c;">threading</span>.<span style="color: black;">RLock</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    queue = <span style="color: #dc143c;">Queue</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    producer = Producer<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Producer'</span>, queue, lock<span style="color: black;">&#41;</span>
    consumer = Consumer<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Consumer'</span>, queue, lock<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Starting threads ...'</span>
    producer.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    consumer.<span style="color: black;">start</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    producer.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    consumer.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'All threads have terminated.'</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>这个是在学习多线程的时候入门经典实例之一，这里只是加了个同步锁（RLock）<br />
多次执行这个脚本会发现，大部分时候这个脚本会发生死锁的现象，偶尔却能正确的执行完</p>
<p>这个问题并不是锁本身的问题，是程序的逻辑问题</p>
<p>producer和 consumer 都sleep  如下时间</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">random</span>.<span style="color: black;">randrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>/<span style="color: #ff4500;">50.0</span><span style="color: black;">&#41;</span></pre></div></div>

<p>当consumer  sleep时间小于producer 的时候而队列为空的时候就会发生貌似死锁的现象</p>
<p>之所以说是貌似，是因为这个并不是死锁引起的问题，而是queue 的get方法，这个方法有个timeout的可选参数，如果没有这个参数，那么get会一直等待队列中添加新的元素进来才会返回，所以后面的consumer 的 release并没有执行导致队列一直锁在那里，producer也没法写入，</p>
<p>关于queue  get方法的更详细用法请参阅<a href="http://docs.python.org/library/queue.html#Queue.Queue.get">python手册Queue章节</a></p>
<p>Python 的 queue 实现就是线程安全的，没有必要上锁，这里就是因为 queue 内部的锁机制同你的锁冲突了，如果要是想自己控制的话，那么 queue 的 put 和 get 都得用 nowait 的方法</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Httpsqs Python Client</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python解析iso8601时间格式获得时间戳</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2009%2F03%2F16%2Fpython-and-programming%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python和其他语言数据类型比较</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/01/25/python-queue-lock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>python满足你需要的50个模块</title>
		<link>http://fendou.org/2011/01/12/50-python-modules/</link>
		<comments>http://fendou.org/2011/01/12/50-python-modules/#comments</comments>
		<pubDate>Wed, 12 Jan 2011 02:46:24 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Excellence Article]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=777</guid>
		<description><![CDATA[Python具有强大的扩展能力，网上有人列出了50个很棒的Python模块，包含几乎所有的需要：比如Databases，GUIs，Images, Sound, OS interaction, Web,以及其他。推荐收藏。 Graphical interface wxPython http://wxpython.org Graphical interface pyGtk http://www.pygtk.org Graphical interface pyQT http://www.riverbankcomputing.co.uk/pyqt/ Graphical interface Pmw http://pmw.sourceforge.net/ Graphical interface Tkinter 3000 http://effbot.org/zone/wck.htm Graphical interface Tix http://tix.sourceforge.net/ Database MySQLdb http://sourceforge.net/projects/mysql-python Database PyGreSQL http://www.pygresql.org/ Database Gadfly http://gadfly.sourceforge.net/ Database SQLAlchemy http://www.sqlalchemy.org/ Database psycopg http://www.initd.org/pub/software/psycopg/ Database kinterbasdb http://kinterbasdb.sourceforge.net/ Database cx_Oracle http://www.cxtools.net/default.aspx?nav=downloads Database pySQLite http://initd.org/tracker/pysqlite MSN Messenger msnlib http://auriga.wearlab.de/~alb/msnlib/ MSN Messenger pymsn http://telepathy.freedesktop.org/wiki/Pymsn MSN Messenger msnp http://msnp.sourceforge.net/ Network Twisted http://twistedmatrix.com/ Images PIL http://www.pythonware.com/products/pil/ Images gdmodule http://newcenturycomputers.net/projects/gdmodule.html...  <a href="http://fendou.org/2011/01/12/50-python-modules/" class="more-link" title="Read python满足你需要的50个模块">Read more &#187;</a><table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Httpsqs Python Client" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Httpsqs Python Client</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python中给urllib2设置超时时间" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Windows平台安装Python2.6 和 MySQL-Python" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>Python具有强大的扩展能力，网上有人列出了50个很棒的Python模块，包含几乎所有的需要：比如Databases，GUIs，Images, Sound, OS interaction, Web,以及其他。推荐收藏。</p>
<p>Graphical interface wxPython <a rel="nofollow" href="http://wxpython.org/" target="_blank">http://wxpython.org</a><br />
Graphical interface pyGtk <a rel="nofollow" href="http://www.pygtk.org/" target="_blank">http://www.pygtk.org</a><br />
Graphical interface pyQT <a rel="nofollow" href="http://www.riverbankcomputing.co.uk/pyqt/" target="_blank">http://www.riverbankcomputing.co.uk/pyqt/</a><br />
Graphical interface Pmw <a rel="nofollow" href="http://pmw.sourceforge.net/" target="_blank">http://pmw.sourceforge.net/</a><br />
Graphical interface Tkinter 3000 <a rel="nofollow" href="http://effbot.org/zone/wck.htm" target="_blank">http://effbot.org/zone/wck.htm</a><br />
Graphical interface Tix <a rel="nofollow" href="http://tix.sourceforge.net/" target="_blank">http://tix.sourceforge.net/</a></p>
<p>Database MySQLdb <a rel="nofollow" href="http://sourceforge.net/projects/mysql-python" target="_blank">http://sourceforge.net/projects/mysql-python</a><br />
Database PyGreSQL <a rel="nofollow" href="http://www.pygresql.org/" target="_blank">http://www.pygresql.org/</a><br />
Database Gadfly <a rel="nofollow" href="http://gadfly.sourceforge.net/" target="_blank">http://gadfly.sourceforge.net/</a><br />
Database SQLAlchemy <a rel="nofollow" href="http://www.sqlalchemy.org/" target="_blank">http://www.sqlalchemy.org/</a><br />
Database psycopg <a rel="nofollow" href="http://www.initd.org/pub/software/psycopg/" target="_blank">http://www.initd.org/pub/software/psycopg/</a><br />
Database kinterbasdb <a rel="nofollow" href="http://kinterbasdb.sourceforge.net/" target="_blank">http://kinterbasdb.sourceforge.net/</a><br />
Database cx_Oracle <a rel="nofollow" href="http://www.cxtools.net/default.aspx?nav=downloads" target="_blank">http://www.cxtools.net/default.aspx?nav=downloads</a><br />
Database pySQLite <a rel="nofollow" href="http://initd.org/tracker/pysqlite" target="_blank">http://initd.org/tracker/pysqlite</a></p>
<p>MSN Messenger msnlib <a rel="nofollow" href="http://auriga.wearlab.de/~alb/msnlib/" target="_blank">http://auriga.wearlab.de/~alb/msnlib/</a><br />
MSN Messenger pymsn <a rel="nofollow" href="http://telepathy.freedesktop.org/wiki/Pymsn" target="_blank">http://telepathy.freedesktop.org/wiki/Pymsn</a><br />
MSN Messenger msnp <a rel="nofollow" href="http://msnp.sourceforge.net/" target="_blank">http://msnp.sourceforge.net/</a><br />
Network Twisted <a rel="nofollow" href="http://twistedmatrix.com/" target="_blank">http://twistedmatrix.com/</a><br />
Images PIL <a rel="nofollow" href="http://www.pythonware.com/products/pil/" target="_blank">http://www.pythonware.com/products/pil/</a><br />
Images gdmodule <a rel="nofollow" href="http://newcenturycomputers.net/projects/gdmodule.html" target="_blank">http://newcenturycomputers.net/projects/gdmodule.html</a><br />
Images VideoCapture <a rel="nofollow" href="http://videocapture.sourceforge.net/" target="_blank">http://videocapture.sourceforge.net/</a></p>
<p>Sciences and Maths scipy <a rel="nofollow" href="http://www.scipy.org/" target="_blank">http://www.scipy.org/</a><br />
Sciences and Maths NumPy <a rel="nofollow" href="http://numpy.scipy.org//" target="_blank">http://numpy.scipy.org//</a><br />
Sciences and Maths numarray <a rel="nofollow" href="http://www.stsci.edu/resources/software_hardware/numarray" target="_blank">http://www.stsci.edu/resources/software_hardware/numarray</a><br />
Sciences and Maths matplotlib <a rel="nofollow" href="http://matplotlib.sourceforge.net/" target="_blank">http://matplotlib.sourceforge.net/</a></p>
<p>Games Pygame <a rel="nofollow" href="http://www.pygame.org/news.html" target="_blank">http://www.pygame.org/news.html</a><br />
Games Pyglet <a rel="nofollow" href="http://www.pyglet.org/" target="_blank">http://www.pyglet.org/</a><br />
Games PySoy <a rel="nofollow" href="http://www.pysoy.org/" target="_blank">http://www.pysoy.org/</a><br />
Games pyOpenGL <a rel="nofollow" href="http://pyopengl.sourceforge.net/" target="_blank">http://pyopengl.sourceforge.net/<br />
</a>Jabber jabberpy<a rel="nofollow" href="http://pyopengl.sourceforge.net/" target="_blank"> </a><a rel="nofollow" href="http://jabberpy.sourceforge.net/" target="_blank">http://jabberpy.sourceforge.net/</a><br />
Web scrape <a rel="nofollow" href="http://zesty.ca/python/scrape.html" target="_blank">http://zesty.ca/python/scrape.html</a><br />
Web Beautiful Soup <a rel="nofollow" href="http://crummy.com/software/BeautifulSoup" target="_blank">http://crummy.com/software/BeautifulSoup</a><br />
Web pythonweb <a rel="nofollow" href="http://www.pythonweb.org/" target="_blank">http://www.pythonweb.org/</a><br />
Web mechanize <a rel="nofollow" href="http://wwwsearch.sourceforge.net/mechanize/" target="_blank">http://wwwsearch.sourceforge.net/mechanize/</a></p>
<p>Localisation geoname.py <a rel="nofollow" href="http://www.zindep.com/blog-zindep/Geoname-python/" target="_blank">http://www.zindep.com/blog-zindep/Geoname-python/</a></p>
<p>Serial port pySerial <a rel="nofollow" href="http://pyserial.sourceforge.net/" target="_blank">http://pyserial.sourceforge.net/</a><br />
Serial port USPP <a rel="nofollow" href="http://ibarona.googlepages.com/uspp" target="_blank">http://ibarona.googlepages.com/uspp</a></p>
<p>Parallel Port pyParallel <a rel="nofollow" href="http://pyserial.sourceforge.net/pyparallel.html" target="_blank">http://pyserial.sourceforge.net/pyparallel.html</a></p>
<p>USB Port pyUSB <a rel="nofollow" href="http://bleyer.org/pyusb/" target="_blank">http://bleyer.org/pyusb/</a></p>
<p>Windows ctypes <a rel="nofollow" href="http://starship.python.net/crew/theller/ctypes/" target="_blank">http://starship.python.net/crew/theller/ctypes/</a><br />
Windows pywin32 <a rel="nofollow" href="http://sourceforge.net/projects/pywin32/" target="_blank">http://sourceforge.net/projects/pywin32/</a><br />
Windows pywinauto <a rel="nofollow" href="http://www.openqa.org/pywinauto/" target="_blank">http://www.openqa.org/pywinauto/</a><br />
Windows pyrtf <a rel="nofollow" href="http://pyrtf.sourceforge.net/" target="_blank">http://pyrtf.sourceforge.net/</a><br />
Windows wmi <a rel="nofollow" href="http://timgolden.me.uk/python/wmi.html" target="_blank">http://timgolden.me.uk/python/wmi.html</a></p>
<p>PDA/GSM/Mobiles pymo <a rel="nofollow" href="http://www.awaretek.com/pymo.html" target="_blank">http://www.awaretek.com/pymo.html</a><br />
PDA/GSM/Mobiles pyS60 <a rel="nofollow" href="http://sourceforge.net/projects/pys60" target="_blank">http://sourceforge.net/projects/pys60</a></p>
<p>Sound pySoundic <a rel="nofollow" href="http://pysonic.sourceforge.net/" target="_blank">http://pysonic.sourceforge.net/</a><br />
Sound pyMedia <a rel="nofollow" href="http://pymedia.org/" target="_blank">http://pymedia.org/</a><br />
Sound FMOD <a rel="nofollow" href="http://www.fmod.org/" target="_blank">http://www.fmod.org/</a><br />
Sound pyMIDI <a rel="nofollow" href="http://www.cs.unc.edu/Research/assist/developer.shtml" target="_blank">http://www.cs.unc.edu/Research/assist/developer.shtml</a></p>
<p>GMail libgmail <a rel="nofollow" href="http://libgmail.sourceforge.net/" target="_blank">http://libgmail.sourceforge.net/</a><br />
Google pyGoogle <a rel="nofollow" href="http://pygoogle.sourceforge.net/" target="_blank">http://pygoogle.sourceforge.net/</a><br />
Expect pyExpect <a rel="nofollow" href="http://pexpect.sourceforge.net/" target="_blank">http://pexpect.sourceforge.net/</a><br />
WordNet pyWordNet <a rel="nofollow" href="http://osteele.com/projects/pywordnet/" target="_blank">http://osteele.com/projects/pywordnet/</a><br />
Command line cmd <a rel="nofollow" href="http://blog.doughellmann.com/2008/05/pymotw-cmd.html" target="_blank">http://blog.doughellmann.com/2008/05/pymotw-cmd.html</a><br />
Compiler backend llvm-py <a rel="nofollow" href="http://mdevan.nfshost.com/llvm-py/" target="_blank">http://mdevan.nfshost.com/llvm-py/</a><br />
3D VPython <a rel="nofollow" href="http://vpython.org/" target="_blank">http://vpython.org</a></p>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Httpsqs Python Client" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fhttpsqs-python-client%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Httpsqs Python Client</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python中给urllib2设置超时时间" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python中给urllib2设置超时时间</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Windows平台安装Python2.6 和 MySQL-Python" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2011/01/12/50-python-modules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python解析iso8601时间格式获得时间戳</title>
		<link>http://fendou.org/2010/11/21/python-parse-iso8601/</link>
		<comments>http://fendou.org/2010/11/21/python-parse-iso8601/#comments</comments>
		<pubDate>Sun, 21 Nov 2010 02:28:04 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=754</guid>
		<description><![CDATA[关于iso8601数据交换标准，请参见维基百科的解释，中文版不完全解释，参见为维基百科中文版 常见示例格式如下： 2010-11-21T00:00:00+08:00 真实的案例，请参见美团网的团购API Python默认安装包中不能对iso8601格式的时间戳，因此先安装这个解析包，下载地址：http://pypi.python.org/pypi/iso8601/ 如果你不能在网站上找到对应Python版本的模块，也可以通过输入easy_install iso8601试试，我的是2.6版本，安装成功 解析过程很简单，代码如下: import time import iso8601 dt = iso8601.parse_date&#40;'2010-11-21T00:00:00+08:00'&#41; timestamp = time.mktime&#40;dt.timetuple&#40;&#41;&#41; PS:感谢妖怪帮助我解决解析iso8601时间格式的问题<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python Queue 的多线程(multi thread)死锁问题" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python Queue 的多线程(multi thread)死锁问题</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="python非贪婪、多行匹配正则表达式例子" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F19%2Fpython-multi-line-non-greedy-regular-expression-sample%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">python非贪婪、多行匹配正则表达式例子</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Windows平台安装Python2.6 和 MySQL-Python" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>关于iso8601数据交换标准，请参见<a href="http://en.wikipedia.org/wiki/ISO_8601">维基百科的解释</a>，中文版不完全解释，参见为<a href="http://zh.wikipedia.org/zh/ISO_8601">维基百科中文版</a><br />
常见示例格式如下：</p>
<blockquote><p>2010-11-21T00:00:00+08:00</p></blockquote>
<p>真实的案例，请参见<a href="view-source:http://www.meituan.com/api/v1/beijing/deals">美团网的团购API</a></p>
<p>Python默认安装包中不能对iso8601格式的时间戳，因此先安装这个解析包，下载地址：<a href="http://pypi.python.org/pypi/iso8601/">http://pypi.python.org/pypi/iso8601/</a><br />
如果你不能在网站上找到对应Python版本的模块，也可以通过输入easy_install iso8601试试，我的是2.6版本，安装成功<br />
解析过程很简单，代码如下:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
<span style="color: #ff7700;font-weight:bold;">import</span> iso8601
dt = iso8601.<span style="color: black;">parse_date</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'2010-11-21T00:00:00+08:00'</span><span style="color: black;">&#41;</span>
timestamp = <span style="color: #dc143c;">time</span>.<span style="color: black;">mktime</span><span style="color: black;">&#40;</span>dt.<span style="color: black;">timetuple</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>PS:感谢<a href="http://www.dualface.com/blog/">妖怪</a>帮助我解决解析iso8601时间格式的问题</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="5"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="超级简单Python Socket Server一例" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F08%2F05%2Fpython-socket-server-simple-example%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2012/01/20/14185006.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">超级简单Python Socket Server一例</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python PIL 生成带阴影的缩略图" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/11/20/11136487.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Python Queue 的多线程(multi thread)死锁问题" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F25%2Fpython-queue-lock%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Python Queue 的多线程(multi thread)死锁问题</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="python非贪婪、多行匹配正则表达式例子" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F19%2Fpython-multi-line-non-greedy-regular-expression-sample%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">python非贪婪、多行匹配正则表达式例子</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Windows平台安装Python2.6 和 MySQL-Python" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="5" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2010/11/21/python-parse-iso8601/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python中给urllib2设置超时时间</title>
		<link>http://fendou.org/2010/11/21/python-urllib2-set-timeout/</link>
		<comments>http://fendou.org/2010/11/21/python-urllib2-set-timeout/#comments</comments>
		<pubDate>Sun, 21 Nov 2010 02:12:29 +0000</pubDate>
		<dc:creator>崔玉松</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://fendou.org/?p=751</guid>
		<description><![CDATA[import socket import urllib2 &#160; socket.setdefaulttimeout&#40;seconds&#41; &#160; open = urllib2.urlopen&#40;&#34;http://xxx.xxx.xxx&#34;&#41; urllib2本身是没有办法设置超时时间的，示例中是通过socket.setdefaulttimeout() 设置了全局默认超时时间，从而给urllib2.urlopen()也设置了默认的超时时间<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python解析iso8601时间格式获得时间戳</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">python满足你需要的50个模块</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2009%2F03%2F16%2Fpython-and-programming%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python和其他语言数据类型比较</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[
<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">socket</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urllib2</span>
&nbsp;
<span style="color: #dc143c;">socket</span>.<span style="color: black;">setdefaulttimeout</span><span style="color: black;">&#40;</span>seconds<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #008000;">open</span> = <span style="color: #dc143c;">urllib2</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;http://xxx.xxx.xxx&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>urllib2本身是没有办法设置超时时间的，示例中是通过socket.setdefaulttimeout() 设置了全局默认超时时间，从而给urllib2.urlopen()也设置了默认的超时时间</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">您可能也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F06%2F17%2Finstall-python26-mysql-python-on-windows%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Windows平台安装Python2.6 和 MySQL-Python</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-parse-iso8601%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python解析iso8601时间格式获得时间戳</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F12%2F50-python-modules%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">python满足你需要的50个模块</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2011%2F01%2F31%2Fpython-pil-shadow-thumb%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python PIL 生成带阴影的缩略图</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect?url=http%3A%2F%2Ffendou.org%2F2009%2F03%2F16%2Fpython-and-programming%2F&from=http%3A%2F%2Ffendou.org%2F2010%2F11%2F21%2Fpython-urllib2-set-timeout%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Python和其他语言数据类型比较</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://fendou.org/2010/11/21/python-urllib2-set-timeout/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

