__init__ (version 0.6)
index
/home/berend/project/pydelicious/trunk/pydelicious/__init__.py

Library to access del.icio.us data via Python.
 
An introduction to the project is given in the README.
 
pydelicious is released under the FreeBSD License. 
See license.txt for details and the copyright holders.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 
Modules
       
datetime
feedparser
httplib
locale
os
socket
sys
time
urllib2

 
Classes
       
DeliciousAPI
exceptions.Exception(exceptions.BaseException)
DeliciousError
DeliciousItemExistsError
PyDeliciousException
PyDeliciousThrottled
PyDeliciousUnauthorized
urllib2.HTTPDefaultErrorHandler(urllib2.BaseHandler)
DeliciousHTTPErrorHandler

 
class DeliciousAPI
    A single-user Python facade to the del.icio.us HTTP API.
 
See http://delicious.com/help/api.
 
Methods ``request`` and ``request_raw`` represent the core. For all API
paths there are furthermore methods (e.g. posts_add for 'posts/all') with
an explicit declaration of parameters and documentation.
 
  Methods defined here:
__init__(self, user, passwd, codec='UTF-8', api_request=<function dlcs_api_request>, xml_parser=<function dlcs_parse_xml>, build_opener=<function dlcs_api_opener>, encode_params=<function dlcs_encode_params>)
Initialize access to the API for ``user`` with ``passwd``.
 
``codec`` sets the encoding of the arguments, which defaults to the
users preferred locale.
 
The ``api_request`` and ``xml_parser`` parameters by default point to
functions within this package with standard implementations which
request and parse a resource. See ``dlcs_api_request()`` and
``dlcs_parse_xml()``.
 
Parameter ``build_opener`` is a callable that, provided with the 
credentials, should build a urllib2 opener for the delicious API server
with HTTP authentication. See ``dlcs_api_opener()`` for the default
implementation.
 
``encode_params`` finally preprocesses API parameters before
they are passed to ``api_request``.
__repr__(self)
bundles_all(self, **kwds)
Retrieve user bundles from del.icio.us.
::
 
    <bundles>
        <bundel name="..." tags=...">
bundles_delete(self, bundle, **kwds)
Delete a bundle from del.icio.us. Returns a `result` message or
raises an ``DeliciousError``. See ``request()``.
 
&bundle (required)
    the bundle name.
bundles_set(self, bundle, tags, **kwds)
Assign a set of tags to a single bundle, wipes away previous
settings for bundle. Returns a `result` messages or raises an
``DeliciousError``. See ``request()``.
 
&bundle (required)
    the bundle name.
&tags (required)
    list of tags.
get_method(self, path)
get_url(self, url)
Return the del.icio.us url at which the HTML page with posts for
``url`` can be found.
posts_add(self, url, description, extended='', tags='', dt='', replace=False, shared=True, **kwds)
Add a post to del.icio.us. Returns a `result` message or raises an
``DeliciousError``. See ``request()``.
 
&url (required)
    the url of the item.
&description (required)
    the description of the item.
&extended (optional)
    notes for the item.
&tags (optional)
    tags for the item (space delimited).
&dt (optional)
    datestamp of the item (format "CCYY-MM-DDThh:mm:ssZ").
    Requires a LITERAL "T" and "Z" like in ISO8601 at
    http://www.cl.cam.ac.uk/~mgk25/iso-time.html for example:
    "1984-09-01T14:21:31Z"
&replace=no (optional) - don't replace post if given url has already
    been posted.
&shared=yes (optional) - wether the item is public.
posts_all(self, tag='', start=None, results=None, fromdt=None, todt=None, meta=True, hashes=False, **kwds)
Returns all posts. Please use sparingly. Call the `posts_update`
method to see if you need to fetch this at all.
::
 
    <posts tag="..." user="..." update="CCYY-MM-DDThh:mm:ssZ">
        <post ...>
 
&tag
    (optional) Filter by this tag.
