def go_page2(self, event): name = self.inpt_name.GetValue() name = name.replace(' ', '') familia = self.inpt_familia.GetValue() if len(familia) == 0: self.empty_pole() return group = self.inpt_group.GetValue() if len(group) == 0: self.empty_pole() return zach_number = self.inpt_zachetka.GetValue() zach_number = zach_number.replace(' ', '') if len(zach_number) == 0: self.empty_pole() return fio = str(familia).lower() + ' ' + str(name).lower() new_session = Session() if new_session.query(exists().where(Student.fname == fio). where(Student.group == group).where(Student.zach_number == zach_number)).scalar(): print("ЗАГРУЖАЮ ВАШЕ ЗАДАНИЕ") else: print("пора занести вас в базу и придумать для вас задание") student = Student(fname=fio, group=group, zach_number=zach_number) new_session.add(student) new_session.commit() from gui import SecondPage SecondPage.SecondPage.OnInit(SecondPage) self.Destroy()
def create_appointment(date, time, email): try: session = Session() if not check_is_past_time(date, time): raise DWDCantCreateAppointmentBeforeException( CANT_CREATE_APPOINTMENT_BEFORE_MESSAGE.format( date=date.strftime(DATE_FORMAT), time=time, email=email, )) previous_appointment = session.query(Appointment).filter( and_( Appointment.date == date, Appointment.time == time, Appointment.is_deleted == False, )).one_or_none() if previous_appointment is not None: raise DWDDuplicateAppointmentException( DUPLICATE_APPOINTMENT_MESSAGE.format( appointment=previous_appointment, )) now = datetime.now() action = session.query(Action).filter(Action.name == CREATE).one() appointment = Appointment(date, time, email) log = Log(now, appointment, action, None, None, None, date, time, email) session.add(appointment) session.add(log) session.commit() except DanceWithDeathException as dwde: raise dwde except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) message = ' '.join(line for line in lines) _log.error(message) raise DWDCantCreateAppointmentException( CANT_CREATE_APPOINTMENT_MESSAGE.format( date=date.strftime(DATE_FORMAT), time=time, email=email, )) finally: session.close() return get_times(date), date.strftime(DATE_FORMAT)
def get_times(date): time_dict = { tm: { ENABLED: check_is_past_time(date, tm) if check_date_range(date) else False, APPOINTMENT: None } for tm in range(MIN_TIME, MAX_TIME + 1) } session = Session() now = datetime.now() try: action = session.query(Action).filter(Action.name == LIST).one() appointments = session.query(Appointment).filter( and_( Appointment.date == date, Appointment.is_deleted == False, )).all() for appointment in appointments: time_dict[appointment.time][APPOINTMENT] = { ID: appointment.id, DATE: appointment.date.strftime(DATE_FORMAT), TIME: appointment.time, EMAIL: appointment.email, } log = Log(now, None, action, None, None, None, date, None, None) session.add(log) session.commit() except pymysqlOperationalError as poe: raise DWDBrokenPipeError(BROKEN_PIPE_ERROR_MESSAGE) except sqlalchemyOperationalError as soe: raise DWDBrokenPipeError(BROKEN_PIPE_ERROR_MESSAGE) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) message = ' '.join(line for line in lines) _log.error(message) raise DWDCantListAppointmentsException( CANT_LIST_APPOINTMENTS_MESSAGE.format( date=date.strftime(DATE_FORMAT), )) finally: session.close() return time_dict
def fetch_emails(creds, max_results, fetch_label): """ Fetches a list of emails from the authenticated user's mail ---------------------------------- arguments: - creds: oauth token object - fetch_label: label for filtered fetch """ service = build('gmail', 'v1', credentials=creds) include_spam_trash = False if ('SPAM' in fetch_label or 'TRASH' in fetch_label): include_spam_trash = True result = service.users().messages().list( userId='me', labelIds=fetch_label, maxResults=max_results, includeSpamTrash=include_spam_trash).execute() message_ids = result.get('messages', []) if not message_ids: print(f'No new {fetch_label} messages!') else: print(f'{len(message_ids)} {fetch_label} messages were fetched!') s = Session() count = 0 for message_id in message_ids: result = service.users().messages().get( userId='me', id=message_id['id'], format='metadata').execute() headers = result['payload']['headers'] record = {'message_id': result['id'], 'labels': result['labelIds']} for header in headers: if header['name'] == 'From': record['sender'] = header['value'] elif header['name'] == 'To': record['recipient'] = header['value'] elif header['name'] == 'Subject': record['subject'] = header['value'] elif header['name'] == 'Date': record['date'] = parser.parse(header['value']).date() message = Message(**record) q = s.query(Message).filter_by(message_id=message.message_id) if not s.query(q.exists()).scalar(): s.add(message) count += 1 s.commit() s.close() print(f'{count} new {fetch_label} messages were added to the db!')
def delete_appointment(id): try: session = Session() now = datetime.now() action = session.query(Action).filter(Action.name == DELETE).one() appointment = session.query(Appointment).filter( Appointment.id == id).one() date = appointment.date time = appointment.time if not check_is_past_time(date, time): raise DWDCantDeleteAppointmentBeforeException( CANT_DELETE_APPOINTMENT_BEFORE_MESSAGE.format( appointment=appointment, )) log = Log(now, appointment, action, appointment.date, appointment.time, appointment.email) appointment.is_deleted = True session.add(log) session.commit() except DanceWithDeathException as dwde: raise dwde except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) message = ' '.join(line for line in lines) _log.error(message) raise DWDCantDeleteAppointmentException( CANT_DELETE_APPOINTMENT_MESSAGE.format(id=id, )) finally: session.close() return get_times(date), date.strftime(DATE_FORMAT)
def hacer_usuario_y_ejemplo(): db_session = Session() usuario = Usuario(nombre="Cosme Fulanito") db_session.add(usuario) db_session.commit() print usuario.id evento1 = Evento(organizador=usuario.nombre, nombre="Evento uno", descripcion="Me gustaria poder organizar una juntada", fecha=datetime.date.today(), asistiran=0, organizador_id=usuario.id) evento2 = Evento(organizador=usuario.nombre, nombre="Evento dos", descripcion="Hagamos tambien otra juntada mas", fecha=datetime.date.today(), asistiran=0, organizador_id=usuario.id) print evento1.organizador_id db_session.add(evento1) db_session.add(evento2) db_session.commit() session['usuario_id'] = usuario.id
def hacer_usuario_y_ejemplo(): db_session = Session() usuario = Usuario(nombre="Cosme Fulanito") db_session.add(usuario) db_session.commit() print usuario.id evento1 = Evento(organizador=usuario.nombre, nombre="Evento uno", descripcion="Me gustaria poder organizar una juntada", fecha=datetime.date.today(), asistiran=0, organizador_id=usuario.id) evento2 = Evento(organizador=usuario.nombre, nombre="Evento dos", descripcion="Hagamos tambien otra juntada mas", fecha=datetime.date.today(), asistiran=0, organizador_id=usuario.id) print evento1.organizador_id db_session.add(evento1) db_session.add(evento2) db_session.commit() session['usuario_id'] = usuario.id
def update_appointment(id, new_date, new_time, new_email): try: session = Session() now = datetime.now() action = session.query(Action).filter(Action.name == UPDATE).one() appointment = session.query(Appointment).filter( Appointment.id == id).one() old_date = appointment.date old_time = appointment.time old_email = appointment.email if not check_is_past_time(old_date, old_time): raise DWDCantUpdateAppointmentBeforeException( CANT_UPDATE_APPOINTMENT_BEFORE_MESSAGE.format( appointment=appointment, )) if new_date is None: new_date = old_date if new_time is None: new_time = old_time if new_email is None: new_email = old_email previous_appointment = session.query(Appointment).filter( and_( Appointment.date == new_date, Appointment.time == new_time, Appointment.is_deleted == False, )).one_or_none() if previous_appointment is not None and previous_appointment != appointment: raise DWDDuplicateAppointmentException( DUPLICATE_APPOINTMENT_MESSAGE.format( appointment=previous_appointment, )) log = Log(now, appointment, action, old_date, old_time, old_email, new_date, new_time, new_email) appointment.date = new_date appointment.time = new_time appointment.email = new_email session.add(log) session.commit() except DanceWithDeathException as dwde: raise dwde except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) message = ' '.join(line for line in lines) _log.error(message) raise DWDCantUpdateAppointmentException( CANT_UPDATE_APPOINTMENT_MESSAGE.format( id=id, date=new_date.strftime(DATE_FORMAT), time=time, email=email, )) finally: session.close() return get_times(new_date), new_date.strftime(DATE_FORMAT)
def update_accounts_balances(tgbot): config_json_rpc_api_url = get_config_value('BLOCKCHAINPOLLER', 'json_rpc_api_url') config_json_rpc_api_port = int( get_config_value('BLOCKCHAINPOLLER', 'json_rpc_api_port')) json_rpc_api_url = 'localhost' if config_json_rpc_api_url is None else config_json_rpc_api_url json_rpc_api_port = 8545 if config_json_rpc_api_port is None else config_json_rpc_api_port try: ether_stock_price_request = requests.get( 'https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=EUR') ether_stock_price = ether_stock_price_request.json()[0] except (requests.ConnectionError, IndexError): return else: if ether_stock_price_request.status_code != 200: # try next time if there is network error return session = Session() accounts_queryset = session.query(Account).options(eagerload( Account.chats)).all() for account in accounts_queryset: post_json = { 'jsonrpc': '2.0', 'method': 'eth_getBalance', 'params': ['{}'.format(account.id), 'latest'], 'id': 1 } account_balance = requests.post('http://{}:{}'.format( json_rpc_api_url, json_rpc_api_port), json=post_json).json() old_balance = session.query(AccountBalance).filter_by( account_id=account.id).order_by(AccountBalance.id.desc()).first() if 'error' not in account_balance: new_balance = int(account_balance['result'], 16) if old_balance is None or new_balance != old_balance.balance: changed_value = new_balance if old_balance is None else ( new_balance - old_balance.balance) / 10**18 changed_in_money = { 'EUR': changed_value * float(ether_stock_price['price_eur']), 'USD': changed_value * float(ether_stock_price['price_usd']) } new_account_balance = AccountBalance( account_id=account.id, balance=new_balance, change_in_money=changed_in_money) session.add(new_account_balance) session.commit() if old_balance is not None: for chat in account.chats: if chat.subscription_active: tgbot.send_message( chat_id=chat.id, text='{} UTC - 1 ETH = ${} / €{}\n' 'Account {} balance changed {} ETH.\n' 'Value ${} / €{}'.format( str(datetime.utcnow()), round( float(ether_stock_price['price_usd']), 2), round( float(ether_stock_price['price_eur']), 2), account.id, changed_value, round(changed_in_money["USD"], 3), round(changed_in_money["EUR"], 3))) session.close()