1
0
Fork 0
mirror of https://github.com/Findus23/RadioStats.git synced 2024-09-19 16:03:48 +02:00
RadioStats/server.py

50 lines
1.3 KiB
Python
Raw Normal View History

2018-02-07 13:47:48 +01:00
from flask import jsonify
from playhouse.shortcuts import model_to_dict
from app import app
from models import *
2018-02-08 10:56:30 +01:00
def query_to_response(query, limit=5, key=False, **kwargs):
2018-02-07 13:47:48 +01:00
"""
2018-02-08 10:56:30 +01:00
:type key: str
:type limit: int|boolean
2018-02-07 13:47:48 +01:00
:param **kwargs
:type query: peewee.ModelSelect
"""
if limit:
query = query.limit(limit)
print(query.sql())
2018-02-08 10:56:30 +01:00
data = {} if key is not False else []
2018-02-07 13:47:48 +01:00
for i in query:
2018-02-08 10:56:30 +01:00
element = model_to_dict(i, **kwargs)
if key is not False:
data[getattr(i, key)] = element
else:
data.append(element)
response = jsonify(data)
if __name__ == '__main__':
response.headers.add('Access-Control-Allow-Origin', '*')
return response
2018-02-07 13:47:48 +01:00
@app.route('/')
def index():
2018-02-08 10:56:30 +01:00
return query_to_response(Channel.select(), limit=False, key="shortname")
2018-02-07 13:47:48 +01:00
@app.route('/<channel>')
def popular(channel):
# range = request.args.get('')
2018-02-08 10:56:30 +01:00
get = Play.select(Play.song, fn.Count(SQL('*')).alias("count")) \
2018-02-07 13:47:48 +01:00
.join(Channel).switch(Play).join(Song) \
.where((Song.show == 0) & (Channel.shortname == channel)) \
2018-02-08 10:56:30 +01:00
.group_by(Play.song).order_by(SQL('count').desc())
return query_to_response(get, extra_attrs=["count"], exclude=[Play.channel, Play.time, Play.id])
2018-02-07 13:47:48 +01:00
if __name__ == '__main__':
2018-02-08 10:56:30 +01:00
app.debug = True
2018-02-07 13:47:48 +01:00
app.run()