我应该在Python类中重构什么?
我对Python相当陌生。这是我的第一节课:我应该在Python类中重构什么?,python,exception-handling,Python,Exception Handling,我对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):
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更新时,出现以下错误:
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.
回溯(最近一次呼叫最后一次):
文件“C:\Users\anlopes\workspace\redes\u sociais\src\twitterC.py”,第42行,在
x、 UpdateWitterStatus({“url”:”http://xxx.com/?cat=49“,”msg“:“正在搜索一些…?”})
文件“C:\Users\anlopes\workspace\redes\u sociais\src\twitterC.py”,第35行,在UpdateWitterStatus中
状态=api.PostUpdate(更新)#Fazer o更新
PostUpdate中的文件“C:\home\u python\python\u virtualenv\lib\site packages\twitter.py”,第2549行
自我检查(数据)
文件“C:\home\u python\python\u virtualenv\lib\site packages\twitter.py”,第3484行,在checkfortwitterrorr中
引发TwitterError(数据['error'])
twitter.TwitterError:状态重复。
例如,如何在Python中捕获此错误
需要一些线索
非常感谢,正如输出清楚地表明的那样,您的代码引发了twitter.TwitterError异常。你像这样抓住它:
try:
# yadda yadda
except twitter.TwitterError:
# exception code
else:
# happy flow code, optionally.
finally:
# must-run code, optionally
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
def CreateTable(cursor, args):
cursor.execute("CREATE TABLE IF NOT EXISTS {0};".format(args)) # Make a table
现在,当您编写第一个类时,不知道如何捕获语言中的异常,您不会尝试获取twitter更新并将其保存到数据库中。您可以打印“Hello World!”。去做一个教程:D.输出清楚地表明,您的代码引发了twitter.TwitterError异常。你像这样抓住它:
try:
# yadda yadda
except twitter.TwitterError:
# exception code
else:
# happy flow code, optionally.
finally:
# must-run code, optionally
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
def CreateTable(cursor, args):
cursor.execute("CREATE TABLE IF NOT EXISTS {0};".format(args)) # Make a table
现在,当您编写第一个类时,不知道如何捕获语言中的异常,您不会尝试获取twitter更新并将其保存到数据库中。您可以打印“Hello World!”。去做一个教程:D.重构的第一件事是从类中获取这些代码。它完全没有必要在一个。这应该是一个模块,具有独立的功能 编辑以添加更多解释在Python中,大多数代码自然分组到模块中。当您需要离散实例时,类主要很有用,每个实例都有自己的数据。这里的情况并非如此-您只是将该类用作相关代码的占位符。这就是模块的用途
例如,如果您想对一条Tweet进行建模,该Tweet知道自己的内容以及如何将自己保存到数据库中,那么这确实是OOP的一个很好的用途。但是“与Twitter相关的东西”不是一个类,而是一个模块。重构的第一件事是将这些代码从类中提取出来。它完全没有必要在一个。这应该是一个模块,具有独立的功能 编辑以添加更多解释在Python中,大多数代码自然分组到模块中。当您需要离散实例时,类主要很有用,每个实例都有自己的数据。这里的情况并非如此-您只是将该类用作相关代码的占位符。这就是模块的用途
例如,如果您想对一条Tweet进行建模,该Tweet知道自己的内容以及如何将自己保存到数据库中,那么这确实是OOP的一个很好的用途。但是“与Twitter相关的东西”不是一个类,它是一个模块。一种可能是编写一个连接数据库和断开数据库连接的函数,并在连接期间执行一些操作。它可能看起来像这样:
try:
# yadda yadda
except twitter.TwitterError:
# exception code
else:
# happy flow code, optionally.
finally:
# must-run code, optionally
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
def CreateTable(cursor, args):
cursor.execute("CREATE TABLE IF NOT EXISTS {0};".format(args)) # Make a table
现在,Func
和args
参数实际上对数据库进行交互。例如,类似这样的事情:
try:
# yadda yadda
except twitter.TwitterError:
# exception code
else:
# happy flow code, optionally.
finally:
# must-run code, optionally
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
def CreateTable(cursor, args):
cursor.execute("CREATE TABLE IF NOT EXISTS {0};".format(args)) # Make a table
现在,如果您希望创建一个表,您只需进行以下调用:
f = DBFactory()
f.DBConnection(CreateTable, "twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT)"
您可以类似地继续与数据库的其他交互,例如插入或删除条目。每次调用DBConnection
方法时。这将更好地模块化您的类。至少在我看来是这样
请注意,我没有尝试上面的代码,所以可能有一个输入错误,但我希望你能理解。我希望这对你有帮助
切里奥Woltan一种可能是编写一个连接数据库和断开数据库连接的函数,并在连接期间执行一些操作。它可能看起来像这样:
try:
# yadda yadda
except twitter.TwitterError:
# exception code
else:
# happy flow code, optionally.
finally:
# must-run code, optionally
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
def CreateTable(cursor, args):
cursor.execute("CREATE TABLE IF NOT EXISTS {0};".format(args)) # Make a table
现在,Func
和args
参数实际上对数据库进行交互。例如,类似这样的事情:
try:
# yadda yadda
except twitter.TwitterError:
# exception code
else:
# happy flow code, optionally.
finally:
# must-run code, optionally
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
def CreateTable(cursor, args):
cursor.execute("CREATE TABLE IF NOT EXISTS {0};".format(args)) # Make a table
现在,如果您希望创建一个表,您只需进行以下调用:
f = DBFactory()
f.DBConnection(CreateTable, "twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT)"
您可以类似地继续与数据库的其他交互,例如插入或删除条目。每次调用DBConnection
方法时。这将更好地模块化您的类。至少在我看来是这样
请注意,我没有尝试上面的代码,所以可能有一个输入错误,但我希望你能理解。我希望这对你有帮助
切里奥沃尔坦那是你的头等舱吗?像凡人一样用语言热身:你说的“当我尝试复制Twitter更新时”是什么意思?除了你显示的代码之外,你还在做什么?我看不到有人试图在这段代码中复制任何东西。这应该是开着的吗?很抱歉没有解释清楚。当我两次发送相同的更新时,twitter包会引发一个异常。我不想把这个作为警告发送到数据库。这是你的第一堂课吗?像凡人一样用语言热身:你说的“当我尝试复制Twitter更新时”是什么意思?除了你显示的代码之外,你还在做什么?我看不到有人试图在这段代码中复制任何东西。这应该是开着的吗?很抱歉没有解释清楚。当我两次发送相同的更新时,twitter包会引发一个异常。我不想将此作为警告发送到数据库。为什么您假设André不知道如何在Python中捕获异常@安德烈,是吗?嗯。。。他的问题是“如何在Python中捕获此错误?”。除非这意味着避免错误或其他什么,。。。o