示例#1
0
class Users:
    """ Класс управления пользовательскими данными """
    ds = None

    def __init__(self):
        """ инициализация источника данных """
        self.ds = Datasource()
        self.ds.switch_datasource('users')

    def get_active_accounts(self, fin_id=0):
        """ возвращает массив с параметрами пользовательских аккаунтов """
        return self.ds.get_accounts({
            'A.disabled': 0,
            'F.disabled': 0,
            'A.fin_id': fin_id
        })
示例#2
0
#!/usr/bin/env python
#-*-coding:utf-8-*-
""" Загружаем историю торгов """

import sys
import init
from datasource import Datasource

ds = Datasource()
ds.switch_datasource('request')

if len(sys.argv) != 3:
    print(
        "Укажите fin_id и файл с исходниками торгов: \"update.py fin_id source_file\""
    )
    for row in ds.get_finances({'disabled =': 0}):
        print("{rate_category_name} \t{curr_name}: \t{fin_id}".format(**row))
    quit()

fin_id = int(sys.argv[1])
if len(ds.get_finances({'disabled =': 0, 'fin_id =': fin_id})) != 1:
    print("В БД нет записи fin_id = {}".format(fin_id))
    quit()

import os

file_name = str(sys.argv[2])
if not os.path.isfile(file_name):
    print("Не найден файл \"{}\"".format(file_name))
    quit()
示例#3
0
class Manager:
	""" Класс управления запросами """
	smtp_config = None

	ds = None
	interface = None

	def __init__(self):
		""" инициализация источника данных """
		self.ds = Datasource()
		self.ds.switch_datasource('report')
	
	@classmethod
	def set_report_configs(cls, configs = {} ):
		""" Регистрация конфигурации способа отчёта """
		cls.smtp_config = configs # TODO предусмотреть возможность хранения множества конфигураций

	def get_reports(self):
		""" возвращает массив объектами отчётов """
		messages = self.ds.get_messages({'send_ts': None})
		return [SmtpReportClient(self, row) for row in messages]

	def set_report(self, account, event_type):
		""" Формируе сообщение в БД """ 
		recepient = account['user_email']
		subject = account['curr_name'] + ' ' + event_type['type_descr']
		if event_type['type_name'] == 'downtrend':
			body = """
{:%Y.%m.%d %H:%M}
Тип: {}\tВалюта: {}\tЦена: {}
Это больше чем {} на вкладе {} с объемом {}.
			""".format(
				datetime.datetime.now(),

				event_type['type_descr'],
				account['curr_name'],
				event_type['buy_price'],

				account['curr_price'],
				account['curr_name'],
				account['curr_volume']
			)
		else:
			body = """
{:%Y.%m.%d %H:%M}
Тип: {}\tВалюта: {}\tЦена: {}
Это меньше чем {} на вкладе {} с объемом {}.
			""".format(
				datetime.datetime.now(),

				event_type['type_descr'],
				account['curr_name'],
				event_type['sell_price'],

				account['curr_price'],
				account['curr_name'],
				account['curr_volume']
			)
		return self.ds.insert_message({'recepient': recepient, 'subject': subject, 'body': body, 'created_ts': int(datetime.datetime.now().timestamp())})


	def get_smtp_config(self):
		""" возвращает параметры SMTP соединения """
		return self.smtp_config

	def confirm_report_error(self, message_id: int = None):
		""" Подтверждение отправки отчёта """
		return self.ds.update_message({'send_ts': int(datetime.datetime.now().timestamp())}, {'message_id': message_id})
	
	def set_report_error(self, report_id: int = None, error = 'uncknown error'):
		""" Регистрируется ошибка полученная при отправке отчёта """
		# =============== код для проверки всей фигни =============== #
		print("set_report_error report_id: {}, error: \"{}\"".format(report_id, error))
		# =============== код для проверки всей фигни =============== #
		pass
示例#4
0
#!/usr/bin/env python
#-*-coding:utf-8-*-
""" Модуль проверки кода """

import init

from datasource import Datasource

ds = Datasource()
ds.switch_datasource('stat')

for fin_row in ds.get_finances({'disabled =': 0}):
    [top_rate] = ds.get_top_rate({'RL.fin_id': fin_row['fin_id']})
    top_rate['event_dt_dispaly'] = top_rate['event_dt'].strftime(
        '%Y.%m.%d %H:%M:%S')
    top_rate['change_percent'] = ds.get_change_percent(fin_row['fin_id'])
    print(
        "{event_dt_dispaly} {curr_name} \tbuy: {buy_price} \tsell: {sell_price}\tchange percent: {change_percent:+05.2f}%"
        .format(**top_rate))