move to django

This commit is contained in:
boyska 2020-03-02 01:49:44 +01:00
parent 4559793726
commit d9f7bcdafa
40 changed files with 424 additions and 188 deletions

163
app.py
View file

@ -1,163 +0,0 @@
import flask
import sqlite3
from datetime import datetime
from flask import Flask, render_template, redirect, url_for, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy.exc
from sqlalchemy_utils import PasswordType
# from sqlalchemy import Column, Integer, String
# from sqlalchemy.ext.declarative import declarative_base
# TODO: sqlalchemy?
# schema:
# Utente: uid, username, password
# TipoRadio: trid, tipo
# Avvistamento: aid, uid, tipo_radio, data, commento
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///map.db"
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = "user"
uid = db.Column(db.Integer, primary_key=True, nullable=False)
username = db.Column(db.String, unique=True)
password = db.Column(PasswordType(schemes=["pbkdf2_sha512"]))
rapporti = db.relationship("RapportoRicezione")
class TipoRadio(db.Model):
__tablename__ = "tiporadio"
tid = db.Column(db.Integer, primary_key=True, nullable=False)
nome = db.Column(db.Unicode)
descrizione = db.Column(db.Unicode)
rapporti = db.relationship("RapportoRicezione")
class RapportoRicezione(db.Model):
__tablename__ = "rapporto"
rid = db.Column(db.Integer, primary_key=True)
uid = db.Column(db.Integer, db.ForeignKey("user.uid"))
tid = db.Column(db.Integer, db.ForeignKey("tiporadio.tid"))
date = db.Column(db.Date, default=lambda: datetime.now())
lat = db.Column(db.Float)
lng = db.Column(db.Float)
comprensibile = db.Column(db.Integer) # TODO: >= 0 <= 5
stabilita = db.Column(db.Integer) # TODO: >= 0 <= 5
author = db.relationship(User, back_populates="rapporti")
tipo_radio = db.relationship(TipoRadio, back_populates="rapporti")
def serialize(self):
d = {k:v for k,v in self.__dict__.items() if not k.startswith('_')}
d['colore'] = self.colore
d['radius'] = self.radius
d['explaination'] = self.explaination
return d
@property
def colore(self):
c = self.comprensibile
if c > 3:
return 'green'
if c > 1:
return 'yellow'
return 'red'
@property
def radius(self):
return self.stabilita * 70
@property
def explaination(self):
return 'Aggiunto il %s da %s' % (self.date, self.author.username)
def __repr__(self):
return "<Rapporto %s del %s>" % (self.rid, self.date)
@app.before_first_request
def init_db():
db.create_all()
try:
anon = User(username="anonymous", password="antani")
db.session.add(anon)
db.session.commit()
except sqlalchemy.exc.IntegrityError:
db.session.rollback()
for nome in ["radiolina portatile", "autoradio", "stereo fisso dentro casa"]:
try:
t = TipoRadio(nome=nome)
db.session.add(t)
db.session.commit()
except sqlalchemy.exc.IntegrityError:
db.session.rollback()
cnt = int(RapportoRicezione.query.count())
if cnt == 0:
for i in range(6):
r = RapportoRicezione(
uid=User.query.filter(User.username == "anonymous")[0].uid,
tid=TipoRadio.query.all()[0].tid,
stabilita=i,
comprensibile=i,
lat=43.8199 - i * 0.01,
lng=11.22185 + i * 0.03,
)
db.session.add(r)
db.session.commit()
@app.route("/")
def home():
return render_template("index.html")
@app.route("/add")
def add():
return render_template("add.html")
@app.route("/api/rapporti/get")
def get_rapporti():
query = RapportoRicezione.query.all()
# TODO: usa query params per filtrare in base a $cose
return jsonify(dict(rapporti=[r.serialize() for r in query]))
@app.route("/api/rapporti/add", methods=['POST'])
def add_rapporto():
anon = User.query.filter(User.username=='anonymous')[0].uid
r = RapportoRicezione(
uid=anon,
lat=request.form['lat'],
lng=request.form['lng'],
stabilita=request.form['stabilita'],
comprensibile=request.form['comprensibile'],
)
db.session.add(r)
db.session.commit()
r = RapportoRicezione.query.get(r.rid)
return jsonify(r.serialize())
@app.route("/api/rapporti/delete", methods=['POST'])
def delete_rapporto():
r = RapportoRicezione.query.get(int(request.form['rid']))
db.session.delete(r)
db.session.commit()
return jsonify(True)

