本文整理匯總了Python中db.DB.close方法的典型用法代碼示例。如果您正苦於以下問題:Python DB.close方法的具體用法?Python DB.close怎麽用?Python DB.close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類db.DB
的用法示例。
在下文中一共展示了DB.close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: read_file_paths
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def read_file_paths(self, list_of_projects):
if not os.path.isfile(list_of_projects):
logging.error('File [%s] does not exist!' % list_of_projects )
sys.exit(1)
else:
db = DB(self.DB_user, self.DB_name, self.DB_pass, logging)
try:
proj_paths = set()
with open(list_of_projects) as f:
for line in f:
proj_path = line.replace('\n','')
if not db.project_exists(proj_path):
proj_paths.add( proj_path )
if len(proj_paths) > 0:
logging.info('List of project paths successfully read. Ready to process %s new projects.' % len(proj_paths))
else:
logging.warning('The list of new projects is empty (or these are already on the DB).')
sys.exit(1)
db.close()
return proj_paths
except Exception as e:
logging.error('Error on read_file_paths')
logging.error(e)
db.close()
sys.exit(1)
示例2: __init__
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def __init__(self, file_list_projects):
self.target_folders = str(time.time())
# Creating folder for the processes logs
self.logs_folder = os.path.join(self.PATH_logs,self.target_folders)
if os.path.exists( self.logs_folder ):
logging.error('Folder [%s] already exists!' % self.logs_folder )
sys.exit(1)
else:
os.makedirs(self.logs_folder)
# Create folder for processes output
self.output_folder = os.path.join(self.PATH_output,self.target_folders)
if os.path.exists( self.output_folder ):
logging.error('Folder [%s] already exists!' % self.output_folder )
sys.exit(1)
else:
os.makedirs(self.output_folder)
# Logging code
FORMAT = '[%(levelname)s] (%(asctime)-15s) %(message)s'
logging.basicConfig(level=logging.DEBUG,format=FORMAT)
file_handler = logging.FileHandler( os.path.join(self.logs_folder,'tokenizer.log') )
file_handler.setFormatter(logging.Formatter(FORMAT))
logging.getLogger().addHandler(file_handler)
self.read_config()
db = DB('pribeiro','CPP','pass',logging)
logging.info('Database \''+self.DB_name+'\' successfully initialized')
db.close()
self.proj_paths = self.read_file_paths(file_list_projects)
示例3: History
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
class History():
def __init__(self):
self.db = DB()
self.solves = self.db.load()
def save(self, timer, scramble, mode):
solve = Solve(timer.begin, timer.gettime(), scramble, mode)
self.solves[mode].append(solve)
self.db.insert(solve)
self._last = solve
def deletelast(self):
self.solves[self._last.mode].pop()
self.db.delete(self._last.rowid)
print("Last solve deleted!\n0.00", end="\r")
def set_dnf(self):
self._last.dnf = True
self.db.setflag("dnf", self._last.rowid)
def set_plustwo(self):
self._last.plustwo = True
self.db.setflag("plustwo", self._last.rowid)
def getlast(self, mode, n):
return self.solves[mode][-n:]
def close(self):
self.db.close()
示例4: process_projects
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def process_projects(self, process_num, proj_paths, global_queue):
db = DB(self.DB_user, self.DB_name, self.DB_pass, self.process_logging)
try:
FILE_files_tokens_file = os.path.join(self.output_folder,'files-tokens-'+str(process_num)+'.tokens')
self.filecount = 0
with open(FILE_files_tokens_file, 'a+') as FILE_tokens_file:
p_start = dt.datetime.now()
for proj_path in proj_paths:
self.process_one_project(process_num, proj_path, FILE_tokens_file, db)
p_elapsed = (dt.datetime.now() - p_start).seconds
self.process_logging.info('Process %s finished. %s files in %ss.', process_num, self.filecount, p_elapsed)
# Let parent know
global_queue.put((process_num, self.filecount))
sys.exit(0)
except Exception as e:
self.process_logging.error('Error in process '+str(process_num))
self.process_logging.error(e)
sys.exit(1)
finally:
db.close()
示例5: mult_connect_to_server
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def mult_connect_to_server(addr, conn_num, db_table_name):
""" 對服務器發起異步多連接"""
# 創建conn_num個socket
sockets = [socket.socket() for x in range(conn_num)]
# 將它們都設為非阻塞
map(lambda sock: sock.setblocking(False), sockets)
# 發起連接,並記錄每個socket發起連接的時間(單位為毫秒)
times = {}
for _socket in sockets:
_socket.connect(addr)
times[_socket.fileno()] = {'connect_time':round(time.time() * 1000)}
# 用一個epoll對象來監聽它們
epoller = select.epoll()
map(lambda sock: epoller.register(sock, select.EPOLLIN), sockets)
# 記錄文件描述符號到socket對象的映射
sockets = {sock.fileno:sock for sock in sockets}
# 創建數據訪問對象
db = DB(table_name=db_table_name)
# 輪詢監聽
epoll_loop(epoller, sockets, times, db=db)
db.close()
示例6: save
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def save(self):
try:
db = DB()
except:
return False
for day, games in self.iteritems():
for game in games:
game['home_team_id'] = game['home']['id']
game['home_team_full'] = game['home']['full']
game['home_team_display_code'] = game['home']['display_code']
game['home_probable_id'] = game['home']['probable_id']
game['away_team_id'] = game['away']['id']
game['away_team_full'] = game['away']['full']
game['away_team_display_code'] = game['away']['display_code']
game['away_probable_id'] = game['away']['probable_id']
game['game_date'] = game['game_id'][0:10].replace('/', '-')
if game['game_status'] == 'F':
game['home_score'] = game['home']['result']
game['away_score'] = game['away']['result']
else:
game['home_score'] = None
game['away_score'] = None
del(game['home'])
del(game['away'])
del(game['pitcher'])
sql = 'REPLACE INTO schedule (%s) VALUES (%s)' % (','.join(game.keys()), ','.join(['%s'] * len(game.values())))
db.execute(sql, game.values())
db.close()
示例7: count_players
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def count_players():
"""
Returns the number of players currently registered.
"""
cursor = DB().execute('SELECT COUNT(*) FROM "players"')["cursor"]
total = cursor.fetchone()[0]
cursor.close()
return total
示例8: main
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def main(fileurl, sysarg):
linklist = parse_link(fileurl)
for i in xrange(0,len(linklist)):
if i%10 == sysarg:
gzfiles = parse_gz(linklist[i])
if(len(gzfiles) == 0):
continue
docs = []
for j in xrange(0, len(gzfiles)):
docs.append({'user' : slicelink(gzfiles[j])[0], 'board' : slicelink(gzfiles[j])[1], 'date' : slicelink(gzfiles[j])[2]})
DB['pindb']['user_board_date'].insert_many(docs)
DB.close()
示例9: start_process
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def start_process(input_process, DB_user, DB_name, DB_pass):
db_object = DB(DB_user, DB_name, DB_pass, logging)
try:
for proj_id in input_process:
find_clones_for_project(projectId,db_object,'') # last field is for debug, and can be 'all','final' or '' (empty)
except Exception as e:
print 'Error in clone_finder.start_process'
print e
sys.exit(1)
finally:
db_object.close()
示例10: player_standings
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def player_standings():
"""
Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place, or a player
tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by the database)
name: the player's full name (as registered)
wins: the number of matches the player has won
matches: the number of matches the player has played
"""
query = 'SELECT * FROM "player_standings"'
cursor = DB().execute(query)["cursor"]
standings = cursor.fetchall()
cursor.close()
return standings
示例11: import_pairs_to_DB
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def import_pairs_to_DB(self):
try:
db = DB(self.DB_user, self.DB_name, self.DB_pass, logging)
log_interval = 1000
pair_number = 0
cc_backup_folder = os.path.join(self.PATH_CC,'backup_output')
latest_folder = 0
for folder in os.listdir(cc_backup_folder):
if folder.isdigit():
if int(folder) > latest_folder:
latest_folder = int(folder)
cc_backup_folder = os.path.join(cc_backup_folder,str(latest_folder))
logging.info('Copying CC pairs from %s' % (cc_backup_folder))
for folder in os.listdir(cc_backup_folder):
if folder.startswith('NODE_'):
pairs_file = os.path.join(cc_backup_folder,folder,'queryclones_index_WITH_FILTER.txt')
if os.path.isfile(pairs_file):
logging.info('Reading %s' % pairs_file)
with open(pairs_file,'r') as result:
for pair in result:
pair_number += 1
line_split = pair[:-1].split(',')
db.insert_CCPairs(line_split[0],line_split[1],line_split[2],line_split[3])
if pair_number%log_interval == 0:
logging.info('%s pairs imported to the DB' % (pair_number))
else:
logging.error('File %s not found' % (pairs_file))
db.close()
except Exception as e:
logging.error('Error on TokenizerController.import_pairs_to_DB')
logging.error(e)
示例12: sign_service
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def sign_service():
# 設置程序工作目錄為當前程序所在目錄
set_work_dir()
while True:
if have_signed_already():
sleep_until_tomorrow_sign_time()
if not is_sign_time_now():
sleep_until_today_sign_time()
try:
gold_num = sign()
except TimeoutError:
sleep(5*50)
except RepeatSignError:
sleep_until_tomorrow_sign_time()
else:
db = DB(database='sign_records.db')
db.insert(gold=gold_num)
db.close()
sleep_until_tomorrow_sign_time()
示例13: task
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def task(addr, db_table_name):
""" 向addr發送數據,然後接收數據"""
# 創建socket
sock = socket.socket()
try:
# 發起連接,記錄連接發起的時間
start_conn_time = round(time.time()*1000000)
sock.connect(addr)
# 記錄連接成功的時間
conn_comp_time = round(time.time()*1000000)
# 準備要發送json數據
d = {'start_conn_time': start_conn_time,
'conn_comp_time': conn_comp_time,}
msg = pack_dict(d)
# 記錄發起請求的時間
request_time = round(time.time()*1000000)
# 發送數據
complete_send(sock, msg)
# 開始接收數據
bmsg = complete_recv(sock)
# 關閉socket
sock.close()
# 記錄接收完成的時間
request_comp_time = round(time.time()*1000000)
# 解包數據
d = unpack_bytes(bmsg)
# 將發起請求和請求返回時間插入字典
d['request_time'] = request_time
d['request_comp_time'] = request_comp_time
# 將數據保存到數據庫
db = DB(db_table_name)
db.insert(**d)
db.close()
except socket.error as e:
print(sock.getsockname(),'上連接發生錯誤,', e)
示例14: swiss_pairings
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
def swiss_pairings():
"""
Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a player adjacent
to him or her in the standings.
Returns:
A list of tuples, each of which contains (id1, name1, id2, name2)
id1: the first player's unique id
name1: the first player's name
id2: the second player's unique id
name2: the second player's name
"""
query = 'SELECT * FROM "swiss_pairings"'
cursor = DB().execute(query)["cursor"]
pairings = cursor.fetchall()
cursor.close()
return pairings
示例15: DB
# 需要導入模塊: from db import DB [as 別名]
# 或者: from db.DB import close [as 別名]
from db import DB
database = DB()
try:
if None == database.insert('hello', 'world', 12, 23, 's'):
print("OK")
if None == database.insert('fuck', 'uuuuu', 2, 333, 'b'):
print("OK")
result = database.delete('fuck', 'uuuuu', 'b')
print(result)
result = database.delete('j', 'b', 'c')
print(result)
database.close()
except Exception as e:
print(str(e))