Skip to content

Commit

Permalink
Merge pull request #19 from andrew4ever/dev
Browse files Browse the repository at this point in the history
Fix issue #17
  • Loading branch information
andrewyazura authored Sep 28, 2020
2 parents 933041d + 22a2014 commit 1ed4493
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 12 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ USERNAME=
PASSWORD=

SESSION_COOKIE_NAME=
MAX_RECORD_DAYS=

# NEW DATABASE URI
SQLALCHEMY_DATABASE_URI='mysql+mysqlconnector://user:pass@host/database'
SQLALCHEMY_DATABASE_URI='mysql+mysqlconnector://user:pass@host/database'
24 changes: 24 additions & 0 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# This workflow will install Python dependencies, run tests and lint with a single version of Python
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions

name: Python application

on: [ push, pull_request ]

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Set up Python 3.8
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Install dependencies
run: |
python -m pip install --upgrade pip
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Run tests
run: |
python -m unittest discover
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ Server is based on **Flask** and few extensions:

Database: **MySQL**

## Executing

First of all, activate virtual environment with:

`source venv/bin/activate`

To start the server run:

`python run.py`

To start tests run:

`python -m unittest tests`

## Credits

All credits to @andrew4ever
25 changes: 17 additions & 8 deletions common/AQICalculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
# In future old backend will be replaced by this new project and aqi calculator will be refactored

import math
from os import environ
from datetime import datetime

import mysql.connector


Expand Down Expand Up @@ -34,13 +37,19 @@ def calculate_aqi(self):
continue

self.cursor.execute(
"SELECT * FROM `sensor_record` WHERE `sensor_id` = {}".format(
"SELECT * FROM `sensor_record` WHERE `sensor_id` = {} ORDER BY `created_at` DESC".format(
sensor[0])
)
record = self.cursor.fetchone()

if record:
if not record:
continue

timedelta = datetime.now() - record[2]

if timedelta.days < int(environ.get('MAX_RECORD_DAYS')):
records.append(record)
print(sensor[0], record)

# arrange records to squares
squares = {}
Expand All @@ -52,6 +61,12 @@ def calculate_aqi(self):

squares[square_center].append(record)

self.cursor.execute("SELECT * FROM `sensor_value_type`")
types = self.cursor.fetchall()
used_ids = [value_type[0]
for value_type in types if value_type[-2] == 1]
types = {value_type[0]: value_type for value_type in types}

# get aqi for each square
for center, records in squares.items():
# prepare dataset
Expand All @@ -61,12 +76,6 @@ def calculate_aqi(self):
"SELECT * FROM `sensor_value` WHERE `record_id` = {}".format(record[0]))
values = self.cursor.fetchall()

self.cursor.execute("SELECT * FROM `sensor_value_type`")
types = self.cursor.fetchall()
used_ids = [value_type[0]
for value_type in types if value_type[-2] == 1]
types = {value_type[0]: value_type for value_type in types}

for value in values:
if value[2] not in used_ids:
continue
Expand Down
4 changes: 2 additions & 2 deletions models/area.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ class AreaModel(db.Model):
)

def __repr__(self):
return '<Area {}>'.format(self._string_coords())
return '<Area {}>'.format(self.string_coords())

def _string_coords(self):
def string_coords(self):
return str(self.latitude) + '-' + str(self.longitude)

def as_dict(self):
Expand Down
2 changes: 1 addition & 1 deletion resources/area.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def get(self):
areas = AreaModel.query \
.filter_by(latitude=latitude) \
.filter_by(longitude=longitude) \
.limit(10).order_by(desc(AreaModel.created)).all()
.order_by(desc(AreaModel.created)).all()

if not areas:
return {'code': 404, 'message': 'Area not found'}, 404
Expand Down
9 changes: 9 additions & 0 deletions resources/map.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from datetime import datetime
from os import environ

from flask_restful import Resource
from sqlalchemy import desc

Expand All @@ -17,6 +20,12 @@ def get(self):
if (a['latitude'], a['longitude']) in areas_coords:
continue

timedelta = datetime.now() - \
datetime.strptime(a['created'], '%Y-%m-%d %H:%M:%S')

if timedelta.days >= int(environ.get('MAX_RECORD_DAYS')):
continue

areas_coords.append((a['latitude'], a['longitude']))
areas_list.append(area.as_dict())

Expand Down
3 changes: 3 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from tests.models.area import AreaModelTest
from tests.resources.area import AreaResourceTest
from tests.resources.map import MapResourceTest
43 changes: 43 additions & 0 deletions tests/models/area.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import unittest

from models import AreaModel


class AreaModelTest(unittest.TestCase):
def test_as_dict(self):
data = {
'aqi': 42,
'latitude': '50.442',
'longitude': '30.91'
}

result = AreaModel(**data).as_dict()
del result['created']
del result['id']

self.assertEqual(result, data)

def test_string_coords(self):
data = {
'aqi': 42,
'latitude': '50.442',
'longitude': '30.91'
}

result = AreaModel(**data).string_coords()

self.assertEqual(result, self.string_coords(data))

def test_repr(self):
data = {
'aqi': 42,
'latitude': '50.442',
'longitude': '30.91'
}

result = str(AreaModel(**data))

self.assertEqual(result, '<Area {}>'.format(self.string_coords(data)))

def string_coords(self, data):
return data['latitude'] + '-' + data['longitude']
7 changes: 7 additions & 0 deletions tests/resources/area.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import unittest

from resources import AreaResource


class AreaResourceTest(unittest.TestCase):
pass
7 changes: 7 additions & 0 deletions tests/resources/map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import unittest

from resources import Map


class MapResourceTest(unittest.TestCase):
pass

0 comments on commit 1ed4493

Please sign in to comment.