View file

@ -1,11 +1,4 @@
Click==7.0
Flask-SQLAlchemy==2.4.1
Flask==1.1.1
Jinja2==2.11.1
MarkupSafe==1.1.1
SQLAlchemy-Utils==0.36.1
SQLAlchemy==1.3.13
Werkzeug==1.0.0
itsdangerous==1.1.0
passlib==1.7.2
six==1.14.0
Django==2.2
gunicorn==20.0.4
pytz==2019.3
sqlparse==0.3.1

1
rxmap/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
*.sqlite3

21
rxmap/manage.py Executable file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rxmap.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

0
rxmap/rxmap/__init__.py Normal file
View file

123
rxmap/rxmap/settings.py Normal file
View file

@ -0,0 +1,123 @@
"""
Django settings for rxmap project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'o4-qdex8sx_b3i!hu81qtri*-&pztgkolc^p()r0g3vauzk+^b'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rxmapp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'rxmap.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'rxmap.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_USER_MODEL = 'rxmapp.User'
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'it-it'
TIME_ZONE = 'Europe/Rome'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'static'

22
rxmap/rxmap/urls.py Normal file
View file

@ -0,0 +1,22 @@
"""rxmap URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('rxmapp.urls')),
]

16
rxmap/rxmap/wsgi.py Normal file
View file