&start={#}
    (optional) Start returning posts this many results into the set.
&results={#}
    (optional) Return this many results.
&fromdt={CCYY-MM-DDThh:mm:ssZ}
    (optional) Filter for posts on this date or later
&todt={CCYY-MM-DDThh:mm:ssZ}
    (optional) Filter for posts on this date or earlier
&meta=yes
    (optional) Include change detection signatures on each item in a
    'meta' attribute. Clients wishing to maintain a synchronized local
    store of bookmarks should retain the value of this attribute - its
    value will change when any significant field of the bookmark
    changes.
&hashes
    (optional, exclusive) Do not fetch post details but a posts
    manifest with url- and meta-hashes. Other options do not apply.
posts_dates(self, tag='', **kwds)
Returns a list of dates with the number of posts at each date.
::
 
    <dates>
        <date date="CCYY-MM-DD" count="888">
 
&tag={TAG}
    (optional) Filter by this tag
posts_delete(self, url, **kwds)
Delete a post from del.icio.us. Returns a `result` message or
raises an ``DeliciousError``. See ``request()``.
 
&url (required)
    the url of the item.
posts_get(self, tag='', dt='', url='', hashes=[], meta=True, **kwds)
Returns posts matching the arguments. If no date or url is given,
most recent date will be used.
::
 
    <posts dt="CCYY-MM-DD" tag="..." user="...">
        <post ...>
 
&tag={TAG} {TAG} ... {TAG}
    (optional) Filter by this/these tag(s).
&dt={CCYY-MM-DDThh:mm:ssZ}
    (optional) Filter by this date, defaults to the most recent date on
    which bookmarks were saved.
&url={URL}
    (optional) Fetch a bookmark for this URL, regardless of date.
&hashes={MD5} {MD5} ... {MD5}
    (optional) Fetch multiple bookmarks by one or more URL MD5s
    regardless of date.
&meta=yes
    (optional) Include change detection signatures on each item in a
    'meta' attribute. Clients wishing to maintain a synchronized local
    store of bookmarks should retain the value of this attribute - its
    value will change when any significant field of the bookmark
    changes.
posts_recent(self, tag='', count='', **kwds)
Returns a list of the most recent posts, filtered by argument.
::
 
    <posts tag="..." user="...">
        <post ...>
 
&tag={TAG}
    (optional) Filter by this tag.
&count={1..100}
    (optional) Number of items to retrieve (Default:15, Maximum:100).
posts_update(self, **kwds)
Returns the last update time for the user. Use this before calling
`posts_all` to see if the data has changed since the last fetch.
::
 
    <update time="CCYY-MM-DDThh:mm:ssZ">
request(self, path, _raw=False, **params)
Sends a request message to `path` in the API, and parses the results
from XML. Use with ``_raw=True`` or ``call request_raw()`` directly
to get the filehandler and process the response message manually.
 
Calls to some paths will return a `result` message, i.e.::
 
    <result code="..." />
 
or::
 
    <result>...</result>
 
These should all be parsed to ``{'result':(Boolean, MessageString)}``,
this method raises a ``DeliciousError`` on negative `result` answers.
Positive answers are silently accepted and nothing is returned.
 
Using ``_raw=True`` bypasses all parsing and never raises
``DeliciousError``.
 
See ``dlcs_parse_xml()`` and ``request_raw()``.
request_raw(self, path, **params)
Calls the path in the API, returns the filehandle. Returned file-
like instances have an ``HTTPMessage`` instance with HTTP header
information available. Use ``filehandle.info()`` or refer to the
``urllib2.openurl`` documentation.
tags_delete(self, tag, **kwds)
Delete an existing tag.
 
&tag={TAG}
    (required) Tag to delete
tags_get(self, **kwds)
Returns a list of tags and the number of times it is used by the
user.
::
 
    <tags>
        <tag tag="TagName" count="888">
tags_rename(self, old, new, **kwds)
Rename an existing tag with a new tag name. Returns a `result`
message or raises an ``DeliciousError``. See ``request()``.
 
&old={TAG}
    (required) Tag to rename.
&new={TAG}
    (required) New tag name.

Data and other attributes defined here:
paths = {'posts/add': 'posts_add', 'posts/all': 'posts_all', 'posts/dates': 'posts_dates', 'posts/delete': 'posts_delete', 'posts/get': 'posts_get', 'posts/recent': 'posts_recent', 'posts/update': 'posts_update', 'tags/bundles/all': 'bundles_all', 'tags/bundles/delete': 'bundles_delete', 'tags/bundles/set': 'bundles_set', ...}

 
class DeliciousError(exceptions.Exception)
    Raised when the server responds with a negative answer
 
 
Method resolution order:
DeliciousError
exceptions.Exception
exceptions.BaseException
__builtin__.object

Static methods defined here:
raiseFor(error_string, path, **params)

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)
__unicode__(...)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message

 
class DeliciousHTTPErrorHandler(urllib2.HTTPDefaultErrorHandler)
    
Method resolution order:
DeliciousHTTPErrorHandler
urllib2.HTTPDefaultErrorHandler
urllib2.BaseHandler

Methods defined here:
http_error_401(self, req, fp, code, msg, headers)
http_error_503(self, req, fp, code, msg, headers)

Methods inherited from urllib2.HTTPDefaultErrorHandler:
http_error_default(self, req, fp, code, msg, hdrs)

Methods inherited from urllib2.BaseHandler:
__lt__(self, other)
add_parent(self, parent)
close(self)

Data and other attributes inherited from urllib2.BaseHandler:
handler_order = 500

 
class DeliciousItemExistsError(DeliciousError)
    Raised then adding an already existing post.
 
 
Method resolution order:
DeliciousItemExistsError
DeliciousError
exceptions.Exception
exceptions.BaseException
__builtin__.object

Static methods inherited from DeliciousError:
raiseFor(error_string, path, **params)

Data descriptors inherited from DeliciousError:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)
__unicode__(...)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message

 
class PyDeliciousException(exceptions.Exception)
    Standard pydelicious error
 
 
