Django Tweepy File
Question: I’m confused about this; instead of writing tweepy codes like-

    
    
    auth=tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    
    api=tweepy.API(auth)
    

In a new python file (IDLE). Can’t we write it in our views.py in django? Or
we should create a new file in django app for the codes?


Answer: I added a twitter_status.py file to my project and from views.py I call the
update_twitter_status() method

twitter_status.py:

    
    
    """
    Adds a tweet to the twitter account in settings.
    
    Login to dev.twitter.com and add a desktop application
    Add the keys and secrets for the added application to the settings file
    
    Requires tweepy to be installed
    https://github.com/joshthecoder/tweepy
    
    """
    from django.conf import settings
    from tweepy import *
    
    class TwitterManager:
        def __get_api_handle(self):
            #Create OAuth object
            auth = OAuthHandler(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET)
    
            #Set access tokens
            auth.set_access_token(settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_TOKEN_SECRET)
    
            #Create API handle
            api = API(auth)
    
            return api
    
        def update_twitter_status(self, message):
    
            api = self.__get_api_handle()
    
            #Send update
            api.update_status(message)
    

Then in my views.py I just call the update_twitter_status(message) method

views.py:

    
    
    from myproject.twitter_status import TwitterManager
    
    def __update_twitter(message):
        twit_mgr = TwitterManager()
        twit_mgr.update_twitter_status(message)
    

Then whenever I want to tweet from my views.py I add this line

    
    
    __update_twitter('I am tweeting')
    

If someone disagree on how I have implemeted the class or methods please I
would be glad to get your feedback.

