Login

Signal to post new saved objects to Twitter

Author:
arthurfurlan
Posted:
February 24, 2009
Language:
Python
Version:
1.0
Score:
6 (after 6 ratings)

Post new saved objects to Twitter.

Example:

from django.db import models

class MyModel(models.Model):
    text = models.CharField(max_length=255)
    link = models.CharField(max_length=255)

    def __unicode__(self):
        return u'%s' % self.text

    def get_absolute_url(self):
        return self.link

    # the following method is optional
    def get_twitter_message(self):
        return u'my-custom-twitter-message: %s - %s' % (self.text, self.link)

models.signals.post_save.connect(post_to_twitter, sender=MyModel)
 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
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Arthur Furlan <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# On Debian systems, you can find the full text of the license in
# /usr/share/common-licenses/GPL-2

import os
import twitter
import urllib, urllib2
from django.conf import settings
from django.contrib.sites.models import Site

TWITTER_MAXLENGTH = getattr(settings, 'TWITTER_MAXLENGTH', 140)

def post_to_twitter(sender, instance, *args, **kwargs):
    """ 
    Post new saved objects to Twitter.

    Example:
        from django.db import models

        class MyModel(models.Model):
            text = models.CharField(max_length=255)
            link = models.CharField(max_length=255)

            def __unicode__(self):
                return u'%s' % self.text

            def get_absolute_url(self):
                return self.link

            # the following method is optional
            def get_twitter_message(self):
                return u'my-custom-twitter-message: %s - %s' \
                        % (self.text, self.link)

        models.signals.post_save.connect(post_to_twitter, sender=MyModel)
    """

    # avoid to post the same object twice
    if not kwargs.get('created'):
        return False

    # check if there's a twitter account configured
    try:
        username = settings.TWITTER_USERNAME
        password = settings.TWITTER_PASSWORD
    except AttributeError:
        print 'WARNING: Twitter account not configured.'
        return False

    # if the absolute url wasn't a real absolute url and doesn't contains the
    # protocol and domain defineds, then append this relative url to the domain
    # of the current site, emulating the browser's behaviour
    url = instance.get_absolute_url()
    if not url.startswith('http://') and not url.startswith('https://'):
        domain = Site.objects.get_current().domain
        url = u'http://%s%s' % (domain, url)

    # tinyurl'ze the object's link
    create_api = 'http://tinyurl.com/api-create.php'
    data = urllib.urlencode(dict(url=url))
    link = urllib2.urlopen(create_api, data=data).read().strip()

    # create the twitter message
    try:
        text = instance.get_twitter_message()
    except AttributeError:
        text = unicode(instance)

    mesg = u'%s - %s' % (text, link)
    if len(mesg) > TWITTER_MAXLENGTH:
        size = len(mesg + '...') - TWITTER_MAXLENGTH
        mesg = u'%s... - %s' % (text[:-size], link)

    try:
        twitter_api = twitter.Api(username, password)
        twitter_api.PostUpdate(mesg)
    except urllib2.HTTPError, ex:
        print 'ERROR:', str(ex)
        return False

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.