Jul 21

Dasblog is a great blog system. However it’s too new to be perfect. After struggling with it, I finally decide to switch to a mature blog system, i.e. WordPress.

However, it’s not a one-click task. The most important thing is to import previous?articles from Dasblog. Again, I found Python is such a beautiful thing! The task was done by 158 lines of python code! The path data went through is very interesting:

blogware XML data?-> python data -> xml-rpc data -> http data?-> php data -> mysql data

A bit complicated, hehe. Now the new blog address is http://www.frankdu.com/blog. I need time to test the system, and make sure everything works Okay.

May 17

出自:Dive Into Python,Chapter 11.
网址:http://diveintopython.org

有五个你必须关注的 HTTP 重要特性。

11.3.1. 用户代理 (User-Agent)

User-Agent 是一种客户端告知服务器谁在什么时候通过 HTTP 请求了一个 web 页, feed
汇聚或其他类型的 web 服务的简单途径。 当客户请求一个资源时, 应该尽可能明确发起请求的是谁。
以便当产生异常错误时,允许服务器端的管理员与客户端的开发者取得联系。

默认情况下 Python 发送一个通用的 User-Agent: Python-urllib/1.15。 下一节,
您将看到更加有针对性的 User-Agent

11.3.2. 重定向 (Redirects)

有时资源移来移去。 Web 站点重组内容, 页面移动到了新的地址。甚至是 web 服务重组。 原来位于 http://example.com/index.xml 的 feed 汇聚可能被移动到 http://example.com/xml/atom.xml。 或者因为一个机构的扩展或重组,整个域被迁移。 例如,
http://www.example.com/index.xml 可能被重定向到 http://server-farm-1.example.com/index.xml

您每次从 HTTP 服务器请求任何类型的资源时, 服务器的响应中均包含一个状态代码。 状态代码 200
的意思是 “一切正常, 这就是您请求的页面”。 状态代码 404
的意思是 “页面没找到”。 (当浏览 web 时,你可能看到过 404 errors。)

HTTP 有两种不同的方法表示资源已经被移动。 状态代码 302 表示 临时重定向; 这意谓着 “哎呀,
访问内容被临时移动” (然后在 Location: 头部给出临时地址)。 状态代码 301 表示 永久重定向; 这意谓着
“哎呀, 访问内容被永久移动” (然后在 Location:
头部给出新地址)。 如果您获得了一个 302 状态代码和一个新地址, HTTP
规范说您应该使用新地址获取您的请求, 但是下次您要访问同一资源时, 应该使用就地址重试。 但是如果您获得了一个 301 状态代码和一个新地址, 您应该从次使用新地址。

当从 HTTP 服务器接受到一个适当的状态代码时, urllib.urlopen 将自动 “跟踪” 重定向, 但不幸的是,
当它做了重定向时不会告诉你。你将最终获得所请求的数据,却丝毫不会察觉到在这个过程中一个潜在的库 “帮助”
你做了一次重定向操作。因此你将继续不断的使用旧地址, 并且每次都将获得被重定向的新地址。这一过程要往返两次而不是一次: 太没效率了! 本章的后面,
您将看到如何改进这一点,从而适当的且有效率的处理永久重定向。

11.3.3. Last-Modified/If-Modified-Since

有些数据随时都在变化。 CNN.com 的主页经常几分钟就更新。 另一方面, Google.com 的主页几个星期才更新一次 (当他们上传特殊的假日
logo, 或为一个新服务作广告时)。 Web 服务是不变的:通常服务器指导你所请求的数据的最后修改时间,并且 HTTP
为服务器提供了一种将最近修改数据连同你请求的数据一同发送的方法。

如果你第二次 (或第三次, 或第四次) 请求相同的数据, 你可以告诉服务器你上一次获得的最后修改日期: 在你的请求中发送了一个 If-Modified-Since 头信息, 它包含了上一次从服务器连同数据所获得的日期。 如果数据从那时起没有改变,
服务器将返回一个特殊的 HTTP 状态代码 304, 这意谓着 “从上一次请求后这个数据没有改变”。 为什么这一点有何进步呢? 因为当服务器发送状态编码 304 时, 不再重新发送数据
您仅仅获得了这个状态代码。 所以当数据没有更新时,你不需要一次又一次地下载相同的数据; 服务器假定你有本地的缓存数据。