Method resolution order:
PyDeliciousException
exceptions.Exception
exceptions.BaseException
__builtin__.object

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)
__unicode__(...)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message

 
class PyDeliciousThrottled(exceptions.Exception)
    
Method resolution order:
PyDeliciousThrottled
exceptions.Exception
exceptions.BaseException
__builtin__.object

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)
__unicode__(...)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message

 
class PyDeliciousUnauthorized(exceptions.Exception)
    
Method resolution order:
PyDeliciousUnauthorized
exceptions.Exception
exceptions.BaseException
__builtin__.object

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)
__unicode__(...)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message

 
Functions
       
add(user, passwd, url, description, tags='', extended='', dt=None, replace=False)
apiNew(user, passwd)
Creates a new DeliciousAPI object, requires user(name) and passwd.
build_api_opener(host, user, passwd, extra_handlers=())
Build a urllib2 style opener with HTTP Basic authorization for one host
and additional error handling. If HTTP_PROXY is set a proxyhandler is also
added.
delete(user, passwd, url)
Delete the URL from the del.icio.us account.
delicious_datetime(str)
Parse a ISO 8601 formatted string to a Python datetime ...
dict0(d)
Removes empty string values from dictionary
dlcs_api_opener(user, passwd)
Build an opener for DLCS_API_HOST, see build_api_opener()
dlcs_api_request(path, params='', user='', passwd='', throttle=True, opener=None)
Retrieve/query a path within the del.icio.us API.
 
