Skip to content

Commit

Permalink
Merge pull request #212 from Sakuten/feature/183-generate-media-to-an…
Browse files Browse the repository at this point in the history
…nounce

`/render_results`エンドポイントの追加
  • Loading branch information
shino authored Sep 14, 2018
2 parents 0248a7e + 15875c2 commit ca9345a
Show file tree
Hide file tree
Showing 7 changed files with 320 additions and 15 deletions.
45 changes: 31 additions & 14 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class BaseConfig(object):
(time(8, 50), time(9, 20)),
(time(10, 15), time(10, 45)),
(time(12, 25), time(12, 55)),
(time(13, 50), time(14, 20)),
(time(13, 50), time(14, 20))
]
ONE_DAY_KIND = ['visitor']

Expand Down
54 changes: 54 additions & 0 deletions api/routes/api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from itertools import chain
from jinja2 import Environment, FileSystemLoader

from flask import Blueprint, jsonify, g, request, current_app
from api.models import Lottery, Classroom, User, Application, db, group_member
Expand Down Expand Up @@ -407,6 +408,59 @@ def check_id(classroom_id, secret_id):
return jsonify({"status": application.status})


@bp.route('/render_results', methods=['GET'])
@spec('api/results.yml')
def results():
"""return HTML file that contains the results of previous lotteries
This endpoint will be used for printing PDF
which will be put on the wall.
whoever access here can get the file. This is not a problem because
those infomations are public.
"""
# 1. Get previous time index
# 2. Get previous lotteries using index
# 3. Search for caches for those lotteries
# 4. If cache was found, return it
# 5. Make 2 public_id lists, based on user's 'kind'('student', 'visitor')
# 6. Send them to the jinja template
# 8. Caches that file locally
# 9. Return file

def public_id_generator(lottery, kind):
"""return list of winners' public_id for selected 'kind'
original at: L.336, written by @tamazasa
"""
for app in lottery.application:
if app.status == 'won' and app.user.kind == kind:
yield encode_public_id(app.user.public_id)

# 1.
try:
index = get_prev_time_index()
except (OutOfHoursError, OutOfAcceptingHoursError):
return error_response(6) # not acceptable time
# 2.
lotteries = Lottery.query.filter_by(index=index)

# 5.
whole_results = {'visitor': [], 'student': []}
for kind in whole_results.keys():
for lottery in lotteries:
public_ids = list(public_id_generator(lottery, kind))
cl = Classroom.query.get(lottery.classroom_id)
result = {'classroom': f'{cl.grade}{cl.get_classroom_name()}',
'winners': public_ids}
whole_results[kind].append(result)
data = {'kinds': [], 'horizontal': 3}
for key, value in whole_results.items():
data['kinds'].append({'lotteries': value, 'kind': key})

# 6.
env = Environment(loader=FileSystemLoader('api/templates'))
template = env.get_template('results.html')
return template.render(data)


@bp.route('/health')
@spec('api/health.yml')
def health():
Expand Down
14 changes: 14 additions & 0 deletions api/spec/routes/api/results.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
return PDF file that contains the results of previous lotteries
---
produces:
- application/pdf
responses:
'200':
description: PDF file which contains whole winners for previous winners
schema:
type: file
'400':
description: not acceptable time
schema:
$ref: '#/definitions/ErrorMessage'
summary: return PDF file that contains the results of previous lotteries
76 changes: 76 additions & 0 deletions api/templates/results.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
</head>
<style>
body {
color: gray;
}
:root {
--a0-height: 1133.5mm;
--a0-width: 806mm;
}
html {
font-size: 15mm;
font-family: 'MS Gothic';
}
.one_page {
height: var(--a0-height);
color: black;
}
.inner-page {
margin: 35mm;
}
.kind {
font-size: 3em;
border: 1.5mm solid;
padding: 7mm 10mm;
}
.winner {
font-size: 2em;
font-weight: bold;
line-height: 1.7;
margin: 3mm 20mm 7mm 30mm;
}
.classroom {
font-size: 3em;
font-weight: bold;
margin: 90mm 45mm;
}
li {
display: inline;
}
</style>
<body>
{% for kind in kinds %}
{% for lottery in kind['lotteries'] %}
<div class="one_page">
<div class="inner-page">
<p style="margin-bottom: 30mm">
<span class="kind">
{% set kind = '来場者' if kind['kind'] == 'visitor' else '生徒' %}
{{ kind }}
</span>
</p>
<p>
<span class="classroom" style="text-decoration: underline;">
{{ lottery['classroom'] }}
</span>
</p>
<div class="container">
<ul>
{% for winner in lottery['winners'] %}
<li>
<span class="winner">{{winner}}</span>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endfor %}
{% endfor %}
</body>
</html>
77 changes: 77 additions & 0 deletions scripts/apply_ramdom.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
import sys
import os
sys.path.append(os.getcwd()) # noqa: E402
from cards.id import load_id_json_file
from urllib.request import Request, urlopen
from urllib.error import HTTPError
from pathlib import Path
import json


class client():
def get(self, _url, _json=None, follow_redirects=False, headers=None):
default_headers = {"Content-Type": "application/json"}
if headers:
default_headers.update(headers)
json_data = json.dumps(_json).encode("utf-8") if _json else None

url = f'http://localhost:8888{_url}'
request = Request(url, data=json_data,
headers=default_headers, method='GET')
try:
response = urlopen(request)
except HTTPError as e:
print('Error: {}'.format(e.read()), file=sys.stderr)
sys.exit(-1)
else:
response_body = response.read().decode("utf-8")
response.close()
return json.loads(response_body)

def post(self, _url, _json=None, follow_redirects=False, headers=None):
default_headers = {"Content-Type": "application/json"}
if headers:
default_headers.update(headers)
json_data = json.dumps(_json).encode("utf-8") if _json else None
url = f'http://localhost:8888{_url}'
request = Request(url, data=json_data,
headers=default_headers, method='POST')

try:
response = urlopen(request)
except HTTPError as e:
print('Error: {}'.format(e.read()), file=sys.stderr)
sys.exit(-1)
else:
response_body = response.read().decode("utf-8")
response.close()
return json.loads(response_body)


def login(client, secret_id, rresp):
return client.post('/auth', _json={
"id": secret_id,
"g-recaptcha-response": rresp
}, follow_redirects=True)


client = client()


id_list = load_id_json_file(Path(__file__).parent.parent /
Path('cards/test_users.json'))
users = [i for i in id_list if i['authority'] == 'normal']

lotteries = client.get('/lotteries/available')

for lottery in lotteries:
print(f'applying to {lottery["id"]}: ', end='')
for user in users:
token = login(client, user['secret_id'], '')['token']
client.post(f'/lotteries/{lottery["id"]}', _json={"group_members": ""},
headers={"Authorization": f"Bearer {token}"})
print('.', end='')
print(' DONE')

print('all lotteries are treated')
Loading

0 comments on commit ca9345a

Please sign in to comment.