所有现代的浏览器都支持最近修改的数据检查。如果你曾经访问过某页, 一天后重新访问相同的页时发现它没有变化, 并奇怪第二次访问时页面加载得如此之快 –
这就是原因所在。 你的浏览器首次访问时会在本地缓存页面内容, 当你第二次访问, 浏览器自动发送 首次访问时从服务器获得的最近修改日期。 服务器简单的返回 304: 没有修改, 因此浏览器就会知道从本地缓存加载页面。 在这一点上,Web 服务也如此智能。

Python 的 URL 库没有提供内置的最近修改数据检查支持, 但是
你可以为每一个请求添加任意的头信息并在每一个响应中读取任意头信息, 从而自己添加这种支持。

11.3.4. ETag/If-None-Match

ETag 是实现与最近修改数据检查同样的功能的另一种方法: 没有变化时不重新下载数据。 其工作原理是: 服务器发送你所请求的数据的同时,发送某种数据的
hash (在 ETag 头信息中) 。 hash 的确定完全取决于服务器。 当第二次请求相同的数据时, 在
If-None-Match: 头信息中将包含 ETag hash, 如果数据没有改变, 服务器将返回 304 状态代码。 与最近修改数据检查相同, 服务器 仅仅 发送 304 状态代码;
第二次将不为你发送相同的数据。 在第二次请求时, 通过包含 ETag hash, 你会告诉服务器,如果 hash 仍旧匹配就没有必要重新发送相同的数据,
因为你还有上一次访问过的数据。

Python 的 URL 库没有对 ETag 的内置支持,
但是在本章后面你将看到如何添加这种支持。

11.3.5. 压缩 (Compression)

最后一个重要的 HTTP 特性是 gzip 压缩。当谈论 HTTP web 服务时, 几乎总是会谈及在网络线路上传输的 XML。XML 是文本,
而且还是相当冗长的文本, 并且文本通常可以被很好地压缩。当你通过 HTTP 请求一个资源时, 可以告诉服务器, 如果它有任何新数据要发送给我时,
请以压缩的格式发送。 在你的请求中包含 Accept-encoding: gzip 头信息, 如果服务器支持压缩,
他将返回由 gzip 压缩的数据并且使用 Content-encoding: gzip 头信息标记。

Python 的 URL 库本身没有内置对 gzip 压缩的支持,
但是你能为请求添加任意的头信息。 Python 还提供了一个独立的 gzip 模块, 它提供了对数据进行解压缩的功能。

May 12

在看Dive Into Python,下面的Python代码是第4章《自省的威力》的示例,运行一下,object可以是list、tuple、dictionary等。然后思考一下,如果用Java或C#写,大概要多少代码呢?另外,”None is None”是啥语言呢?英语?Python?都对!呵呵!

def info(object, spacing=10, collapse=1):

    “”"Print methods and doc strings.

   
    Takes module, class, list, dictionary, or string.”"”

   
    methodList = [method for method in dir(object) if callable(getattr(object, method))]

    processFunc = collapse and (lambda s: ” “.join(s.split())) or (lambda s: s)

    print “\n”.join(["%s %s" %

        (method.ljust(spacing),

        processFunc(str(getattr(object, method).__doc__)))

        for method in methodList])

if __name__ == “__main__”:

    print info.__doc__

May 10

本来想找RSS 1.0/2.0、ATOM 1.0的schema的,结果找到一个很好的种子feed解析器,而且是通用的,就是Python写的feedparser:

    http://feedparser.org/

Python能用的模块还真的不少,使用挺方便的,通过version属性,可以很容易的知道种子的类型,到底是ATOM还是RSS,更重要的是直接就能解析RSS和ATOM文档,赞!

Mar 06

美好的世界中,懒人总有选择。对我这样一个Python新手,没有足够的闲暇时间,去读完Python中的XML处理模块,那么最好的方式,就是利用已有的只是囖。那么最直接的方式,就是利用.NET的类库,这方面的工具就是:

IronPython
http://www.codeplex.com/IronPython

Python for .NET
http://pythonnet.sourceforge.net/

Python这个脚本语言有很灵活的选择,比如你熟悉Java,可以考虑JPython,^_^

Feb 21

某种意义上Python可以看作有2种字符串:str和unicode,一个字符串可以使用type()来检查属于那种类型。str可以看作非常基本的byte数据。在Python中处理中文,需要额外做一些编码解码工作,比如:

  • 生成一个xml文件,open()的编码是ascii,而且没有指定编码的地方,如果想用utf-8怎么办呢?OK,import codes,然后codes.open(filename, mode, encoding)
  • 把一个网页html文件从gb2312,转换成utf8编码呢?读入一行到strLine, 然后strLine.decode(’gb2312′).encode(’utf-8′),不过这个比较慢,呵呵
  • 怎么知道缺省的编码呢?sys.getdefaultencoding()和sys.getfilesystemencoding()
  • 如何检查一个串的编码方式?”chardet, auto-detecting character encodings” @ http://chardet.feedparser.org/,使用这个工具,给出网页地址,它会自动下载并检测编码方式

