AtomAPIでブックマーク

はてブにPOSTするPythonスクリプトPythonでAtomクライアント - Λάδι ΒιώσαςフォトライフへのPOSTが解説されていたので、そのまま流用しようと思ったら何故かブックマークの方はUser-Agentいじらないと通らなかった。

#coding: utf-8

import random
import datetime, time
import base64, sha
import httplib

class AtomClient:
  def __init__(self):
    self.endopoint = None
    self.wsse = None

  def credentials(self, endpoint, user, password):
    nonce = sha.sha(str(time.time() + random.random())).digest()
    now = datetime.datetime.now().isoformat() + "Z"
    digest = sha.sha(nonce + now + password).digest()

    wsse = 'UsernameToken Username="%(u)s", PasswordDigest="%(p)s", Nonce="%(n)s", Created="%(c)s"'
    value = dict(u = user, p = base64.encodestring(digest).strip(),
           n = base64.encodestring(nonce).strip(), c = now)

    self.endpoint = endpoint
    self.wsse = wsse % value

  def atom_request(self, method, URI, body):
    con = httplib.HTTPConnection(self.endpoint)
    # ここ
    con.request(method, URI, body, {
        'X-WSSE' : self.wsse,
        'Content-Type':'text/xml',
        'User-Agent': 'Python WSSE'})
    r = con.getresponse()

    response = dict(status=r.status, reason=r.reason, data=r.read())
    con.close()
    return response

class HateBu(AtomClient):
  def upload_entry(self, url, comment):
    entry = '''<entry xmlns="http://purl.org/atom/ns#">
                 <title>dummy</title>
                 <link rel="related" type="text/html" href="%s"/>
                 <summary type="text/plain">%s</summary>
               </entry>'''
    return self.atom_request('POST', '/atom/post', entry%(url, comment))

# 使い方
hp = HateBu()
hp.credentials('b.hatena.ne.jp', 'username', 'password')
print hp.upload_entry('http://ist.ksc.kwansei.ac.jp/portal/', 'これはサブい')

参考