This commit is contained in:
adii1823
2021-10-28 17:41:38 +05:30
parent 03bb4d43c0
commit 0a0ceaf7d7
51 changed files with 2945 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
# apic/rails/__init__.py
+4
View File
@@ -0,0 +1,4 @@
# apic/rails/admin.py
from django.contrib import admin
# Register your models here.
+7
View File
@@ -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"
+9
View File
@@ -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
)
+1
View File
@@ -0,0 +1 @@
# apic/rails/migrations/__init__.py
+4
View File
@@ -0,0 +1,4 @@
# apic/rails/models.py
from django.db import models
# Create your models here.
+29
View File
@@ -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 %}
+17
View File
@@ -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 }} &lt;Code: {{ station.code }}
({{ station.city }}, {{ station.country }})&gt;&nbsp;
<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 }} &lt;{{ user.full_name }}
(<a href="mailto: {{ user.email }})">{{ user.email }}</a>&gt;
{{ 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 %}
+4
View File
@@ -0,0 +1,4 @@
# apic/rails/tests.py
from django.test import TestCase
# Create your tests here.
+32
View File
@@ -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",
),
]
+169
View File
@@ -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