Parent: [5b7bb0] (diff)

Child: [793d05] (diff)

Download this file

wiki-post.py    101 lines (83 with data), 3.4 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
#!/usr/bin/python
from sys import stdin, stdout
import hmac, hashlib
from datetime import datetime
import os
import urllib
from urllib2 import urlopen, HTTPError
from urlparse import urlparse, urljoin
from optparse import OptionParser
from ConfigParser import ConfigParser
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
This function was borrowed from Django
"""
if strings_only and isinstance(s, (types.NoneType, int)):
return s
elif not isinstance(s, basestring):
try:
return str(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return ' '.join([smart_str(arg, encoding, strings_only,
errors) for arg in s])
return unicode(s).encode(encoding, errors)
elif isinstance(s, unicode):
r = s.encode(encoding, errors)
return r
elif s and encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
return s
def generate_smart_str(params):
for (key, value) in params:
yield smart_str(key), smart_str(value)
def urlencode(params):
"""
A version of Python's urllib.urlencode() function that can operate on
unicode strings. The parameters are first case to UTF-8 encoded strings and
then encoded as per normal.
"""
return urllib.urlencode([i for i in generate_smart_str(params)])
class Signer(object):
def __init__(self, secret_key, api_key):
self.secret_key = secret_key
self.api_key = api_key
def __call__(self, path, params):
params.append(('api_key', self.api_key))
params.append(('api_timestamp', datetime.utcnow().isoformat()))
message = path + '?' + urlencode(sorted(params))
digest = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()
params.append(('api_signature', digest))
return params
def main():
usage = 'usage: %prog [options] PageName [file]'
op = OptionParser(usage=usage)
op.add_option('-c', '--config', metavar='CONFIG')
op.add_option('-a', '--api-key', metavar='KEY')
op.add_option('-s', '--secret-key', metavar='KEY')
op.add_option('-u', '--url', metavar='URL')
(options, args) = op.parse_args()
page = args[0]
f = open(args[1], 'r') if len(args)>1 else stdin
markdown = f.read()
config = ConfigParser()
config.read([str(os.path.expanduser('~/.forge-api.ini')), str(options.config)])
api_key = options.api_key or config.get('keys', 'api-key')
secret_key = options.secret_key or config.get('keys', 'secret-key')
# print an error message if no keys are found
url = urljoin(options.url or config.get('wiki', 'url'), page)
sign = Signer(secret_key, api_key)
params = sign(urlparse(url).path, [('text', markdown)])
try:
result = urlopen(url, urlencode(params))
stdout.write(result.read())
except HTTPError, e:
stdout.write(e.read())
if __name__ == '__main__':
main()