Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4123082
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T23:33:55+00:00 2026-05-20T23:33:55+00:00

I’m fairly new to Python. And this is my first class: import config #

  • 0

I’m fairly new to Python. And this is my first class:

import config   # Ficheiro de configuracao
import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python

class TwitterC:
    def logToDatabase(self, tweet, timestamp):
        # Will log to the database
        database      = sqlite3.connect('database.db') # Create a database file
        cursor        = database.cursor() # Create a cursor
        cursor.execute("CREATE TABLE IF NOT EXISTS twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT);") # Make a table
        # Assign the values for the insert into
        msg_ins       = tweet
        timestamp_ins = timestamp
        values        = [msg_ins, timestamp_ins]
        # Insert data into the table
        cursor.execute("INSERT INTO twitter(tweet, timestamp) VALUES(?, ?)", values)
        database.commit() # Save our changes
        database.close() # Close the connection to the database

    def shortUrl(self, url):
        bit = bitly_api.Connection(config.bitly_username, config.bitly_key) # Instanciar a API
        return bit.shorten(url) # Encurtar o URL

    def updateTwitterStatus(self, update): 
        short   = self.shortUrl(update["url"]) # Vou encurtar o URL
        update  = update["msg"] + short['url']
        # Will post to twitter and print the posted text
        api     = twitter.Api(consumer_key=config.consumer_key, 
                                   consumer_secret=config.consumer_secret, 
                                   access_token_key=config.access_token_key, 
                                   access_token_secret=config.access_token_secret)
        status  = api.PostUpdate(update) # Fazer o update
        msg     = status.text # Vou gravar o texto enviado para a variavel 'msg'
        # Vou gravar p a Base de Dados
        self.logToDatabase(msg, time.time())
        print msg # So p mostrar o texto enviado. Comentar esta linha de futuro.

x = TwitterC()
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=49", "msg": "Searching for some ....? "})

My question. What should I refactor in this ugly code(I think)?

For example. When I try do duplicate a Twitter Update I got this error:

Traceback (most recent call last):
  File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 42, in <module>
    x.updateTwitterStatus({"url": "http://xxx.com/?cat=49", "msg": "Searching for some ...? "})
  File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 35, in updateTwitterStatus
    status  = api.PostUpdate(update) # Fazer o update
  File "C:\home_python\python_virtualenv\lib\site-packages\twitter.py", line 2549, in PostUpdate
    self._CheckForTwitterError(data)
  File "C:\home_python\python_virtualenv\lib\site-packages\twitter.py", line 3484, in _CheckForTwitterError
    raise TwitterError(data['error'])
twitter.TwitterError: Status is a duplicate.

How can I for example catch this error in Python?

Some clues needed.

Best Regards,

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T23:33:56+00:00Added an answer on May 20, 2026 at 11:33 pm

    One possibility would be to write a function that connects to and disconnects from the database and during the connection time does some stuff. It could look something like this:

    class DBFactory(object):
        def DBConnection(self, Func, args):
            database      = sqlite3.connect('database.db') # Create a database file
            cursor        = database.cursor() # Create a cursor
    
            Func(cursor, args)
    
            database.commit() # Save our changes
            database.close() # Close the connection to the database
    

    Now the Func and args parameter actually do the interaction to the database. For example something like this:

    def CreateTable(cursor, args):
        cursor.execute("CREATE TABLE IF NOT EXISTS {0};".format(args)) # Make a table
    

    Now if you wish to create a table you simple have to make this call:

    f = DBFactory()
    f.DBConnection(CreateTable, "twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT)"
    

    You can proceed similarly with other interactions to the database for example inserting or deleting entries. Each time calling the DBConnection method. This should modularize your class a little better. At least in my opinion.

    Please note that I did not give this code above a try, so there might be a typo in there, but I hope you get the idea. I hope this helped ya

    Cherio
    Woltan

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.