This implements a minimum interval between calls to avoid
throttling. [#]_ Use param 'throttle' to turn this behaviour off.
 
.. [#] http://del.icio.us/help/api/
dlcs_encode_params(params, usercodec='UTF-8')
Turn all param values (int, list, bool) into utf8 encoded strings.
dlcs_feed(name_or_url, url_map={'': '%(format)s', 'alerts': '%(format)s/alerts', 'popular': '%(format)s/popular', 'popular_tagged': '%(format)s/popular/%(tag)s', 'recent': '%(format)s/recent', 'tagged': '%(format)s/tag/%(tags)s', 'url': '%(format)s/url/%(urlmd5)s', 'urlinfo': 'json/urlinfo/%(urlmd5)s', 'user': '%(format)s/%(username)s', 'user_inbox': '%(format)s/inbox/%(username)s?private=%(key)s', ...}, count=15, **params)
Request and parse a feed. See delicious_v2_feeds for available names and
required parameters. Format defaults to json.
dlcs_parse_xml(data, split_tags=False)
Parse any del.icio.us XML document and return Python data structure.
 
Recognizes all XML document formats as returned by the version 1 API and
translates to a JSON-like data structure (dicts 'n lists).
 
Returned instance is always a dictionary. Examples::
 
 {'posts': [{'url':'...','hash':'...',},],}
 {'tags':['tag1', 'tag2',]}
 {'dates': [{'count':'...','date':'...'},], 'tag':'', 'user':'...'}
 {'result':(True, "done")}
 # etcetera.
dlcs_rss_request(tag='', popular=0, user='', url='')
Parse a RSS request.
 
This requests old (now undocumented?) URL paths that still seem to work.
get(user, passwd, tag='', dt=None, count=0, hashes=[])
Returns a list of posts for the user
get_all(user, passwd, tag='', start=0, results=100, fromdt=None, todt=None)
Returns a list with all posts. Please use sparingly. See `get_updated`
get_popular(tag='')
parse RSS for popular URLS for tag
get_tagposts(tag)
parse RSS for tag
get_tags(user, passwd)
Returns a list with all tags for user.
get_update(user, passwd)
Returns the last update time for the user.
get_urlposts(url)
parse RSS for URL
get_userposts(user)
parse RSS for user
getfeed(name, **params)
getrss(tag='', popular=0, url='', user='')
Get posts from del.icio.us via parsing RSS.
 
tag (opt) sort by tag
popular (opt) look for the popular stuff
user (opt) get the posts by a user, this striks popular
url (opt) get the posts by url
http_request(url, user_agent='pydelicious/0.6 http://code.google.com/p/pydelicious/', retry=4, opener=None)
Retrieve the contents referenced by the URL using urllib2.
 
Retries up to four times (default) on exceptions.
json_fans(user, raw=True, callback=None)
callback=NAME       wrap the object definition in a function call NAME(...)
?raw                a pure JSON object is returned, instead of an object named 
                    Delicious.
json_network(user, raw=True, callback=None)
callback=NAME       wrap the object definition in a function call NAME(...)
?raw                a raw JSON object is returned, instead of an object named 
                    Delicious.posts
json_posts(user, count=15, tag=None, raw=True)
user
count=###   the number of posts you want to get (default is 15, maximum 
            is 100)
raw         a raw JSON object is returned, instead of an object named 
            Delicious.posts
json_tags(user, atleast, count, sort='alpha', raw=True, callback=None)
user
atleast=###         include only tags for which there are at least ### 
                    number of posts.
count=###           include ### tags, counting down from the top.
sort={alpha|count}  construct the object with tags in alphabetic order 
                    (alpha), or by count of posts (count).
callback=NAME       wrap the object definition in a function call NAME(...),
                    thus invoking that function when the feed is executed.
raw                 a pure JSON object is returned, instead of code that 
                    will construct an object named Delicious.tags.
md5 = openssl_md5(...)
Returns a md5 hash object; optionally initialized with a string
rename_tag(user, passwd, oldtag, newtag)
Rename the tag for the del.icio.us account.

 
Data
        DEBUG = 0
DLCS_API = 'https://api.del.icio.us/v1'
DLCS_API_HOST = 'api.del.icio.us'
DLCS_API_PATH = 'v1'
DLCS_API_REALM = 'del.icio.us API'
DLCS_FEEDS = 'http://feeds.delicious.com/v2/'
DLCS_OK_MESSAGES = ('done', 'ok')
DLCS_REQUEST_TIMEOUT = 444
DLCS_RSS = 'http://del.icio.us/rss/'
DLCS_WAIT_TIME = 4
HTTPS_PROXY = 'http://localhost:8080/'
HTTP_PROXY = 'http://localhost:8080/'
ISO_8601_DATETIME = '%Y-%m-%dT%H:%M:%SZ'
PREFERRED_ENCODING = 'UTF-8'
USER_AGENT = 'pydelicious/0.6 http://code.google.com/p/pydelicious/'
Waiter = <__init__._Waiter instance>
__author__ = 'Berend (.mpe)'
__author_email__ = 'dev,pydelicious@dotmpe.com'
__credits__ = 'Frank Timmermann (original author), and in no\npa...o, me.gooz, mohangk, stumble.then.rise, clupprich'
__description__ = "Access delicious.com API's with Python"
__docformat__ = 'restructuredtext en'
__license__ = 'FreeBSD'
__long_description__ = "A complete Python interface to del.icio.us Bookmarks' HTTP API's."
__rcs_id__ = ': __init__.py 64 2010-11-13 12:43:28Z berend.van.berkum '
__url__ = 'http://code.google.com/p/pydelicious/'
__version__ = '0.6'
delicious_v2_feeds = {'': '%(format)s', 'alerts': '%(format)s/alerts', 'popular': '%(format)s/popular', 'popular_tagged': '%(format)s/popular/%(tag)s', 'recent': '%(format)s/recent', 'tagged': '%(format)s/tag/%(tags)s', 'url': '%(format)s/url/%(urlmd5)s', 'urlinfo': 'json/urlinfo/%(urlmd5)s', 'user': '%(format)s/%(username)s', 'user_inbox': '%(format)s/inbox/%(username)s?private=%(key)s', ...}

 
Author
        Berend (.mpe)

 
Credits
        Frank Timmermann (original author), and in no
particular order: Greg Pinero, me.gooz, mohangk, stumble.then.rise, clupprich