?

Feb 20

Original Copy: http://www.physics.ucf.edu/~mdj/MinimalPython.html

I am trying to get familiar with Python, python is quite interesting for programming. There are lots of modules handy for us. For example, I need an FTP client library. It’s not easy to find a powerful .net open source implementation. However, ftplib is just part of Python’s standard library, not to mention other powerful network modules and string manipulation modules. The reason I learn it is to do crawling work and information extraction with it. :)

Nov 22

Brad是BT的作者,这是他很久以前写的一篇文章,不多说了。相信和
我一样喜欢看PB、DH的会非常感谢BT的流行,:)

=========================================

Posted 15 Mar 2001 by Bram
(Author of BitTorrent)

Software engineers suffer from not knowing what their code should look like. The classic essay worse is better exemplifies this - How can worse be better? Isn’t worse worse? Even more confusingly, it’s generally referenced to claim the exact opposite of what it’s trying to argue.

The problem is that people use very different, and often antithetical, criteria to judge the ‘beauty’ of code. Clearly there is a need for a measure of code quality which is more objective than aesthetic.

I suggest that you judge code based on it’s maintainability.

Truly maintanable code is flexible and can be taken in many directions. Code is not more maintainable just because it has more features - invoking functionality which is currently dormant is not maintenance, it’s use. Maintenance is when you add new functionality or change existing functionality. This is often done long after the code was originally written and in a completely unforseeable manner.

Planning for the unexpected is a paradoxical concept - if you don’t know what it is, how can you plan for it? Thankfully, there are many concrete techniques which work.

Use less code

The less code you have, the less there is to maintain. You shouldn’t slavishly count characters or lines of code in your program and reduce it at all costs, but generally speaking, less is better. Get rid of unused functions and diagnostic statements - they’re just more muck to wade through.

Using existing libraries, of course, results in less code. In practice, many libraries so low quality that you’re better off rewriting them, but many aren’t, and you should use those when possible.

Encapsulate

If you create well-defined boundaries which are only connected by narrow bridges, you can rearrange entire towns with the neigbors being none the wiser. If there’s too much travel going on, even a single eviction can cause widespread panic.

Reduce preconditions

Code which is very persnickity about how it’s invoked makes everything else harder to maintain. Examples are requiring that methods be called in a certain order, and requiring that a certain method be called only once. Try to avoid those.

Write in an easy to maintain language

My favorite language for maintainability is Python. It has simple, clean syntax, object encapsulation, good library support, and optional named parameters. An example of a language which is terrible for maintainability is Perl. Yes, I said it. No, I’m not going to back down.

Write test code

New code always runs the risk of breaking something. A test suite which is easy to run and either returns ‘everything passed’ or ‘these tests failed’ makes it very easy to detect and fix regressions. Test code has to be changed much less often when it tests interfaces rather than implementations. For example, code which turns objects into strings and back again (known as ‘pickling’) can be tested by pickling and unpickling an object and comparing the result with the original. Those tests will continue to work even if the string format is completely changed.

Create tools

There are two ways of building a barn - one is to make a hammer and use it to nail the barn together, the other is to nail it together with your hands. They might take about the same amount of time, but the hammer will help you again in the future.

Use safe techniques

There are several techniques which result in more maintainable code under almost all circumstances. Garbage collection magically removes all the headaches of memory allocation. Monothreading gets rid of all the headaches of thread safety. And don’t forget the first rule of writing internet applications - ‘Don’t re-implement TCP/IP’.

Let yourself get frustrated

Many times I have gotten frustrated doing something the ‘right’ way, figured ‘fuck it’, and done something simpler and more expedient. Sometimes it turns out to be a hack, but often it turns out to actually be a more flexible solution, for the very reasons I got frustrated by.

A word about performance

There’s a rule of thumb that 1% of the code takes up x% of the actual runtime, and in recent years x has been increasing dramatically. Combined with how much cheaper fast machines are than developer time, this means that performance is much less of an issue than it used to be. Sometimes it makes sense to work on better performance, but it should be viewed as a feature like any other, not an overriding principle to build software around. Maintainability works much better.

-Bram Cohen