def clean_run(name): session = Session() run = session.query(Run).filter(Run.name==name).first() if run is None: return session.query(Result).filter(Result.run==run).delete(synchronize_session=False) session.commit()
def PUT(self, id): data = web.data() item = json.loads(data) if id == '0': id = None code = item['code'] if ('code' in item) else 'code' title = item['title'] if ('title' in item) else 'title' try: posttime = datetime.datetime.strptime(item['posttime'], '%Y-%m-%d') except (KeyError, ValueError): posttime = datetime.datetime.now() remark = item['remark'] if ('remark' in item) else '' articleobj = ArticleModel(id, code, title, posttime, remark) articledict = { 'code': code, 'title': title, 'posttime': posttime, 'remark': remark } if id: Session.query(ArticleModel).filter( ArticleModel.id == id).update(articledict) else: Session.add(articleobj) Session.commit()
def book_save(_id): status, msg = True, '' b_name = request.args.get('name') s = Session() b = s.query(Book).filter_by(id=_id).first() del b.authors[:] for key, val in request.args.items(): if key == 'name': continue a = s.query(Author).filter_by(id=key).first() b.authors.append(a) b.name = b_name try: s.commit() except IntegrityError: status = False msg = 'The book with name %s already exists' % b_name s.close() return json.dumps({'ok': status, 'msg': msg})
def main_page(): s = Session() meals = s.query(Meal).all() products = s.query(Product).all() s.close() return render_template('beta.html', meals=meals, products=products)
def main_page(): s = Session() books = s.query(Book).all() authors = s.query(Author).all() s.close() return render_template('beta.html', books=books, authors=authors)
def updateAllPlaylist(): print("-" * 10, "Updating all playlists", "-" * 10) session = Session() playlists = session.query(playlistDB).all() for playlist in playlists: print("[*] Playlist name:", playlist.name) songsList = getPlaylist(playlist.nid)["playlist"]["trackIds"] idList = [i["id"] for i in songsList] DBsongsList = session.query(songDB.nid).filter( songDB.playlist.contains(playlist.name)).all() DBidList = [i[0] for i in DBsongsList] addIdList = list(set(idList) - set(DBidList)) delIdList = list(set(DBidList) - set(idList)) delDataList = session.query(songDB).filter( songDB.nid.in_(delIdList)).all() if addIdList: print(" | Adding new songs...") record = addNewSongs(playlist.name, addIdList) print(" | Total {} songs, {} new songs added, {} songs modified.". format(len(idList), record["add"], record["modify"])) if delIdList: print(" | Removing deleted songs...") removePlaylistInSongDB(delDataList) if not addIdList or delIdList: print(" | Nothing to do.") print("[*] All done.") print("") # 好看
def get_parlamentar(self, _name, scope=None): session = Session() if scope is None: parlamentar = session.query(Parlamentar).filter_by(name=_name)[0] mandato = session.query(Mandato).filter_by( parlamentar_id=parlamentar.id)[0] ex = session.query(Exercicio).filter_by( parlamentar_id=parlamentar.id) exercicios = [e for e in ex] dictp = dict(parlamentar=parlamentar, mandato=mandato, exercicios=exercicios) else: qry = session.query(Parlamentar).filter( Parlamentar.name.like('%' + _name + '%')).all() dictp = [] for p in qry: dict_temp = dict() dict_temp['parlamentar'] = p dict_temp['mandato'] = session.query(Mandato).filter_by( parlamentar_id=p.id) dictp.append(dict_temp) return dictp
def get(self): cmt_id = int(self.get_argument('cmt_id')) session = Session() comment = session.query(Comment).get(cmt_id) user = session.query(User).get(comment.user_id) self.render('reply_comment.html', comment=comment, user=user)
def contest(contest_id): session = Session() contest = session.query(Contest).filter(Contest.contest_id == contest_id).first() tasks = session.query(Task).filter(Task.contest_id == contest_id).all() results = session.query(Result).filter(Result.contest_id == contest_id).all() result_hash = {(r.user_id, r.problem_id): r for r in results} user_ids = {r.user_id for r in results} return render_template('contest.jinja2', contest=contest, tasks=tasks, result_hash=result_hash, user_ids=user_ids)
def addInfoToSongs(fileDict, isflacTranscode): # {123233:"123-12323.mp3"} session = Session() imgPath = os.path.join(config.basePath, "images", "album") audioBasePath = os.path.join(config.basePath, "songs") flacTranscodeError = [] threadLoop = [] sem = threading.Semaphore(20) for nid in fileDict: # fileDict[nid][0]: 文件名字;fileDict[nid][1]: 文件类型 songInfo = session.query(songDB).filter( songDB.nid == nid).first().to_dict() albumInfo = session.query(albumDB).filter( albumDB.name == songInfo["album"]).first().to_dict() md5 = hashlib.md5() md5.update(albumInfo["imgSrc"].encode("utf-8")) albumImgSrcHex = md5.hexdigest() filename = albumImgSrcHex + ".jpg" songInfo["imgPath"] = os.path.join(imgPath, filename) songInfo["audioBasePath"] = audioBasePath if fileDict[nid][1] == "mp3": with sem: t = threading.Thread(target=addInfoToMp3, args=( fileDict[nid][0], songInfo, )) t.start() threadLoop.append(t) elif fileDict[nid][1] == "flac": with sem: t = threading.Thread(target=addInfoToFlac, args=( fileDict[nid][0], songInfo, )) t.start() threadLoop.append(t) if isflacTranscode: with sem: t = threading.Thread(target=flacToM4a, args=( fileDict[nid][0], audioBasePath, )) t.start() threadLoop.append(t) else: pass for t in threadLoop: t.join() del threadLoop
def get_list(uuid): session = Session() resp = [] user = session.query(User).filter(User.greenlist_uuid == uuid).one_or_none() for elem in session.query(UserList).filter(UserList.user_id == user.id).all(): resp.append({ "productId": elem.product.id, "name": elem.product.name, "footprint": elem.product.footprint, "image": elem.product.image }) session.close() return resp
def remove_server(server_id , group_id): try : session = Session() server = session.query(Server).filter(Server.id == server_id).first() group = session.query(ServerGroup).filter(ServerGroup.id == group_id).first() if server == None or group == None : return {"status":-1 , "val":None} if server in group.servers : group.servers.remove(server) group.save(session) return {"status":0 , "val":None} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def remove_service(service_id , group_id): try : session = Session() service = session.query(Service).filter(Service.id == service_id).first() group = session.query(ServerGroup).filter(ServerGroup.id == group_id).first() if server == None or group == None : return {"status":-1 , "val":None} if server in group.servers : group.service.remove(service) group.save(session) return {"status":0 , "val":None} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def edit_meal(_id): s = Session() b = s.query(Meal).filter_by(id=_id).first() current_products = b.products products = s.query(Product).all() other_products = [] for a in products: if a not in b.products: other_products.append(a) s.close() return render_template('edit_meal.html', meal=b, other_products=other_products, current_products=current_products)
def edit_book(_id): s = Session() b = s.query(Book).filter_by(id=_id).first() current_authors = b.authors authors = s.query(Author).all() other_authors = [] for a in authors: if a not in b.authors: other_authors.append(a) s.close() return render_template('edit_book.html', book=b, other_authors=other_authors, current_authors=current_authors)
def add_service2group(service_id,group_id): try : session = Session() service = session.query(Service).filter(Service.id == service_id).first() group = session.query(ServerGroup).filter(ServerGroup.id == group_id).first() if service == None or group == None : return {"status":-1 , "val" : None} if service not in group.service : group.services.append(service) group.save(session) return {"status":0 , "val" : None} return {"status":-1 , "val":None} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def delete_task(task_id) : try : session = Session() task = session.query(Task).filter(Task.id == task_id).first() taskStatuss = session.query(TaskStatus).filter(TaskStatus.task_id == task_id).all() for taskStatus in taskStatuss: taskStatus.delete(session) if task == None : return {"status":-1 , "val":None} task.delete(session) return {"status":0 , "val":None} except Exception , msginfo : print msginfo return {"status":-1 , "val":msginfo}
def delete_serverGroup(group_id): session=Session() serverGroup=session.query(ServerGroup).filter(ServerGroup.id==group_id).first() tasknum=session.query(Task).filter(Task.server_group_id==group_id).count() if len(serverGroup.servers): return {'status':-1,'val':'serverGroup still has server in it.'} if tasknum!=0: return {'status':-1,'val':'serverGroup still has been used in task'} try: if serverGroup==None: return {"status":-1,'val':"group is not in db."} serverGroup.delete(session) return {"status":0,"val":None} except Exception,msginfo: return {"status":-1,"val":msginfo}
def do_command (task_id) : try : task_res = get_task_by_id(task_id) if task_res["status"] != 0 : return {"status":-1 , "val":None} task = task_res["val"]["task"] group_id = script_group = task_res["val"]["script_group"].id server_group = task_res["val"]["server_group"] scripts = get_scripts_by_group_id(group_id)["val"] script_list = [] for script in scripts : script_list.append(str(script.location)) server_list = [] for server in server_group.servers : server_list.append(server.dump()) if script_list == [] or server_list == [] : return {"status":-1 , "val":None} task_to_do = {"scripts":script_list , "servers":server_list} success_array , key_code_list = upload_remotefile.do_task(task_to_do) session = Session() taskStatus = session.query(TaskStatus).filter(TaskStatus.task_id == task_id).first() if taskStatus == None : taskStatus = TaskStatus(task_id , json.dumps(success_array) , json.dumps(key_code_list)) taskStatus_id = taskStatus.save_return_id(session) else : taskStatus.success_array = json.dumps(success_array) taskStatus.key_code_list = json.dumps(key_code_list) taskStatus_id = taskStatus.id taskStatus.save(session) session.close() return {"status":0 , "val":taskStatus_id} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def rep_generacional(): session = Session() representantes = [ as_dict(representante) for representante in session.query(Representante).all() ] for indice, representante in enumerate(representantes): asistencias = limpiar_asistencias( session.query(Asistencias).filter( Asistencias.nombre_representante == representante["nombre"]).all()) representantes[indice]["asistencias"] = asistencias session.close() return representantes
def update_position(group_id , json_str) : try : session = Session() position_list = json_str.split('|') position_list.remove(position_list[len(position_list)-1]) for i in range(len(position_list)) : position_list[i] = int(str(position_list[i])) sorted_script = session.query(Sorted_Script).filter(Sorted_Script.group_id == group_id).first() sorted_array = json.loads(sorted_script.sorted_array) check = True for item in position_list : if item not in sorted_array : check = False break if len(position_list) != len(sorted_array) : check = False if check == True : sorted_script.sorted_array = json.dumps(position_list) sorted_script.save(session) return {"status":0 , "val":None} else : return {"status":-1 , "val":None} except Exception , msginfo : return {"status":-1 , "val":msginfo}
class LogHandlerTests(reader.LogHandler): def __init__(self): self.session = Session() self.tests = {(item.test, item.subtest) for item in self.session.query(Test)} self.new_tests = [] def _insert_test(self, test, subtest): if (test, subtest) not in self.tests: test_obj = {"test": test, "subtest": subtest} self.new_tests.append(test_obj) self.tests.add((test, subtest)) def test_status(self, data): test = self._insert_test(data["test"], data["subtest"]) def test_end(self, data): self._insert_test(data["test"], None) sys.stdout.write("-") sys.stdout.flush() def suite_end(self, data): self.session.bulk_insert_mappings(Test, self.new_tests) self.session.commit() sys.stdout.write(" committing\n")
def draw_table(self): s = Session() self.orders = s.query(Order).all() s.close() self.ui.orders_table.clear() self.ui.orders_table.setRowCount(1) self.ui.orders_table.setColumnCount(5) self.ui.orders_table.setHorizontalHeaderLabels([QString.fromUtf8('Номер'), QString.fromUtf8('Поломка'), QString.fromUtf8('Дата приемки'), QString.fromUtf8('Клиент'), QString.fromUtf8('Статус')]) #self.ui.orders_table.resizeColumnsToContents() for order in self.orders: data = [] data.append(str(order.id)) data.append(QString.fromUtf8(order.device)) data.append(str(order.get_ordered_date())) data.append(QString.fromUtf8(order.get_client().get_fio())) data.append(QString.fromUtf8(order.get_status(1).to_string())) for i in range(0,5): tableitem = QTableWidgetItem() tableitem.setText(data[i]) tableitem.font = QFont("Arial", 10) tableitem.font.setBold(True) tableitem.textcolor = QColor("black") self.ui.orders_table.setItem(self.ui.orders_table.rowCount() - 1,i,tableitem) self.ui.orders_table.setRowCount(self.ui.orders_table.rowCount()+1) self.ui.orders_table.resizeColumnsToContents()
def get(username): session = Session() try: return session.query(PlayerData).filter( PlayerData.name == username).one() except: return None
def add_to_list(uuid, product_id, trees_difference): msg = "Success" try: session = Session() user = session.query(User).filter(User.greenlist_uuid == uuid).one_or_none() if session.query(UserList).filter( UserList.user_id == user.id).filter(UserList.product_id == product_id).first() is None: product = session.query(Product).filter(Product.id == product_id).one_or_none() product_to_user = UserList(user, product, trees_difference) session.add(product_to_user) session.commit() session.close() except Exception as e: msg = e finally: return msg
def mythicspoiler_crawl(self, context): local_session = Session() cards = self.ms.get_cards_from_news() for page, image_url, card_set in cards: if image_url not in self.mythicspoiler_futur_cards_url: config.bot_logger.info( f"New card detected from mythicspoiler: {page}") # New card detected on mythic spoiler, save it self.mythicspoiler_futur_cards_url.append(image_url) # Try to see if it has already been spoiled im = Image(location=image_url, descr=im_utils.descript_image(image_url)) if not self.sd.is_duplicate( im, [s.image.descr for s in self.spoiled]): # card not recognize as a duplicate, save then publish it local_session.add(im) sp = Spoiler(url=page, source=SpoilerSource.MYTHICSPOILER.value, source_id=SpoilerSource.MYTHICSPOILER.value, found_at=datetime.now(), set_code=card_set) sp.image = im sp.set = local_session.query(Set).filter( Set.code == card_set).first() local_session.add(sp) self.spoiled.append(sp) self.send_spoiler(sp, context) local_session.commit()
def initialize_device(): """ Set up the Device info into the database. By this time, the HardwareDefinition and SoftwareDefinition entries must be entered. """ session = Session() hd = session.query(HardwareDefinition).one() sd = session.query(SoftwareDefinition).one() device = Device(id=hd.serial_number, interior_sensor=hd.interior_sensor, exterior_sensor=hd.exterior_sensor) device.hardware_version = hd.hardware_version device.software_version = sd.software_version device.database_service = True # database always set to True device.device_service = sd.device_service device.grainbin_service = sd.grainbin_service session.add(device) # set grainbin info if sd.grainbin_service: grainbins = initialize_grainbin(device.id, hd.grainbin_reader_count) device.grainbin_count = len(grainbins) session.add_all(grainbins) session.commit() session.close() return
def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"!status( .*)?", text) if not match: return session = Session() try: realm = session.query(Realm).filter(Realm.name == wowconfig["realm"]).one() status = u"Currently *{0}* is ".format(realm.name) if realm.online: status += "online (last check: {0})".format( humanize.naturaltime(realm.lastchecked) ) status += "\n\n*Battleground status*:\n```" for area in realm.areas: status += "{0} : {1} controlled : {2} : next in {3}\n".format( area.name, area.faction, area.status, humanize.naturaldelta(area.next), ) status += "```" else: status += "offline (last check: {0}, last seen: {1})".format( humanize.naturaltime(realm.lastchecked), humanize.naturaltime(realm.lastseen) ) return status except NoResultFound: return u"No status known on *{0}*".format(wowconfig["realm"])
def syncSeason(self, serie, season): qry = Session.query(Serie).filter_by(path=serie) if qry.count() == 0: raise Exception("No serie linked to %s/%s" % (serie, saison)) serie = qry.one() path = season num = getSeasonNumFromFoldername(season) if num is None: raise Exception("This is not a season (%s)" % season) season = filter(lambda season: season.num == num, serie.seasons) if len(season) == 0: season = Season(num=num, path=path) Session.add(season) serie.seasons.append(season) else: assert 1 == len(season) season = season[0] season.num = num season.path = path episodes = glob(os.path.join(self.basepath, serie.path, season.path, "*")) episodes = filter(lambda episode: os.path.isfile(episode), episodes) for episode in [os.path.basename(e) for e in episodes]: try: self.syncEpisode(serie.path, season.path, episode) except: pass
def scryfall_cards_crawl(self, context): local_session = Session() futur_cards = scryfall.get_futur_cards() for futur_card in futur_cards: if not futur_card.get("id") in self.scryfall_futur_cards_id: config.bot_logger.info( f"New card detected from scryfall: {futur_card.get('name')}" ) # New card detected, add it to scryfall list self.scryfall_futur_cards_id.append(futur_card.get("id")) # Try to see if it has already been spoiled for i_url in scryfall.get_image_urls(futur_card): im = Image(location=i_url, descr=im_utils.descript_image(i_url)) if not self.sd.is_duplicate( im, [s.image.descr for s in self.spoiled]): # card not recognize as a duplicate, save then publish it local_session.add(im) sp = Spoiler(url=scryfall.get_card_url(futur_card), source=SpoilerSource.SCRYFALL.value, source_id=futur_card.get("id"), found_at=datetime.now(), set_code=futur_card.get("set_code", None)) sp.image = im local_session.add(sp) self.spoiled.append(sp) sp.set = local_session.query(Set).filter( Set.code == futur_card.get("set_code")).first() self.send_spoiler(sp, context) local_session.commit()
def new_meal_save(): status, msg = True, '' b_name = request.args.get('name') s = Session() b = Meal(b_name) for key, val in request.args.items(): if key == 'name': continue a = s.query(Product).filter_by(id=key).first() b.products.append(a) s.add(b) try: s.commit() except IntegrityError: status = False msg = 'The meal with name %s already exists' % b_name s.close() return json.dumps({'ok': status, 'msg': msg})
class Connection: execution_options = None def __init__(self, execution_options=None): self.execution_options = execution_options self.s: Optional[Session] = None def __enter__(self): """ create connection object :return: """ self.engine = c.engine Session.configure(bind=self.engine) self.s = Session() if self.execution_options: self.s.connection(execution_options=self.execution_options) return self def __exit__(self, exc_type, exc_val, exc_tb): """ remove session """ Session.remove() def upsert_from_form(self, model_class, form): args_dict = {} for column in model_class.__table__.columns: if hasattr(form, column.name) and getattr(form, column.name).data: # TODO Noneや''の時に更新されない args_dict[column.name] = getattr(form, column.name).data if form.id.data: # update (if form has id) id_ = form.id.data self.s.query(model_class).filter(model_class.id == id_).update( args_dict, synchronize_session=False) else: # create new_model = model_class(**args_dict) self.s.add(new_model) self.s.flush() self.s.refresh(new_model) id_ = new_model.id self.s.commit() return id_
def create_statuses(): session = Session() existing = set(item.name for item in session.query(Status)) for status in ["PASS", "FAIL", "OK", "ERROR", "TIMEOUT", "CRASH", "ASSERT", "SKIP", "NOTRUN"]: if status not in existing: session.add(Status(name=status)) session.commit()
def delete(self, sessionid): s = Session() with s.transaction: session = s.query(CoachingSession).get(sessionid) if session: s.delete(session) else: self.response.set_status(404)
def showAllPlaylist(): session = Session() print("-" * 10, "Show all playlists.", "-" * 10) playlists = session.query(playlistDB).all() print("{}\t{}".format("名字", "网易云id")) for playlist in playlists: print("{}\t{}".format(playlist.name, playlist.nid)) print("") # 好看
def exportXmlPlaylistByName(playlistName): # 从名字导出播放列表 session = Session() print("-" * 10, "Export playlist to xml", "-" * 10) playlist = session.query(songDB).filter( songDB.playlist.contains(playlistName)).all() if not playlist: print("[!] Can not find playlist:", playlistName) print("") # 好看 return print("[*] Playlist name:", playlistName) exten = {} # 因为没有储存下载信息,所以通过此方法获取扩展名。如有更好方法请告知,thanks! for name in os.listdir(os.path.join(config.basePath, "songs")): if os.path.isfile(os.path.join(config.basePath, "songs", name)): exten[os.path.splitext(name)[0]] = os.path.splitext(name)[1] failedListRaw = session.query(downloadLogDB).filter( downloadLogDB.status == 0).all() # url获取失败的条目 failedList = [] for i in failedListRaw: failedList.append(i.nid) songsInfo = [] for songInfoRaw in playlist: songInfo = songInfoRaw.to_dict() if songInfo["nid"] not in failedList: filename = quote( config.getSongFileName(songInfo) + exten[config.getSongFileName(songInfo)]) filePath = "file://localhost/" + os.path.join( config.basePath, "songs", filename).replace( "\\", "/") # iTunes文件路径格式 songInfo["filePath"] = filePath songsInfo.append(songInfo) else: print(" ! Can not add", songInfo["name"], ": No song file downloaded.") playlistInfo = session.query(playlistDB).filter( playlistDB.name == playlistName).first().to_dict() playlistFilename = os.path.join(config.basePath, playlistInfo["name"] + ".xml") makeXmlPlaylist(songsInfo, playlistInfo, playlistFilename) print("[*] iTunes xml playlist saved into:", playlistFilename) print("") # 好看
def add_task2service(task_id,service_id): try : session = Session() task = session.query(Task).filter(Task.id == task_id).first() service = session.query(Service).filter(Service.id == service_id).first() if service == None or service == None : return {"status":-1 , "val" : None} if task not in service.tasks: service.tasks.append(task) service.save(session) if task in service.tasks: service.tasks.remove(task) service.save(session) return {"status":0 , "val" : None} return {"status":-1 , "val":None} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def login(self): s = Session() res = s.query(Staff).filter_by(login=unicode(self.ui.login.text()), passwd=unicode(self.ui.password.text())).all() if len(res): self.mv = MainWindow(res[0]) self.mv.show() self.close() s.close()
def get_script_group_list() : try : session = Session() group_list = session.query(ScriptGroup).all() if group_list == None or len(group_list) == 0 : return {"status":-1 , "val":None} return {"status":0 , "val":group_list} except Exception , msginfo : return {"status": -1 , "val":msginfo}
def get_server_by_id(server_id) : try : session = Session() server = session.query(Server).filter(Server.id == server_id).first() if server == None : return {"status":-1 , "val":None} return {"status":0 , "val":server} except Exception , msginfo : return {"status": -1 , "val":msginfo}
def get_service_group_by_id(group_id) : try : session = Session() group_list = session.query(ServerGroup).all() if group_list == None or len(group_list) == 0 : return {"status":-1 , "val":None} return {"status":0 , "val":group_list} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def get_script_by_id(script_id) : try : session = Session() script = session.query(Script).filter(Script.id == script_id).first() if script == None : return {"status":-1 , "val":None} return {"status":0 , "val":script} except Exception , msginfo : return {"status": -1 , "val":msginfo}
def get_scripts_by_group_id (group_id) : try : session = Session() group = session.query(ScriptGroup).filter(ScriptGroup.id == group_id).first() ss = session.query(Sorted_Script).filter(Sorted_Script.group_id == group_id).first() if group == None or ss == None: return {"status":-1 , "val":None} sa = json.loads(ss.sorted_array) sorted_array = [] tmp_dict = {} for script in group.scripts : script.groups = script.groups tmp_dict[script.id] = script for script_id in sa : sorted_array.append(tmp_dict[script_id]) return {"status":0 , "val":sorted_array} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def get_stored_range(x_min, x_max, y_min, y_max): session = Session() value = session.query(DataMap).filter(and_(DataMap.x >= x_min, DataMap.x <= x_max, \ DataMap.y >= y_min, DataMap.y <= y_max)).all() ret_val = {} for tile in value: ret_val[(tile.x, tile.y)] = tile.value return ret_val
def delete_task(task_id) : try : session = Session() task = session.query(Task).filter(Task.id == task_id).first() if task == None : return {"status":-1 , "val":None} task.delete(session) return {"status":0 , "val":None} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def get_script_group_by_id(group_id) : try : session = Session() group = session.query(ScriptGroup).filter(ScriptGroup.id == group_id).first() group.scripts = group.scripts if group == None : return {"status":-1 , "val":None} return {"status":0 , "val":group} except Exception , msginfo : return {"status": -1 , "val":msginfo}
def get(self): try: user_id = int(self.get_cookie('user_id')) except TypeError: self.redirect('/user/login') session = Session() q_user = session.query(User) user = q_user.filter_by(id=user_id).one() self.render('info.html', user=user)
def remove_script(script_id , group_id): try : session = Session() script = session.query(Script).filter(Script.id == script_id).first() group = session.query(ScriptGroup).filter(ScriptGroup.id == group_id).first() if script == None or group == None : return {"status":-1 , "val":None} if script in group.scripts : group.scripts.remove(script) group.save(session) ss = session.query(Sorted_Script).filter(Sorted_Script.group_id == group_id).first() sorted_array = json.loads(ss.sorted_array) sorted_array.remove(int(script_id)) ss.sorted_array = json.dumps(sorted_array) ss.save(session) return {"status":0 , "val":None} return {"status":-1 , "val":None} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def delete_script(script_id) : try : session = Session() script = session.query(Script).filter(Script.id == script_id).first() if script == None : return {"status":-1 , "val": None} for group in script.groups : ss = session.query(Sorted_Script).filter(Sorted_Script.group_id == group.id).first() sorted_array = json.loads(ss.sorted_array) sorted_array.remove(int(script_id)) ss.sorted_array = json.dumps(sorted_array) ss.save(session) while(len(script.groups)>0) : script.groups.pop() script.save(session) script.delete(session) return {"status":0 , "val":script_id} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def draw_client_combo(self): combo = self.ui.client s = Session() clients = s.query(Client).all() s.close() combo.clear() for cl in clients: combo.addItem('%i %s %s'%(cl.id, cl.surname, cl.name)) #QObject.connect(self.ui.manufacter_combo, SIGNAL("currentIndexChanged(int)"), self.setManufacter) #self.setManufacter(0)
def removePlaylistByName(playlistName): # 删除指定名字的播放列表 session = Session() playlist = session.query(songDB).filter( songDB.playlist.contains(playlistName)).all() print("-" * 10, "Remove playlist", "-" * 10) print("[*] Playlist name:", playlistName) print("[*] Length of playlist:", len(playlist)) playlistInfo = session.query(playlistDB).filter( playlistDB.name == playlistName).delete() session.commit() if not playlist: print("[*] Nothing to do.") print("") # 好看 return removePlaylistInSongDB(playlistName, playlist) print("[*] Done.") print("") # 好看
def get_server_group_by_id(group_id) : try : session = Session() group = session.query(ServerGroup).filter(ServerGroup.id == group_id).first() group.servers = group.servers if group == None : return {"status":-1 , "val":None} return {"status":0 , "val":group} except Exception , msginfo : return {"status": -1 , "val":msginfo}
def cron(): gt = (round(time.time()/86400) - config.NOTICE_PERIOD) * 86400 lt = gt + 86400 article_list = Session.query(ArticleModel).filter(lt <= ArticleModel.posttime, ArticleModel.posttime < gt).all() if article_list: names = "\n".join([article.title for article in article_list]) subject = u"文章到期提醒" content = (u"以下%d篇文章已经到期\n%s" % (len(article_list), names)).replace('\n','<br />\n') send_mail(subject, content, config.NOTICE_NAME, config.NOTICE_MAIL) else: print "no articles to be notify"