ch14
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# apic/apic/__init__.py
|
||||
@@ -0,0 +1,17 @@
|
||||
# apic/apic/asgi.py
|
||||
"""
|
||||
ASGI config for apic project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apic.settings")
|
||||
|
||||
application = get_asgi_application()
|
||||
@@ -0,0 +1,132 @@
|
||||
# apic/apic/settings.py
|
||||
"""
|
||||
Django settings for apic project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 3.2.6.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/3.2/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/3.2/ref/settings/
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = "django-insecure-98u5ntukr@mo0e5c*ve+8bk5$i3lr+4n4gc^@=b-7c*j_lyxa("
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
"rails.apps.RailsConfig",
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
]
|
||||
|
||||
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 = "apic.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 = "apic.wsgi.application"
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": BASE_DIR / "db.sqlite3",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
|
||||
|
||||
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/3.2/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = "en-us"
|
||||
|
||||
TIME_ZONE = "UTC"
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/3.2/howto/static-files/
|
||||
|
||||
STATIC_URL = "/static/"
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
|
||||
|
||||
# API Settings
|
||||
|
||||
BASE_API_URL = "http://localhost:8000"
|
||||
@@ -0,0 +1,23 @@
|
||||
# apic/apic/urls.py
|
||||
"""apic URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/3.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 include, path
|
||||
|
||||
urlpatterns = [
|
||||
path("", include("rails.urls")),
|
||||
path("admin/", admin.site.urls),
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
# apic/apic/wsgi.py
|
||||
"""
|
||||
WSGI config for apic 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/3.2/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apic.settings")
|
||||
|
||||
application = get_wsgi_application()
|
||||
@@ -0,0 +1,27 @@
|
||||
# apic/manage.py
|
||||
#!/usr/bin/env python
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run administrative tasks."""
|
||||
os.environ.setdefault(
|
||||
"DJANGO_SETTINGS_MODULE", "apic.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,0 +1 @@
|
||||
# apic/rails/__init__.py
|
||||
@@ -0,0 +1,4 @@
|
||||
# apic/rails/admin.py
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
@@ -0,0 +1,7 @@
|
||||
# apic/rails/apps.py
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class RailsConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "rails"
|
||||
@@ -0,0 +1,9 @@
|
||||
# apic/rails/forms.py
|
||||
from django import forms
|
||||
|
||||
|
||||
class AuthenticateForm(forms.Form):
|
||||
email = forms.EmailField(max_length=256, label="Username")
|
||||
password = forms.CharField(
|
||||
label="Password", widget=forms.PasswordInput
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
# apic/rails/migrations/__init__.py
|
||||
@@ -0,0 +1,4 @@
|
||||
# apic/rails/models.py
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
||||
@@ -0,0 +1,29 @@
|
||||
body {
|
||||
font-family: "Georgia", Times, serif;
|
||||
}
|
||||
|
||||
.bg_color1 {
|
||||
background-color: lightsteelblue;
|
||||
padding: 0.1em 0 0.1em 0.8em;
|
||||
}
|
||||
|
||||
.bg_color2 {
|
||||
background-color:whitesmoke;
|
||||
padding: 0.1em 0 0.1em 0.8em;
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding-top: 1em;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color:steelblue;
|
||||
}
|
||||
|
||||
.error {
|
||||
color:darkred;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{% extends "rails/base.html" %}
|
||||
|
||||
{% block title %}Arrivals{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
{% if arrivals %}
|
||||
<h1>Arrivals to {{ arrivals.0.station_to.city }} ({{ arrivals.0.station_to.code }})</h1>
|
||||
{% endif %}
|
||||
|
||||
{% for arv in arrivals %}
|
||||
|
||||
<div class="{% cycle 'bg_color1' 'bg_color2' %}">
|
||||
<h3>{{ arv.name }}</h3>
|
||||
<p>
|
||||
<em>Departs at</em>: {{ arv.departs_at }}<br>
|
||||
<em>Arrives at</em>: {{ arv.arrives_at }}<br>
|
||||
<em>Cars</em>: {{ arv.first_class}} FC,
|
||||
{{ arv.second_class }} SC
|
||||
({{ arv.seats_per_car }} seats/car)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% empty %}
|
||||
|
||||
{% if error %}
|
||||
|
||||
<div class=" error">
|
||||
<h3>Error</h3>
|
||||
<p>There was a problem connecting to the API.</p>
|
||||
<code>{{ error }}</code>
|
||||
<p>
|
||||
(<em>The above error is shown to the user as an example.
|
||||
For security reasons these errors are normally hidden from the user</em>)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% else %}
|
||||
|
||||
<div>
|
||||
<p>There are no arrivals available at this time.</p>
|
||||
</div>
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}
|
||||
<div class="footer">
|
||||
<a href="{% url 'stations' %}">Back to stations</a>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends "rails/base.html" %}
|
||||
|
||||
{% block title %}Authentication{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
<h1>Authentication</h1>
|
||||
|
||||
<form action="{% url 'authenticate' %}" method="post">
|
||||
{% csrf_token %}
|
||||
{{ form.as_p }}
|
||||
<input type="submit" value="Authenticate">
|
||||
</form>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}
|
||||
<div class="footer">
|
||||
<a href="{% url 'index' %}">Home</a>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,38 @@
|
||||
{% extends "rails/base.html" %}
|
||||
|
||||
{% block title %}Authentication Result{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
{% if token %}
|
||||
|
||||
<p>
|
||||
<label for="token">
|
||||
<h3>Your JWT token:</h3>
|
||||
</label>
|
||||
</p>
|
||||
|
||||
<textarea id="token" name="token" rows="5" cols="60">
|
||||
{{ token }}
|
||||
</textarea>
|
||||
|
||||
{% else %}
|
||||
|
||||
<p>We were unable to retrieve your token.</p>
|
||||
|
||||
{% if auth_error %}
|
||||
|
||||
<code class="error">{{ auth_error }}</code>
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}
|
||||
<div class="footer">
|
||||
<a href="{% url 'authenticate' %}">Back to authenticate</a>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,17 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<meta charset="UTF-8">
|
||||
<title>{% block title %}Hello{% endblock %}</title>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'rails/style.css' %}">
|
||||
|
||||
<body>
|
||||
{% block content %}
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}
|
||||
{% endblock %}
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,53 @@
|
||||
{% extends "rails/base.html" %}
|
||||
|
||||
{% block title %}Departures{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
{% if departures %}
|
||||
<h1>Departures from {{ departures.0.station_from.city }} ({{ departures.0.station_from.code }})</h1>
|
||||
{% endif %}
|
||||
|
||||
{% for dep in departures %}
|
||||
<div class="{% cycle 'bg_color1' 'bg_color2' %}">
|
||||
<h3>{{ dep.name }}</h3>
|
||||
<p>
|
||||
<em>Departs at</em>: {{ dep.departs_at }}<br>
|
||||
<em>Arrives at</em>: {{ dep.arrives_at }}<br>
|
||||
<em>Cars</em>: {{ dep.first_class}} FC,
|
||||
{{ dep.second_class }} SC
|
||||
({{ dep.seats_per_car }} seats/car)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% empty %}
|
||||
|
||||
{% if error %}
|
||||
|
||||
<div class=" error">
|
||||
<h3>Error</h3>
|
||||
<p>There was a problem connecting to the API.</p>
|
||||
<code>{{ error }}</code>
|
||||
<p>
|
||||
(<em>The above error is shown to the user as an example.
|
||||
For security reasons these errors are normally hidden from the user</em>)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% else %}
|
||||
|
||||
<div>
|
||||
<p>There are no departures available at this time.</p>
|
||||
</div>
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}
|
||||
<div class="footer">
|
||||
<a href="{% url 'stations' %}">Back to stations</a>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,26 @@
|
||||
{% extends "rails/base.html" %}
|
||||
|
||||
{% block title %}Home{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
|
||||
<h1>Wecome to our Railways website!</h1>
|
||||
|
||||
<p>Please choose which page you wish to visit below.</p>
|
||||
|
||||
<p>
|
||||
<a href="{% url 'stations' %}">Stations</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a href="{% url 'users' %}">Users</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a href="{% url 'authenticate' %}">Authentication</a>
|
||||
</p>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}{% endblock %}
|
||||
@@ -0,0 +1,52 @@
|
||||
{% extends "rails/base.html" %}
|
||||
|
||||
{% block title %}Stations{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
{% if stations %}
|
||||
<h1>Stations</h1>
|
||||
{% endif %}
|
||||
|
||||
{% for station in stations %}
|
||||
|
||||
<div class="{% cycle 'bg_color1' 'bg_color2' %}">
|
||||
<p>Id: {{ station.id }} <Code: {{ station.code }}
|
||||
({{ station.city }}, {{ station.country }})>
|
||||
<a href="{% url 'departures' station.id %}">Departures</a> -
|
||||
<a href="{% url 'arrivals' station.id %}"">Arrivals</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% empty %}
|
||||
|
||||
{% if error %}
|
||||
|
||||
<div class=" error">
|
||||
<h3>Error</h3>
|
||||
<p>There was a problem connecting to the API.</p>
|
||||
<code>{{ error }}</code>
|
||||
<p>
|
||||
(<em>The above error is shown to the user as an example.
|
||||
For security reasons these errors are normally hidden
|
||||
from the user</em>)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% else %}
|
||||
|
||||
<div>
|
||||
<p>There are no stations available at this time.</p>
|
||||
</div>
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}
|
||||
<div class="footer">
|
||||
<a href="{% url 'index' %}">Home</a>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,50 @@
|
||||
{% extends "rails/base.html" %}
|
||||
|
||||
{% block title %}Users{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
{% if users %}
|
||||
<h1>Users</h1>
|
||||
{% endif %}
|
||||
|
||||
{% for user in users %}
|
||||
|
||||
<div class="{% cycle 'bg_color1' 'bg_color2' %}">
|
||||
<p>Id: {{ user.id }} <{{ user.full_name }}
|
||||
(<a href="mailto: {{ user.email }})">{{ user.email }}</a>>
|
||||
{{ user.role|capfirst }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% empty %}
|
||||
|
||||
{% if error %}
|
||||
|
||||
<div class=" error">
|
||||
<h3>Error</h3>
|
||||
<p>There was a problem connecting to the API.</p>
|
||||
<code>{{ error }}</code>
|
||||
<p>
|
||||
(<em>The above error is shown to the user as an example.
|
||||
For security reasons these errors are normally hidden from the user</em>)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{% else %}
|
||||
|
||||
<div>
|
||||
<p>There are no users available at this time.</p>
|
||||
</div>
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% endfor %}
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}
|
||||
<div class="footer">
|
||||
<a href="{% url 'index' %}">Home</a>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,4 @@
|
||||
# apic/rails/tests.py
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
@@ -0,0 +1,32 @@
|
||||
# apic/rails/urls.py
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.IndexView.as_view(), name="index"),
|
||||
path(
|
||||
"stations", views.StationsView.as_view(), name="stations"
|
||||
),
|
||||
path(
|
||||
"stations/<int:station_id>/departures",
|
||||
views.DeparturesView.as_view(),
|
||||
name="departures",
|
||||
),
|
||||
path(
|
||||
"stations/<int:station_id>/arrivals",
|
||||
views.ArrivalsView.as_view(),
|
||||
name="arrivals",
|
||||
),
|
||||
path("users", views.UsersView.as_view(), name="users"),
|
||||
path(
|
||||
"authenticate",
|
||||
views.AuthenticateView.as_view(),
|
||||
name="authenticate",
|
||||
),
|
||||
path(
|
||||
"authenticate/result",
|
||||
views.AuthenticateResultView.as_view(),
|
||||
name="auth_result",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,169 @@
|
||||
# apic/rails/views.py
|
||||
from datetime import datetime
|
||||
from operator import itemgetter
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import requests
|
||||
from django.conf import settings
|
||||
from django.urls import reverse_lazy
|
||||
from django.views import generic
|
||||
from requests.exceptions import RequestException
|
||||
|
||||
from .forms import AuthenticateForm
|
||||
|
||||
|
||||
class IndexView(generic.TemplateView):
|
||||
template_name = "rails/index.html"
|
||||
|
||||
|
||||
class StationsView(generic.TemplateView):
|
||||
template_name = "rails/stations.html"
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
context = self.get_context_data(**kwargs)
|
||||
|
||||
api_url = urljoin(settings.BASE_API_URL, "stations")
|
||||
|
||||
try:
|
||||
response = requests.get(api_url)
|
||||
response.raise_for_status()
|
||||
except RequestException as err:
|
||||
context["error"] = err
|
||||
else:
|
||||
context["stations"] = response.json()
|
||||
|
||||
return self.render_to_response(context)
|
||||
|
||||
|
||||
class DeparturesView(generic.TemplateView):
|
||||
template_name = "rails/departures.html"
|
||||
|
||||
def get(self, request, station_id, *args, **kwargs):
|
||||
context = self.get_context_data(**kwargs)
|
||||
|
||||
api_url = urljoin(
|
||||
settings.BASE_API_URL,
|
||||
f"stations/{station_id}/departures",
|
||||
)
|
||||
|
||||
try:
|
||||
response = requests.get(api_url)
|
||||
response.raise_for_status()
|
||||
except RequestException as err:
|
||||
context["error"] = err
|
||||
else:
|
||||
trains = prepare_trains(response.json(), "departs_at")
|
||||
context["departures"] = trains
|
||||
|
||||
return self.render_to_response(context)
|
||||
|
||||
|
||||
class ArrivalsView(generic.TemplateView):
|
||||
template_name = "rails/arrivals.html"
|
||||
|
||||
def get(self, request, station_id, *args, **kwargs):
|
||||
context = self.get_context_data(**kwargs)
|
||||
|
||||
api_url = urljoin(
|
||||
settings.BASE_API_URL,
|
||||
f"stations/{station_id}/arrivals",
|
||||
)
|
||||
|
||||
try:
|
||||
response = requests.get(api_url)
|
||||
response.raise_for_status()
|
||||
except RequestException as err:
|
||||
context["error"] = err
|
||||
else:
|
||||
trains = prepare_trains(response.json(), "arrives_at")
|
||||
context["arrivals"] = trains
|
||||
|
||||
return self.render_to_response(context)
|
||||
|
||||
|
||||
class UsersView(generic.TemplateView):
|
||||
template_name = "rails/users.html"
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
context = self.get_context_data(**kwargs)
|
||||
|
||||
api_url = urljoin(
|
||||
settings.BASE_API_URL,
|
||||
"users",
|
||||
)
|
||||
|
||||
try:
|
||||
response = requests.get(api_url)
|
||||
response.raise_for_status()
|
||||
except RequestException as err:
|
||||
context["error"] = err
|
||||
else:
|
||||
context["users"] = response.json()
|
||||
|
||||
return self.render_to_response(context)
|
||||
|
||||
|
||||
class AuthenticateView(generic.FormView):
|
||||
template_name = "rails/authenticate.html"
|
||||
success_url = reverse_lazy("auth_result")
|
||||
form_class = AuthenticateForm
|
||||
|
||||
def form_valid(self, form):
|
||||
data = form.cleaned_data
|
||||
self.api_authenticate(data["email"], data["password"])
|
||||
# leave this as final instruction as it will just perform the redir.
|
||||
return super().form_valid(form)
|
||||
|
||||
def api_authenticate(self, email, password):
|
||||
api_url = urljoin(
|
||||
settings.BASE_API_URL,
|
||||
f"users/authenticate",
|
||||
)
|
||||
|
||||
payload = {
|
||||
"email": email,
|
||||
"password": password,
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(api_url, json=payload)
|
||||
response.raise_for_status()
|
||||
except RequestException as err:
|
||||
self.set_session_data("auth_error", str(err))
|
||||
else:
|
||||
key = "token" if response.ok else "auth_error"
|
||||
self.set_session_data(key, response.json())
|
||||
|
||||
def set_session_data(self, key, data):
|
||||
self.request.session[key] = data
|
||||
|
||||
|
||||
class AuthenticateResultView(generic.TemplateView):
|
||||
template_name = "rails/authenticate.result.html"
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
context = self.get_context_data(**kwargs)
|
||||
context["token"] = request.session.pop("token", None)
|
||||
context["auth_error"] = request.session.pop(
|
||||
"auth_error", None
|
||||
)
|
||||
return self.render_to_response(context)
|
||||
|
||||
|
||||
def prepare_trains(trains: list[dict], key: str):
|
||||
return list(
|
||||
map(
|
||||
parse_datetimes,
|
||||
sorted(trains, key=itemgetter(key)),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def parse_datetimes(train: dict):
|
||||
train["arrives_at"] = datetime.fromisoformat(
|
||||
train["arrives_at"]
|
||||
)
|
||||
train["departs_at"] = datetime.fromisoformat(
|
||||
train["departs_at"]
|
||||
)
|
||||
return train
|
||||
Reference in New Issue
Block a user