我应该在Python类中重构什么?

2024-05-16 12:03:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python相当陌生。这是我的第一堂课:

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 ....? "})

我的问题。在这个难看的代码中我应该重构什么(我想)?在

例如。当我尝试复制Twitter更新时,我遇到了以下错误:

^{pr2}$

例如,如何在Python中捕获此错误?在

需要一些线索。在

谨致问候


Tags: thekeyimportselfapiconfigurlupdate
3条回答

由于输出清楚地说明,您的代码正在引发一个twitter.twitter错误例外情况。你是这样理解的:

try:
    # yadda yadda
except twitter.TwitterError:
    # exception code
else:
    # happy flow code, optionally.
finally:
    # must-run code, optionally

现在,当您编写第一个类时,不知道如何用一种语言捕捉异常,您不会尝试获取twitter更新并将其保存到数据库中。你印的是“你好,世界!”。去做一个教程:D

重构的第一件事是将这些代码从类中取出。它完全没有必要在一起。这应该是一个具有独立功能的模块。在

编辑以添加更多解释在Python中,大多数代码自然地被分组到模块中。类主要用于需要离散实例时,每个实例都有自己的数据。这里不是这样-您只是将类用作相关代码的占位符。这就是模块的用途。在

例如,如果你想为一个Tweet建模,Tweet知道它自己的内容以及如何将自己保存到数据库中,那么OOP确实是一个很好的应用。但是“与Twitter相关的东西”不是一个类,而是一个模块。在

一种可能是编写一个函数来连接和断开与数据库的连接,并在连接期间执行一些操作。它可能看起来像这样:

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

现在,Funcargs参数实际上与数据库进行交互。例如如下:

^{pr2}$

现在,如果要创建一个表,只需调用以下命令:

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

您可以类似地处理与数据库的其他交互,例如插入或删除条目。每次调用DBConnection方法时。这样可以更好地模块化您的类。至少在我看来。在

请注意,我没有尝试上面的代码,所以可能有一个打字错误,但我希望你能理解这个想法。我希望这对你有帮助

切里奥
沃尔坦

相关问题 更多 >