This repository has been archived on 2019-12-12. You can view files and clone it, but cannot push or open issues/pull-requests.
tildetown-scripts/tildetown-py/cgi.py

74 lines
1.7 KiB
Python
Raw Normal View History

2015-07-28 18:04:11 +00:00
import json
import os
2015-08-01 23:16:09 +00:00
import random
2015-07-28 18:04:11 +00:00
import time
from sys import argv
from tempfile import mkdtemp, mkstemp
from flask import Flask, render_template, request, redirect
2015-08-01 23:16:09 +00:00
from stats import get_data
2015-07-28 18:04:11 +00:00
SITE_NAME = 'tilde.town'
app = Flask('~cgi')
2015-08-01 23:16:09 +00:00
_site_context = None
def site_context():
if not _site_context:
_site_context = get_data()
return _site_context
2015-07-28 18:04:11 +00:00
def slurp(file_path):
contents = None
with open(file_path, 'r') as f:
contents = f.read()
return contents
def save_post(name, message):
timestamp = time.time()
data = {
'name': name,
'message': message,
'timestamp': timestamp,
}
_, file_path = mkstemp(dir=app.config['DATA_DIR'])
with open(file_path, 'w') as f:
f.write(json.dumps(data))
@app.route('/random', methods=['GET'])
def get_random():
2015-08-01 23:16:09 +00:00
user = random.choice(site_context()['live_users'])
return redirect('http://tilde.town/~{}'.format(user['username']))
2015-07-28 18:04:11 +00:00
@app.route('/guestbook', methods=['GET'])
def get_guestbook():
data_dir = app.config['DATA_DIR']
# TODO sort by timestamp
posts = map(lambda p: json.loads(slurp(os.path.join(data_dir, p))), os.listdir(data_dir))
2015-08-01 23:16:09 +00:00
context = {
2015-07-28 18:04:11 +00:00
"posts": posts,
}
2015-08-01 23:16:09 +00:00
context.update(site_context())
2015-07-28 18:04:11 +00:00
return render_template('guestbook.html', **context)
@app.route('/guestbook', methods=['POST'])
def post_guestbook():
save_post(request.form['name'], request.form['message'])
return redirect("/guestbook")
@app.route('/helpdesk', methods=['GET'])
def helpdesk():
2015-08-01 23:16:09 +00:00
return "HELPDESK UNDER CONSTRUCTION"
2015-07-28 18:04:11 +00:00
if __name__ == '__main__':
if len(argv) == 2:
data_dir = argv[1]
else:
data_dir = mkdtemp()
app.config['DEBUG'] = True
app.config['DATA_DIR'] = data_dir
app.run()