furl: 使い易いPythonのURLライブラリ

https://github.com/gruns/furl

インストール


$ git clone https://github.com/gruns/furl.git
$ cd furl
$ ls
API.md furl.py furl.pyc LICENSE.md README.md tests/
setup.pyなどはない。

python2.7以上

python2.6でも使えるようにしたフォーク:https://github.com/tengu/furl


$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from furl import furl
Traceback (most recent call last):
File "", line 1, in
File "furl.py", line 170
self.params = {k:urllib.unquote_plus(v) for k, v in query.iteritems()}
^
SyntaxError: invalid syntax
>>> ^D

$ python2.7
Python 2.7.0+ (r27:82500, Sep 15 2010, 18:14:55)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from furl import furl
>>> u=furl('http://example.com:8000/dir/file?foo=bar&arg=42')
>>> u
furl('http://example.com:8000/dir/file?foo=bar&arg=42')

python2.7だとエラーがない。

属性を簡単に編集できる


>>> [ a for a in dir(u) if not a.startswith('_') ]
['DEFAULT_PORTS', 'add', 'args', 'fragment', 'fragmentstr', 'host', 'netloc', 'parse', 'path', 'pathstr', 'port', 'query', 'querystr', 'remove', 'scheme', 'set', 'url']
>>> u.host
'example.com'
>>> u.netloc
'example.com:8000'
>>> u.port
8000

パスはオブジェクト。その場で編集できる。


>>> u.path
Path('/dir/file')
>>> type(u.path)

>>> dir(u.path)
[... 'add', 'isabsolute', 'isdir', 'isfile', 'parse', 'remove', 'segments', 'set']
>>> u.path.add('hoge')
Path('/dir/file/hoge')
>>> u.path
Path('/dir/file/hoge')

パスを文字列としてアクセス


>>> u.pathstr
'/dir/file/hoge'

クエリもオブジェクト


>>> u.query
Query('foo=bar&arg=42')
>>> dir(u.query)
[..., 'add', 'params', 'parse', 'remove', 'set']

dictとして操作できる。


>>> type(u.query.params)

>>> u.query.params
{'foo': 'bar', 'arg': '42'}
>>> u.query.params['foo']='baz'
>>> u.query
Query('foo=baz&arg=42')
>>> u.query.params.items()
[('foo', 'baz'), ('arg', '42')]

URLを文字列としてアクセス


>>> u.url
'http://example.com:8000/dir/file/hoge?foo=baz&arg=42'
>>> type(u.url)

>>> str(u)
'http://example.com:8000/dir/file/hoge?foo=baz&arg=42'

これ以外にも色々機能がある。しかし、u.path='bar'ができる時点で俺的にはもう使用が決定済み。

以前からPythonの標準URLライブラリは使い難いと思っていた。urlエンコードはurllib.escape? いや、encode? それともurllib2だっけ?デコードの方はurllib1それとも2? と迷ったり、urlparseでパースしたURLオブジェクトの属性を更新しようとして"can't set attribute"と叱られたり。PerlのURLなら$uri->path($new_path)とできるに… PythonにおけるURL処理がこんなに醜いわけがない。きっと俺の理解が足りないんだ…などと釈然としなかった。

furlのようなライブラリが出てくるってことは本当に使い難かったんだな。