Skip to content

Commit 4a59820

Browse files
committed
update backend
1 parent 073deb7 commit 4a59820

9 files changed

+154
-82
lines changed

.env.sample

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# SITN specific stuff
2+
PGPOSTGRESPASSWORD=password
3+
DOCKER_HOST="ssh://[email protected]"
4+
DOCKER_BACK_PORT=5004
5+
DOCKER_FRONT_PORT=5005
6+
DOCKER_BASE=sitn/geoshop-local
7+
COMPOSE_PROJECT_NAME=geoshop-local
8+
API_BASE_URL=https://sitn.ne.ch
9+
10+
# Do not set this to True if your server is exposed to internet!
11+
DEBUG=False
12+
13+
PGDATABASE=geoshop
14+
PGUSER=geoshop
15+
PGHOST=host.docker.internal
16+
PGPORT=5432
17+
PGPASSWORD=geoshop
18+
PGSCHEMA=geoshop
19+
20+
# The folder where the geodata will be uploaded
21+
MEDIA_ROOT=./files
22+
# A link to public images used in product and metadata
23+
MEDIA_URL=https://example.com/geoshop_media/
24+
25+
ALLOWED_HOST=localhost,127.0.0.1,proxy.example.com
26+
# Base URL of the api
27+
ROOTURL=
28+
29+
DEFAULT_FROM_EMAIL=[email protected]
30+
EMAIL_HOST=smtp.example.com
31+
ADMIN_USERNAME=admin
32+
ADMIN_EMAIL_LIST=[email protected]
33+
34+
# This is used for CORS and to generate links in email templates
35+
FRONT_URL=localhost:4200
36+
FRONT_HREF=/geoshop
37+
FRONT_PROTOCOL=http
38+
CSRF_COOKIE_DOMAIN=localhost
39+
LOGGING_LEVEL=INFO
40+
41+
# Generate this key with Django tools
42+
SECRET_KEY=GenerateOneSecretKey
43+
ADMIN_PASSWORD=Test1234
44+
EXTRACT_USER_PASSWORD=Test1234
45+
46+
AUTO_LEGEND_URL=http://example.com/mapserv?FORMAT=image%2Fpng&TRANSPARENT=true&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetLegendGraphic&LAYER=
47+
# If you plan to manage secret metadata, provide your intranet legend service
48+
INTRA_LEGEND_URL=https://example.com/mapserv_proxy?ogcserver=source+for+image%2Fpng&FORMAT=image%2Fpng&TRANSPARENT=true&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetLegendGraphic&LAYER=
49+
50+
# Only for testing purpose
51+
EMAIL_TEST_TO=[email protected]
52+
53+
DEFAULT_LANGUAGE=en
54+
# For non-docker, uncomment this (only tested in Windows)
55+
#GDAL_PATH="C:\Applications\Mapserver72_x64\bin"
56+
#GDAL_LIBRARY_PATH="C:\Applications\Mapserver72_x64\bin\gdal300.dll"
57+
#GEOS_LIBRARY_PATH="C:\Applications\Mapserver72_x64\bin\geos_c.dll"
58+
59+
# Geometric settings
60+
DEFAULT_SRID=2056

