Python 3.1 twitter with library installed,

I want to send twitter messages from python 3.0. None of the twitter APIs I looked at python 3.1 support. Since post-post 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 standard libraries can format this so that a message can be sent. My head says it should be possible.

+3
source share
1 answer

Try the following:

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 function urlencodeprepares a message for the request HTTP POST.

Request HTTP-, : http://en.wikipedia.org/wiki/Basic_access_authentication

urlopen . , POST, GET.

Python3. , HTTP, . Dive Into Python 3 , .

+2

Source: https://habr.com/ru/post/1744925/


All Articles