send_to_twitter.py tidak dapat dijalankan ?

Catatan : Error ini terjadi jika menggunakan Python 3.2.2

Kode yang ditulis pada buku

import urllib.request

def send_to_twitter():

msg = "Test, send from python :)"

password_manager = urllib.request.HTTPPasswordMgr()

password_manager.add_password("Twitter API",

"http://twitter.com/statuses", "...", "...")

http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)

page_opener = urllib.request.build_opener(http_handler)

urllib.request.install_opener(page_opener)

params = urllib.parse.urlencode( {'status': msg} )

resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)

resp.read()


send_to_twitter()

Error :

Traceback (most recent call last):

File "send_to_twitter.py", line 15, in <module>

send_to_twitter()

File "send_to_twitter.py", line 12, in send_to_twitter

resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)

File "/usr/lib/python3.2/urllib/request.py", line 138, in urlopen

return opener.open(url, data, timeout)

File "/usr/lib/python3.2/urllib/request.py", line 367, in open

req = meth(req)

File "/usr/lib/python3.2/urllib/request.py", line 1066, in do_request_

raise TypeError("POST data should be bytes"

TypeError: POST data should be bytes or an iterable of bytes. It cannot be str.

Untuk mengatasi masalah kita bisa melakukan encoding pada variabel params, sehingga kode diatas menjadi seperti berikut :

import urllib.request

def send_to_twitter():

msg = "Test, send from python :)"

password_manager = urllib.request.HTTPPasswordMgr()

password_manager.add_password("Twitter API",

"http://twitter.com/statuses", "...", "...")

http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)

page_opener = urllib.request.build_opener(http_handler)

urllib.request.install_opener(page_opener)

params = urllib.parse.urlencode( {'status': msg} )

params = params.encode('utf8')

resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)

resp.read()


send_to_twitter()

Tapi lagi-lagi terjadi errro :

Traceback (most recent call last):

File "send_to_twitter.py", line 16, in <module>

send_to_twitter()

File "send_to_twitter.py", line 13, in send_to_twitter

resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)

File "/usr/lib/python3.2/urllib/request.py", line 138, in urlopen

return opener.open(url, data, timeout)

File "/usr/lib/python3.2/urllib/request.py", line 375, in open

response = meth(req, response)

File "/usr/lib/python3.2/urllib/request.py", line 487, in http_response

'http', request, response, code, msg, hdrs)

File "/usr/lib/python3.2/urllib/request.py", line 413, in error

return self._call_chain(*args)

File "/usr/lib/python3.2/urllib/request.py", line 347, in _call_chain

result = func(*args)

File "/usr/lib/python3.2/urllib/request.py", line 495, in http_error_default

raise HTTPError(req.full_url, code, msg, hdrs, fp)

urllib.error.HTTPError: HTTP Error 401: Unauthorized

Hal ini terjadi, karena Twitter sudah tidak mendukung Basic Authentication sejak 16 Agustus 2010 , sesudah buku Head First Programming diterbitkan [2].

Untuk mengatasi masalah ini, Anda dapat menggunakan tweepy, tapi sayang tweepy pada [3] belum mendukung Python 3.x. Tapi jangan khawatir, ternyata sudah sahabat disana yang sudah memporting Tweepy agar dapat berjelan di Python 3.x [3]

Sehingga kode diatas menjadi seperti berikut :

import tweepy

def send_to_twitter(msg):

CONSUMER_KEY = '...'

CONSUMER_SECRET = '...'

ACCESS_KEY = '...'

ACCESS_SECRET = '...'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)

auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

api = tweepy.API(auth)

api.update_status(msg)

send_to_twitter('Post from python')

Untuk informasi lebih lengkap bagaimana cara mengakses Twitter dari command line via Python, silahkan baca [5].

Referensi