.gitignore

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,13 @@ logs/*
77
*.pyc
88

99
front/debug.log
10+
11+
.env
12+
.env.local
13+
.env.dev
14+
.env.prod
15+
.env.prepub
16+
17+
.venv
18+
Pipfile
19+
Pipfile.lock

README.md

Lines changed: 24 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -7,94 +7,62 @@
77

88
## Getting started
99

10-
Fork and clone this repository. Make a copy of the `.env` file and adapt it to your environment settings:
10+
Fork and clone this repository. Make a copy of the `.env.sample` and `back/default_settings.py` files and adapt it to your environment settings:
1111

1212
```powershell
1313
git submodule init
1414
git submodule update
15-
cd back
1615
cp .env.sample .env
17-
cp default_settings.py settings.py
18-
cd ..
16+
cp back/default_settings.py back/settings.py
17+
cp scripts/custom.js back/api/templates/gis/admin
1918
```
2019

2120
### Database
2221

2322
The best is to backup and restore a production db:
2423

25-
```sql
26-
.\scripts\sitn\1_fetch_prod_db.ps1
24+
```powershell
25+
.\scripts\1_fetch_prod_db.ps1
2726
```
2827

2928
Now that the database is ready, you can start backend either with Docker or not.
3029

3130
### Backend with docker
3231

33-
To ease debug, you can add `DEBUG=True` to your `env.local` file. Never add this to a container exposed on internet.
34-
35-
Build backend image:
36-
37-
```powershell
38-
cd back
39-
docker build -t sitn/geoshop-dev-api --build-arg ENV_FILE=.env.local .
40-
```
41-
42-
If you started with an empty database, run this once in order to create admin account:
43-
44-
```powershell
45-
docker run --rm --name geoshop --env-file=.env.local sitn/geoshop-dev-api python manage.py fixturize
46-
```
32+
To ease debug, you can add `DEBUG=True` to your `.env` file. Never add this to a container exposed on internet.
4733

48-
Now you can run it with:
34+
Run de docker composition with the following command and type `local` when asked:
4935

5036
```powershell
51-
docker run -d --rm --name geoshop --env-file=.env.local -p 8000:8000 -v ${PWD}:/app/geoshop_back sitn/geoshop-dev-api gunicorn --reload wsgi -b :8000
37+
python deploy.py
5238
```
5339

54-
You should be able to visit the API at http://localhost:8000.
40+
You should be able to visit the API at http://localhost:5004 or another port if you changed it.
5541

5642
Run tests:
5743

5844
```powershell
59-
docker run --rm --env-file=.env.local -v ${PWD}:/app/geoshop_back sitn/geoshop-dev-api python manage.py test api
60-
```
61-
62-
Make messages for translation:
63-
64-
```powershell
65-
docker run --rm --env-file=.env.local -v ${PWD}:/app/geoshop_back:rw sitn/geoshop-dev-api python manage.py makemessages -l fr
66-
```
67-
68-
Stop the server:
69-
```powershell
70-
docker stop geoshop
45+
docker compose exec api python manage.py test api
7146
```
7247

7348
### Backend without docker on Windows
7449

7550
If not using docker, additionnal packages are required:
7651

7752
* pipenv (pip install pipenv)
78-
* GDAL 2.4 (see instructions below to install it in your venv)
53+
* GDAL (see instructions below to install it in your venv)
7954

80-
Install the app. If you want your `venv` to be inside your project directory, you need to set `PIPENV_VENV_IN_PROJECT` environment variable, otherwise it'll go to your profile, if you want `DEBUG` to be enabled, change it in `settings.py` file but never commit it with debug enabled:
55+
Install the app. If you want your `venv` to be inside your project directory, you need to set `PIPENV_VENV_IN_PROJECT` environment variable, otherwise it'll go to your profile
8156

8257
```powershell
83-
cd back
8458
$env:PIPENV_VENV_IN_PROJECT="True"
85-
pipenv install --dev # installs everything needed
86-
pipenv shell # activates venv and reads .env file
59+
pipenv install --dev -r back/requirements.txt
60+
pipenv shell # activates venv and reads .env file
8761
```
8862

8963
#### Installing GDAL on Windows, only once per machine
90-
Download the GDAL 2.4 wheel (3.X isn't supported yet by Django) on this page: https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal. For example, if you have Python 3.6 64bit, choose `GDAL‑2.4.1‑cp36‑cp36m‑win_amd64.whl`.
91-
Then install it weather system wide or in your venv (the example below will show the venv variant and expects you have your venv activated):
9264

93-
```powershell
94-
pip install path\to\your\GDAL-2.4XXXX.whl
95-
```
96-
97-
You'll then need to add GDAL dll to your PATH if you installed it system wide. You can get the dll path with:
65+
You'll need to add GDAL dll to your PATH if you installed it system wide. You can get the dll path with:
9866

9967
```python
10068
python
@@ -122,21 +90,17 @@ Your database should be ready, now you can run the backend:
12290
python manage.py runserver
12391
```
12492

125-
Translations can be generated, static files collected with:
93+
Translations can be generated and static files collected with:
12694

12795
```powershell
12896
python manage.py compilemessages --locale=fr
129-
python .\manage.py collectstatic
97+
python manage.py collectstatic
13098
```
13199

132-
Then, set `DEBUG` to `True` in `back/settings.py` and you can finally run the server:
133-
134100
```powershell
135101
python manage.py runserver
136102
```
137103

138-
> :warning: **DO NOT COMMIT settings.py with `DEBUG` set to `True` !**
139-
140104
### Run tests
141105

142106
```powershell
@@ -185,17 +149,19 @@ Create an `env.prod` file base on `env.sample`.
185149

186150
### Application deployment
187151

152+
Always:
153+
1. Run tests locally on docker
154+
2. Deploy prepub and test it with a fake order
155+
3. Deploy prod
156+
188157
```powershell
189-
python scripts\deploy.py
158+
python deploy.py
190159
```
191160

192-
And choose your instance to be deployed.
193-
194-
Create a scheduled task that runs `scripts/geoshop_clean_orders.ps1` every month.
161+
And choose your instance to be deployed. You must have `.env.prepub` and `.env.prod` defined at the root of the project.
195162

196163
More info on bookstack
197164

198-
199165
## Upgrading front-end packages
200166

201167
Go to https://update.angular.io/?v=16.0-17.0 and check there are not manual steps to be done.

back

Submodule back updated from 80c6bdf to 6d158b9
Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
import os
2-
import pathlib
32
import datetime
43
import subprocess
54
import re
65

76
dest_config = input('Input "prod", "prepub", "dev" or "local": ')
87

9-
BASE_DIR = pathlib.Path(__file__).parent.absolute()
10-
118
def resub_callback(match):
129
return os.environ.get(match.group(1), '')
1310

@@ -19,36 +16,37 @@ def eval_templates(in_file, out_file):
1916
with open(out_file, "w", encoding="utf8") as f:
2017
f.write(file_content)
2118

22-
# Do not deploy to internet with DEBUG set to True
23-
settings_path = f'{BASE_DIR}/../back/settings.py'
24-
with open(settings_path, 'r') as f:
25-
settings = f.read()
26-
27-
is_debug = re.search(r'^DEBUG = (True)$', settings, re.MULTILINE)
28-
if is_debug:
29-
if dest_config != "local":
30-
print("Cannot deploy if DEBUG=True in settings.py")
31-
quit()
19+
env_file = f'.env.{dest_config}'
20+
if dest_config == "local":
21+
env_file = '.env'
3222

33-
env_file = f'{BASE_DIR}/../back/.env.{dest_config}'
3423
# Read .env
3524
with open(env_file, 'r') as f:
3625
for line in f:
3726
args = line.strip().split('=')
3827
if args[0] and not args[0].startswith('#'):
3928
os.environ[args[0].strip('"')] = args[1].strip('"')
4029

41-
os.environ['ENV_FILE'] = f".env.{dest_config}"
30+
is_debug = os.environ['DEBUG'] == 'True'
31+
if is_debug:
32+
if dest_config != "local":
33+
print("Cannot deploy if DEBUG=True for this config")
34+
quit()
35+
36+
os.environ['ENV_FILE'] = env_file
4237
print(f"{str(datetime.datetime.now())} - COMPOSE_PROJECT_NAME IS {os.environ['COMPOSE_PROJECT_NAME']}")
38+
print(f"{str(datetime.datetime.now())} - ENV_FILE IS {os.environ['ENV_FILE']}")
4339

44-
eval_templates(f'{BASE_DIR}/../front/src/assets/configs/config.json.tmpl', f'{BASE_DIR}/../front/src/assets/configs/config.json')
45-
eval_templates(f'{BASE_DIR}/../front/httpd.conf.tmpl', f'{BASE_DIR}/../front/httpd.conf')
40+
eval_templates(f'front/src/assets/configs/config.json.tmpl', f'front/src/assets/configs/config.json')
41+
eval_templates(f'front/httpd.conf.tmpl', f'front/httpd.conf')
4642

4743
print(f"{str(datetime.datetime.now())} - DOCKER_HOST IS {os.environ['DOCKER_HOST']}")
4844

45+
os.rename('.env', '.env.local')
4946
subprocess.run(['docker-compose', 'build', 'api'])
5047
subprocess.run(['docker-compose', 'build', 'front'])
5148
subprocess.run(['docker-compose', 'down'])
5249
subprocess.run(['docker-compose', 'up', '-d'])
50+
os.rename('.env.local', '.env')
5351

5452
print(f"{str(datetime.datetime.now())} - END")

docker-compose.yml

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,29 @@ services:
55
image: ${DOCKER_BASE}-api
66
build:
77
context: ./back/
8-
args:
9-
ENV_FILE: ${ENV_FILE}
10-
env_file: ./back/${ENV_FILE}
8+
env_file: ${ENV_FILE:-.env}
119
command: "gunicorn wsgi -b :8000 --timeout 90"
10+
depends_on:
11+
migrate:
12+
condition: service_completed_successfully
1213
restart: unless-stopped
1314
ports:
1415
- "${DOCKER_BACK_PORT}:8000"
1516
volumes:
16-
- "${GEOSHOP_DATA}:/mnt/geoshop_data"
17+
- "static-files:/app/geoshop_back/static:ro"
18+
19+
migrate:
20+
image: geoshop-api
21+
build:
22+
context: ./back/
23+
dockerfile: Dockerfile
24+
env_file: ${ENV_FILE:-.env}
25+
command:
26+
- bash
27+
- -c
28+
- "python manage.py migrate && python manage.py collectstatic --noinput && python manage.py compilemessages --locale=fr && python manage.py fixturize"
29+
volumes:
30+
- "static-files:/app/geoshop_back/static:rw"
1731

1832
front:
1933
image: ${DOCKER_BASE}-front
@@ -24,3 +38,6 @@ services:
2438
restart: unless-stopped
2539
ports:
2640
- "${DOCKER_FRONT_PORT}:80"
41+
42+
volumes:
43+
static-files:

scripts/sitn/1_fetch_prod_db.ps1 renamed to scripts/1_fetch_prod_db.ps1

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
$pwd = pwd
2-
foreach ($line in Get-Content $PSScriptRoot\..\..\back\.env.prod) {
2+
foreach ($line in Get-Content $PSScriptRoot\..\.env.prod) {
33
$args = $line -split "="
44
If ($args[0] -And !$args[0].StartsWith("#")) {
55
$cmd = '$env:' + $args[0].Trim('"') + '="' + $args[1].Trim('"') + '"'
@@ -22,7 +22,7 @@ Write-Host "$(Get-Date -Format g) PG dump done..."
2222

2323
Write-Host "$(Get-Date -Format g) variables d'environnement remises sur .env.local"
2424

25-
foreach ($line in Get-Content $PSScriptRoot\..\..\back\.env) {
25+
foreach ($line in Get-Content $PSScriptRoot\..\.env) {
2626
$args = $line -split "="
2727
If ($args[0] -And !$args[0].StartsWith("#")) {
2828
$cmd = '$env:' + $args[0].Trim('"') + '="' + $args[1].Trim('"') + '"'

scripts/custom.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{% extends "gis/admin/openlayers.js" %}
2+
{% block map_options %}
3+
var options = {
4+
projection: new OpenLayers.Projection('EPSG:2056'),
5+
resolutions: [250, 100, 50, 20, 10, 5, 2.5, 2, 1.5, 1, 0.5, 0.25, 0.125, 0.0625],
6+
units: 'm',
7+
maxExtent: new OpenLayers.Bounds(2420000.0, 1030000.0, 2900000.0, 1360000.0),
8+
tileSize: new OpenLayers.Size(256, 256)
9+
};
10+
{% endblock %}
11+
{% block base_layer %}new OpenLayers.Layer.WMTS({
12+
name: "WMTS plan_cadastral",
13+
url: "https://sitn.ne.ch/mapproxy95/wmts/1.0.0/plan_cadastral/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.png",
14+
layer: 'plan_cadastral',
15+
matrixSet: 'EPSG2056',
16+
format: 'png',
17+
isBaseLayer: true,
18+
style: 'default',
19+
requestEncoding: 'REST'
20+
});
21+
{% endblock %}

0 commit comments

Comments
 (0)