Skip to content

Commit fdfb344

Browse files
authored
Merge pull request #279 from mapswipe/dev
v2.1.8
2 parents a1dc9a9 + 8b9a3ae commit fdfb344

31 files changed

+523
-791
lines changed

.travis

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# This is a special configuration file to run tests on Travis-CI via
2+
# GitHub notifications when changes are committed.
3+
#
4+
# For technical details, see http://travis-ci.org/
5+
6+
language: python
7+
python:
8+
- "3.6"
9+
- "3.7"
10+
- "3.8"
11+
12+
before_install:
13+
- pip install --upgrade pip setuptools
14+
- pip install flake8 black
15+
- flake8 --config=mapswipe_workers/setup.cfg mapswipe_workers/mapswipe_workers/*.py
16+
- black --check mapswipe_workers/mapswipe_workers/*.py
17+
18+
install:
19+
- pip install mapswipe_workers/

docker-compose.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ services:
5353
context: mapswipe_workers/
5454
depends_on:
5555
- postgres
56-
command: mapswipe_workers --verbose run --schedule m
56+
command: mapswipe_workers --verbose run --schedule
5757
volumes:
5858
- ./api-data:/var/lib/mapswipe_workers/api-data/:rw
5959
- ./api-data/agg_results:/var/lib/mapswipe_workers/api-data/agg_results:rw

mapswipe_workers/.pre-commit-config.yaml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,3 @@ repos:
77
rev: 3.7.9
88
hooks:
99
- id: flake8
10-
args: ["--ignore=E501,W503"]

mapswipe_workers/Dockerfile

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1-
# This image contains Python 3 and the latest pre-compiled version of GDAL
2-
# Based on Debian (Including apt-get update && upgrade)
3-
FROM thinkwhere/gdal-python:3.7-shippable
1+
# https://github.com/OSGeo/gdal/tree/master/gdal/docker
2+
# Image includes python3.6, gdal-python, gdal-bin
3+
FROM osgeo/gdal:ubuntu-small-latest
44

5-
# Install gdal-bin to get ogr2ogr tool
5+
ENV LC_ALL=C.UTF-8
6+
ENV LANG=C.UTF-8
7+
8+
# Install pip
69
RUN apt-get update
7-
RUN apt-get --yes install gdal-bin
10+
RUN apt-get --yes install python3-pip
811

9-
# create directories for config, logs and data
12+
# Create directories for config, logs and data
1013
ARG config_dir=/usr/share/config/mapswipe_workers/
1114
ARG repo_dir=/usr/local/mapswipe_workers/
1215
ARG data_dir=/var/lib/mapswipe_workers/
@@ -26,7 +29,7 @@ RUN mkdir -p $data_dir"api-data/tasks/"
2629
RUN mkdir -p $data_dir"api-data/yes_maybe/"
2730
RUN mkdir -p $data_dir"api-data/hot_tm/"
2831

29-
# copy mapswipe workers repo from local repo
32+
# Copy mapswipe workers repo from local repo
3033
WORKDIR $repo_dir
3134
COPY mapswipe_workers/ mapswipe_workers/
3235
COPY sample_data/ sample_data/
@@ -35,8 +38,8 @@ COPY requirements.txt .
3538
COPY setup.py .
3639
COPY config $config_dir
3740

38-
# Install dependencies and mapswipe-workers
39-
# RUN python setup.py install
40-
RUN pip install .
41+
# Update setuptools and install mapswipe-workers with dependencies (requirements.txt)
42+
RUN pip3 install --upgrade setuptools
43+
RUN pip3 install .
4144

42-
# we don't use a CMD here, this will be defined in docker-compose.yaml
45+
# Don't use a CMD here, this will be defined in docker-compose.yaml

mapswipe_workers/config/example-configuration.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@
2626
},
2727
"slack": {
2828
"token": "your_slack_token",
29-
"channel": "your_slack_channel",
30-
"username": "your_slack_username"
29+
"channel": "your_slack_channel"
3130
},
3231
"sentry": {
3332
"dsn": "your_sentry_dsn_value"

mapswipe_workers/config/logging.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,4 @@ formatter=mapswipeFormatter
3030
args=('/var/log/mapswipe_workers/mapswipe_workers.log','D', 1, 14,)
3131

3232
[formatter_mapswipeFormatter]
33-
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
33+
format=%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(message)s

mapswipe_workers/mapswipe_workers/auth.py

Lines changed: 30 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -1,150 +1,74 @@
1-
#!/usr/bin/python3
2-
#
3-
# Author: B. Herfort, M. Reinmuth, 2017
4-
############################################
5-
6-
import json
7-
8-
import psycopg2
91
import firebase_admin
10-
from firebase_admin import credentials
11-
from firebase_admin import db
12-
13-
from mapswipe_workers.definitions import CONFIG_PATH
14-
from mapswipe_workers.definitions import SERVICE_ACCOUNT_KEY_PATH
2+
import psycopg2
3+
from firebase_admin import credentials, db
154

5+
from mapswipe_workers.definitions import CONFIG, SERVICE_ACCOUNT_KEY_PATH
166

17-
def load_config():
18-
"""
19-
Loads the user configuration values.
207

21-
Returns
22-
-------
23-
dictonary
24-
"""
25-
with open(CONFIG_PATH) as f:
26-
CONFIG = json.load(f)
27-
return CONFIG
8+
def get_api_key(tileserver: str) -> str:
9+
if tileserver == "custom":
10+
return None
11+
else:
12+
return CONFIG["imagery"][tileserver]["api_key"]
2813

2914

30-
def get_api_key(tileserver):
31-
CONFIG = load_config()
32-
try:
33-
if tileserver == 'custom':
34-
return None
35-
else:
36-
return CONFIG['imagery'][tileserver]['api_key']
37-
except KeyError:
38-
print(
39-
f'Could not find the API key for imagery tileserver '
40-
f'{tileserver} in {CONFIG_PATH}.'
41-
)
42-
raise
43-
44-
45-
def get_tileserver_url(tileserver):
46-
CONFIG = load_config()
47-
try:
48-
if tileserver == 'custom':
49-
return None
50-
else:
51-
return CONFIG['imagery'][tileserver]['url']
52-
except KeyError:
53-
print('Could not find the url for imagery tileserver {} in {}.'.format(
54-
tileserver,
55-
CONFIG_PATH
56-
))
57-
raise
58-
59-
60-
def init_firebase():
61-
try:
62-
# Is an App instance already initialized?
63-
firebase_admin.get_app()
64-
except ValueError:
65-
cred = credentials.Certificate(SERVICE_ACCOUNT_KEY_PATH)
66-
# Initialize the app with a service account, granting admin privileges
67-
firebase_admin.initialize_app(cred)
15+
def get_tileserver_url(tileserver: str) -> str:
16+
if tileserver == "custom":
17+
return None
18+
else:
19+
return CONFIG["imagery"][tileserver]["url"]
6820

6921

70-
def firebaseDB():
22+
def firebaseDB() -> object:
7123
try:
7224
# Is an App instance already initialized?
7325
firebase_admin.get_app()
7426
# Return the imported Firebase Realtime Database module
7527
return db
7628
except ValueError:
7729
cred = credentials.Certificate(SERVICE_ACCOUNT_KEY_PATH)
78-
config = load_config()
79-
databaseName = config['firebase']['database_name']
80-
databaseURL = f'https://{databaseName}.firebaseio.com'
30+
databaseName = CONFIG["firebase"]["database_name"]
31+
databaseURL = f"https://{databaseName}.firebaseio.com"
8132

8233
# Initialize the app with a service account, granting admin privileges
83-
firebase_admin.initialize_app(cred, {
84-
'databaseURL': databaseURL
85-
})
34+
firebase_admin.initialize_app(cred, {"databaseURL": databaseURL})
8635

8736
# Return the imported Firebase Realtime Database module
8837
return db
8938

9039

9140
class postgresDB(object):
41+
"""Helper calss for Postgres interactions"""
42+
9243
_db_connection = None
9344
_db_cur = None
9445

9546
def __init__(self):
96-
CONFIG = load_config()
97-
try:
98-
host = CONFIG['postgres']['host']
99-
port = CONFIG['postgres']['port']
100-
dbname = CONFIG['postgres']['database']
101-
user = CONFIG['postgres']['username']
102-
password = CONFIG['postgres']['password']
103-
except KeyError:
104-
raise Exception(
105-
f'Could not load postgres credentials '
106-
f'from the configuration file'
107-
)
47+
host = CONFIG["postgres"]["host"]
48+
port = CONFIG["postgres"]["port"]
49+
dbname = CONFIG["postgres"]["database"]
50+
user = CONFIG["postgres"]["username"]
51+
password = CONFIG["postgres"]["password"]
10852

10953
self._db_connection = psycopg2.connect(
110-
database=dbname,
111-
user=user,
112-
password=password,
113-
host=host,
114-
port=port
115-
)
54+
database=dbname, user=user, password=password, host=host, port=port,
55+
)
11656

11757
def query(self, query, data=None):
11858
self._db_cur = self._db_connection.cursor()
11959
self._db_cur.execute(query, data)
12060
self._db_connection.commit()
12161
self._db_cur.close()
12262

123-
def copy_from(
124-
self,
125-
f,
126-
table,
127-
columns
128-
):
63+
def copy_from(self, f, table, columns):
12964
self._db_cur = self._db_connection.cursor()
130-
self._db_cur.copy_from(
131-
f,
132-
table,
133-
columns=columns
134-
)
65+
self._db_cur.copy_from(f, table, columns=columns)
13566
self._db_connection.commit()
13667
self._db_cur.close()
13768

138-
def copy_expert(
139-
self,
140-
sql,
141-
file,
142-
):
69+
def copy_expert(self, sql, file):
14370
self._db_cur = self._db_connection.cursor()
144-
self._db_cur.copy_expert(
145-
sql,
146-
file,
147-
)
71+
self._db_cur.copy_expert(sql, file)
14872
self._db_connection.commit()
14973
self._db_cur.close()
15074

mapswipe_workers/mapswipe_workers/base/base_project.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def __init__(self, project_draft):
7878
# def resultRequiredCounter(self):
7979
# return self.resultRequiredCounter
8080

81-
def save_project(self, fb_db):
81+
def save_project(self):
8282
"""
8383
Creates a projects with groups and tasks
8484
and saves it in firebase and postgres
@@ -130,7 +130,6 @@ def save_project(self, fb_db):
130130
)
131131
try:
132132
self.save_to_firebase(
133-
fb_db,
134133
project,
135134
groups,
136135
groupsOfTasks,
@@ -160,7 +159,7 @@ def save_project(self, fb_db):
160159
)
161160
raise CustomError(e)
162161

163-
def save_to_firebase(self, fb_db, project, groups, groupsOfTasks):
162+
def save_to_firebase(self, project, groups, groupsOfTasks):
164163

165164
# remove wkt geometry attribute of projects and tasks
166165
project.pop('geometry', None)
@@ -169,6 +168,7 @@ def save_to_firebase(self, fb_db, project, groups, groupsOfTasks):
169168
groupsOfTasks[group_id][i].pop('geometry', None)
170169

171170

171+
fb_db = auth.firebaseDB()
172172
ref = fb_db.reference('')
173173
# save project
174174
ref.update({
Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,37 @@
1-
import os
21
import json
32
import logging
43
import logging.config
5-
from logging.handlers import TimedRotatingFileHandler
4+
import os
5+
6+
import sentry_sdk
7+
8+
9+
class CustomError(Exception):
10+
pass
11+
12+
13+
def load_config(CONFIG_PATH) -> dict:
14+
"""Read the configuration file."""
15+
with open(CONFIG_PATH) as f:
16+
return json.load(f)
617

718

819
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
920

10-
CONFIG_DIR = os.path.abspath(
11-
'/usr/share/config/mapswipe_workers/'
12-
)
21+
CONFIG_DIR = os.path.abspath("/usr/share/config/mapswipe_workers/")
1322

14-
CONFIG_PATH = os.path.join(
15-
CONFIG_DIR,
16-
'configuration.json'
17-
)
23+
CONFIG_PATH = os.path.join(CONFIG_DIR, "configuration.json")
1824

19-
SERVICE_ACCOUNT_KEY_PATH = os.path.join(
20-
CONFIG_DIR,
21-
'serviceAccountKey.json'
22-
)
25+
CONFIG = load_config(CONFIG_PATH)
2326

24-
LOGGING_CONFIG_PATH = os.path.join(
25-
CONFIG_DIR,
26-
'logging.cfg'
27-
)
27+
SERVICE_ACCOUNT_KEY_PATH = os.path.join(CONFIG_DIR, "serviceAccountKey.json")
2828

29-
DATA_PATH = os.path.abspath(
30-
'/var/lib/mapswipe_workers/'
31-
)
29+
LOGGING_CONFIG_PATH = os.path.join(CONFIG_DIR, "logging.cfg")
3230

33-
logging.config.fileConfig(
34-
fname=LOGGING_CONFIG_PATH,
35-
disable_existing_loggers=True
36-
)
37-
logger = logging.getLogger('Mapswipe Workers')
31+
DATA_PATH = os.path.abspath("/var/lib/mapswipe_workers/")
3832

33+
logging.config.fileConfig(fname=LOGGING_CONFIG_PATH, disable_existing_loggers=True)
34+
logger = logging.getLogger("Mapswipe Workers")
3935

40-
class CustomError(Exception):
41-
pass
36+
sentry_sdk.init(CONFIG["sentry"]["dsn"])
37+
sentry = sentry_sdk

0 commit comments

Comments
 (0)