@ -0,0 +1,16 @@
"""
WSGI config for rxmap project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rxmap.settings')
application = get_wsgi_application()

0
rxmap/rxmapp/__init__.py Normal file
View file

3
rxmap/rxmapp/admin.py Normal file
View file

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

5
rxmap/rxmapp/apps.py Normal file
View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class RxmappConfig(AppConfig):
name = 'rxmapp'

View file

@ -0,0 +1,71 @@
# Generated by Django 2.2 on 2020-03-01 15:46
import datetime
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='TipoRadio',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=64, unique=True)),
('descrizione', models.CharField(max_length=1000)),
],
),
migrations.CreateModel(
name='RapportoRicezione',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField(default=datetime.datetime.now)),
('lat', models.FloatField()),
('lng', models.FloatField()),
('comprensibile', models.IntegerField()),
('stabilita', models.IntegerField()),
('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='rapporti', to=settings.AUTH_USER_MODEL)),
('tipo_radio', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='rapporti', to='rxmapp.TipoRadio')),
],
options={
'verbose_name': 'rapporto ricezione',
},
),
]

View file

68
rxmap/rxmapp/models.py Normal file
View file

@ -0,0 +1,68 @@
from django.db import models
from datetime import datetime
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
pass
class TipoRadio(models.Model):
#tid = db.Column(db.Integer, primary_key=True, nullable=False)
nome = models.CharField(max_length=64, unique=True)
descrizione = models.CharField(max_length=1000)
#rapporti = db.relationship("RapportoRicezione")
class RapportoRicezione(models.Model):
class Meta:
verbose_name = 'rapporto ricezione'
#verbose_plural_name = 'rapporti ricezione'
#rid = db.Column(db.Integer, primary_key=True)
author = models.ForeignKey(User, related_name='rapporti', on_delete=models.PROTECT)
tipo_radio = models.ForeignKey(TipoRadio, on_delete=models.PROTECT, related_name='rapporti')
date = models.DateField(default=datetime.now)
lat = models.FloatField()
lng = models.FloatField()
comprensibile = models.IntegerField() # TODO: >= 0 <= 5
stabilita = models.IntegerField() # TODO: >= 0 <= 5
def serialize(self):
d = {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
d["colore"] = self.colore
d["radius"] = self.radius
d["explaination"] = self.explaination
return d
@property
def colore(self):
c = self.comprensibile
if c > 3:
return "green"
if c > 1:
return "yellow"
return "red"
@property
def radius(self):
return self.stabilita * 70
@property
def explaination(self):
return """
Ricevuto con %s
Aggiunto il %s da %s
""" % (
self.tipo_radio.nome,
self.date,
self.author.username,
)
def __str__(self):
return "<Rapporto %s del %s>" % (self.rid, self.date)

View file

Before

Width:  |  Height:  |  Size: 262 B

After

Width:  |  Height:  |  Size: 262 B

View file

Before

Width:  |  Height:  |  Size: 348 B

After

Width:  |  Height:  |  Size: 348 B

View file

Before

Width:  |  Height:  |  Size: 207 B

After

Width:  |  Height:  |  Size: 207 B

View file

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

View file

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 6.8 KiB

View file

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

View file

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

View file

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

View file

Before

Width:  |  Height:  |  Size: 6.2 KiB

After

Width:  |  Height:  |  Size: 6.2 KiB

View file

@ -29,6 +29,16 @@
<option value="5">In tutto il quartiere</option>
</select>
</div>
<div class="form-field-line">
<label for="tiporadio">Osservazione fatta con</label>
<select name="tiporadio">
{% for tr in tipiradio %}
<option value="{{tr.tid}}"><strong>{{tr.nome}}</strong> - {{tr.descrizione|default('', true)}}</option>
{% endfor %}
</select>
</div>
<input type="hidden" name="lat" />
<input type="hidden" name="lng" />
<button id="addPoint">Aggiungi</button>

View file

@ -40,8 +40,8 @@ footer {
<nav>
<ul>
<li class="brand"><strong>WomMap</strong></li>
<li class="navigation"><a href="{{url_for('home')}}">Vedi</a></li>
<li class="navigation"><a href="{{url_for('add')}}">Aggiungi</a></li>
<li class="navigation"><a href="{% url 'home' %}">Vedi</a></li>
<li class="navigation"><a href="{% url 'add' %}">Aggiungi</a></li>
</ul>
</nav>
{% block main %}

View file

@ -0,0 +1,33 @@
{% extends 'base.html' %}
{% load static %}
{% block extra_css %}
<link rel="stylesheet" href="{% static 'jquery-ui/jquery-ui.min.css' %}" />
{% endblock extra_css %}
{% block extra_scripts %}
<script src="{% static 'js/viewmap.js' %}"> </script>
<script src="{% static 'jquery-ui/jquery-ui.min.js' %}"> </script>
{% endblock extra_scripts %}
{% block content %}
<div id="dialog"></div>
<div id="filters">
<header><h3>Filtra</h3></header>
<form method="GET">
<div class="form-field-line">
<label for="tiporadio">Osservazione fatta con</label>
<select name="tiporadio" >
<option value="NA" disabled selected="selected">//</option>
{% for tr in tipiradio %}
<option value="{{tr.tid}}"><strong>{{tr.nome}}</strong> - {{tr.descrizione|default:'' }}</option>
{% endfor %}
</select>
</div>
<button id="search">Filtra</button>
</form>
</div>
{% endblock content %}

3
rxmap/rxmapp/tests.py Normal file
View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

29
rxmap/rxmapp/urls.py Normal file
View file

@ -0,0 +1,29 @@
"""rxmap URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from . import views
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html'), name="home"),
path('add', TemplateView.as_view(template_name='add.html'), name="add"),
path('api/rapporti/get', views.rapporti_get),
#path('api/rapporti/add', views.rapporti_add),
#path('api/rapporti/delete', views.rapporti_delete),
]

12
rxmap/rxmapp/views.py Normal file
View file

@ -0,0 +1,12 @@
from django.shortcuts import render
from django.http import JsonResponse
from .models import RapportoRicezione
# Create your views here.
def rapporti_get(request):
return JsonResponse([
r.serialize()
for r in RapportoRicezione.objects.all()
], safe=False)

1
rxmap/static/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
*/

View file

@ -1,12 +0,0 @@
{% extends 'base.html' %}
{% block extra_css %}
<link rel="stylesheet" href="{{url_for('static', filename='jquery-ui/jquery-ui.min.css')}}" />
{% endblock extra_css %}
{% block extra_scripts %}
<script src="{{url_for('static', filename='js/viewmap.js')}}"> </script>
<script src="{{url_for('static', filename='jquery-ui/jquery-ui.min.js')}}"> </script>
{% endblock extra_scripts %}
{% block content %}
<div id="dialog"></div>
{% endblock content %}