Python 3.1 twitter post with installed library,
Question: I'd like to be able to post twitter messages from python 3.0. None of the
twitter API I have looked at support python 3.1. Since the post proceedure
only requires this :

    
    
    JSON: curl -u username:password -d status="your message here" http://api.twitter.com/1/statuses/update.json 
    

I was wondering if it is possible with the standard libraries to format this
so a message could be sent. My head says it should be possible.


Answer: Try this:

    
    
    import urllib.request
    import urllib.parse
    import base64
    
    def encode_credentials(username, password):
        byte_creds = '{}:{}'.format(username, password).encode('utf-8')
        return base64.b64encode(byte_creds).decode('utf-8')
    
    def tweet(username, password, message):
        encoded_msg = urllib.parse.urlencode({'status': message})
        credentials = encode_credentials(username, password)
        request = urllib.request.Request(
             'http://api.twitter.com/1/statuses/update.json')
        request.add_header('Authorization', 'Basic ' + credentials)
        urllib.request.urlopen(request, encoded_msg)
    

Then call `tweet('username', 'password', 'Hello twitter from Python3!')`.

The
[`urlencode`](http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlencode)
function prepares the message for the `HTTP POST` request.

The
[`Request`](http://docs.python.org/py3k/library/urllib.request.html#urllib.request.Request)
object uses HTTP authentication as explained here:
<http://en.wikipedia.org/wiki/Basic_access_authentication>

The
[`urlopen`](http://docs.python.org/py3k/library/urllib.request.html#urllib.request.urlopen)
methods sends the request to the twitter. When you pass it some data, it uses
`POST`, otherwise `GET`.

This uses only parts of the Python3 standard library. However, if you want to
work with HTTP, you should reconsider using third-party libraries. This [Dive
Into Python 3 chapter](http://diveintopython3.org/http-web-services.html)
explains how and why.

