我正在編寫一個簡單的Python Web應用程序,它由多個爲iPhone格式化的業務數據頁組成。我很喜歡編程Python,但我對Python的「成語」並不是很熟悉,特別是在類和對象方面。 Python的面向對象設計與我所使用的其他語言有所不同。所以,儘管我的應用程序正在運行,但我很好奇是否有更好的方法來實現我的目標。在Python中操作數據庫結果集的最佳實踐?
細節:通常如何在Python中實現request-transform-render數據庫工作流?目前,我使用pyodbc來獲取數據,將結果複製到對象的屬性上,執行一些計算並使用這些對象的列表進行合併,然後從對象列表中呈現輸出。 (下面的示例代碼,SQL查詢編輯。)這是否理智?有沒有更好的辦法?在我對Python的相對無知中有什麼具體的「陷阱」嗎?我特別關心如何使用空的「Record」類實現行列表。
class Record(object):
pass
def calculate_pnl(records, node_prices):
for record in records:
try:
# fill RT and DA prices from the hash retrieved above
if hasattr(record, 'sink') and record.sink:
record.da = node_prices[record.sink][0] - node_prices[record.id][0]
record.rt = node_prices[record.sink][1] - node_prices[record.id][1]
else:
record.da = node_prices[record.id][0]
record.rt = node_prices[record.id][1]
# calculate dependent values: RT-DA and PNL
record.rtda = record.rt - record.da
record.pnl = record.rtda * record.mw
except:
print sys.exc_info()
def map_rows(cursor, mappings, callback=None):
records = []
for row in cursor:
record = Record()
for field, attr in mappings.iteritems():
setattr(record, attr, getattr(row, field, None))
if not callback or callback(record):
records.append(record)
return records
def get_positions(cursor):
# get the latest position time
cursor.execute("SELECT latest data time")
time = cursor.fetchone().time
hour = eelib.util.get_hour_ending(time)
# fetch the current positions
cursor.execute("SELECT stuff FROM atable", (hour))
# read the rows
nodes = {}
def record_callback(record):
if abs(record.mw) > 0:
if record.id: nodes[record.id] = None
return True
else:
return False
records = util.map_rows(cursor, {
'id': 'id',
'name': 'name',
'mw': 'mw'
}, record_callback)
# query prices
for node_id in nodes:
# RT price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone()
rt5 = row.lmp if row else None
# DA price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone()
da = row.da_lmp if row else None
# update the hash value
nodes[node_id] = (da, rt5)
# calculate the position pricing
calculate_pnl(records, nodes)
# sort
records.sort(key=lambda r: r.name)
# return the records
return records
我不認爲ORM是合適的。我不希望寫入數據庫 - 這完全是一個數據顯示項目。並且編寫查詢不是問題(實際上,我打算簡化上面發佈的第一個草稿代碼,以消除查詢在循環問題)。 – 2008-09-22 19:33:50