def show(): date_from = request.args.get('from') date_to = request.args.get('to') order_by = request.args.get('order_by') print(date_from, date_to) try: date_from = datetime.datetime.strptime(date_from, '%Y.%m.%d').date() date_to = datetime.datetime.strptime(date_to, '%Y.%m.%d').date() except ValueError: return jsonify(error="Incorrect date"), 400 except TypeError: return jsonify(error="Date not found"), 400 result = Stat.get_range(date_from, date_to, order_by) result_arr = [] for res in result: date_json = { 'date': res[0].strftime("%Y.%m.%d"), 'views': res[1], 'clicks': res[2], 'cost': res[3], } try: date_json['cpc'] = round(res[3] / res[2], 2) except ZeroDivisionError: date_json['cpc'] = 0 try: date_json['cpm'] = round(res[3] / res[1] * 1000, 2) except ZeroDivisionError: date_json['cpm'] = 0 result_arr.append(date_json) print(result_arr) return jsonify(result=result_arr)
def test_simple_show(self): date1 = datetime.strptime("2021.03.20", '%Y.%m.%d').date() stat = Stat(date=date1, views=100, clicks=50, cost=13.54) db.session.add(stat) date2 = datetime.strptime("2021.03.21", '%Y.%m.%d').date() stat = Stat(date=date2, views=100, clicks=50, cost=13.54) db.session.add(stat) date3 = datetime.strptime("2021.03.22", '%Y.%m.%d').date() stat = Stat(date=date3, views=100, clicks=50, cost=13.54) db.session.add(stat) db.session.commit() result = Stat.get_range(date1, date2, None) self.assertEqual(len(result), 2)