--- a/scripts/wiki-post.py
+++ b/scripts/wiki-post.py
@@ -4,11 +4,54 @@
import hmac, hashlib
from datetime import datetime
import os
-from urllib import urlencode
-from urllib2 import urlopen
+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:
+ if value is None: continue
+ 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):
@@ -34,7 +77,7 @@
(options, args) = op.parse_args()
page = args[0]
- f = open(args[1], 'r') if len(args)>=1 else stdin
+ f = open(args[1], 'r') if len(args)>1 else stdin
markdown = f.read()
config = ConfigParser()
@@ -48,8 +91,11 @@
sign = Signer(secret_key, api_key)
params = sign(urlparse(url).path, [('text', markdown)])
- result = urlopen(url, urlencode(params))
- stdout.write(result.read())
+ try:
+ result = urlopen(url, urlencode(params))
+ stdout.write(result.read())
+ except HTTPError, e:
+ stdout.write(e.read())
if __name__ == '__main__':
main()