Move web application in a separate module
This commit is contained in:
83
balises.py
83
balises.py
@@ -4,31 +4,13 @@ from argparse import ArgumentParser
|
||||
import datetime as dt
|
||||
|
||||
import bs4
|
||||
import locale
|
||||
import requests
|
||||
import os
|
||||
import urllib.parse
|
||||
|
||||
from bottle import hook, request, route, run, static_file, view
|
||||
|
||||
from config import conf
|
||||
import models
|
||||
from models import Song, AirCast, DoesNotExist
|
||||
from utils import http_get
|
||||
import webapp
|
||||
|
||||
project_dir = os.path.dirname(__file__)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Util functions
|
||||
|
||||
def http_get(url):
|
||||
response = requests.get(url);
|
||||
if response.status_code == 200:
|
||||
pass
|
||||
else:
|
||||
print('Uh, oh, unable to fetch', url)
|
||||
print('Http status code:', response.status_code)
|
||||
raise Error('Download error')
|
||||
return response
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
@@ -77,65 +59,6 @@ def print_aircast(x):
|
||||
print(line_template.format(str(x.date), x.song.artist, x.song.title))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Web application
|
||||
#
|
||||
# Very simple, just a page with an input for a date/time, a query button and a
|
||||
# list of results
|
||||
|
||||
@route('/', method=['GET', 'POST'])
|
||||
@view('search_results')
|
||||
def results_page():
|
||||
try:
|
||||
day = dt.date.fromisoformat(request.forms.date)
|
||||
except ValueError:
|
||||
day = dt.datetime.now().date()
|
||||
|
||||
try:
|
||||
hour = int(request.forms.time.split(':')[0])
|
||||
except ValueError:
|
||||
hour = dt.datetime.now().hour
|
||||
|
||||
delta = int(request.forms.timedelta or 0)
|
||||
hour = hour + delta
|
||||
time = '{:0>2}:00'.format(hour)
|
||||
results = [
|
||||
{ 'date': x.date,
|
||||
'song': x.song,
|
||||
'youtube_url': 'https://www.youtube.com/results?search_query=' +
|
||||
urllib.parse.quote_plus(x.song.artist + ' ' + x.song.title)
|
||||
}
|
||||
for x in search_song(day, hour)
|
||||
]
|
||||
return dict(results=results,
|
||||
date=day,
|
||||
time=time,
|
||||
start_time=time,
|
||||
end_time = '{:0>2}:00'.format(hour+1))
|
||||
|
||||
@route('/static/<filename>')
|
||||
def serve_static_file(filename):
|
||||
static_root = os.path.join(project_dir, 'static')
|
||||
return static_file(filename, root=static_root)
|
||||
|
||||
@hook('before_request')
|
||||
def set_locale():
|
||||
"""Set the locale for all categories to the first lang in Accept-Language
|
||||
header. Default to fr_FR.UTF-8
|
||||
"""
|
||||
accept_language = request.get_header('Accept-Language', 'fr-FR')
|
||||
first_lang = accept_language.split(';')[0].split(',')[0]
|
||||
lang = first_lang.translate(str.maketrans('-', '_')) + '.UTF-8'
|
||||
locale.setlocale(locale.LC_ALL, lang)
|
||||
|
||||
@hook('before_request')
|
||||
def connect_to_db():
|
||||
models.db.connect()
|
||||
|
||||
@hook('after_request')
|
||||
def close_db_connection():
|
||||
models.db.close()
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Argument parsing
|
||||
# use a decorator to simplify argparse usage, as suggested by
|
||||
@@ -171,7 +94,7 @@ def update(args):
|
||||
|
||||
@subcommand()
|
||||
def serve(args):
|
||||
run(host=conf['server'].get('host', 'localhost'),
|
||||
webapp.run(host=conf['server'].get('host', 'localhost'),
|
||||
port=conf['server'].getint('port', 9980),
|
||||
debug=conf['server'].getboolean('debug', False),
|
||||
reloader=conf['server'].getboolean('reloader', False))
|
||||
|
||||
15
utils.py
Normal file
15
utils.py
Normal file
@@ -0,0 +1,15 @@
|
||||
import requests
|
||||
import os
|
||||
|
||||
def http_get(url):
|
||||
response = requests.get(url);
|
||||
if response.status_code == 200:
|
||||
pass
|
||||
else:
|
||||
print('Uh, oh, unable to fetch', url)
|
||||
print('Http status code:', response.status_code)
|
||||
raise Error('Download error')
|
||||
return response
|
||||
|
||||
def project_dir():
|
||||
return os.path.dirname(__file__)
|
||||
70
webapp.py
Normal file
70
webapp.py
Normal file
@@ -0,0 +1,70 @@
|
||||
from bottle import hook, request, route, run, static_file, view
|
||||
import models
|
||||
from models import Song, AirCast
|
||||
from balises import search_song
|
||||
from utils import project_dir
|
||||
|
||||
import datetime as dt
|
||||
import locale
|
||||
import os
|
||||
import urllib.parse
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Web application
|
||||
#
|
||||
# Very simple, just a page with an input for a date/time, a query button and a
|
||||
# list of results
|
||||
|
||||
@route('/', method=['GET', 'POST'])
|
||||
@view('search_results')
|
||||
def results_page():
|
||||
try:
|
||||
day = dt.date.fromisoformat(request.forms.date)
|
||||
except ValueError:
|
||||
day = dt.datetime.now().date()
|
||||
|
||||
try:
|
||||
hour = int(request.forms.time.split(':')[0])
|
||||
except ValueError:
|
||||
hour = dt.datetime.now().hour
|
||||
|
||||
delta = int(request.forms.timedelta or 0)
|
||||
hour = hour + delta
|
||||
time = '{:0>2}:00'.format(hour)
|
||||
results = [
|
||||
{ 'date': x.date,
|
||||
'song': x.song,
|
||||
'youtube_url': 'https://www.youtube.com/results?search_query=' +
|
||||
urllib.parse.quote_plus(x.song.artist + ' ' + x.song.title)
|
||||
}
|
||||
for x in search_song(day, hour)
|
||||
]
|
||||
return dict(results=results,
|
||||
date=day,
|
||||
time=time,
|
||||
start_time=time,
|
||||
end_time = '{:0>2}:00'.format(hour+1))
|
||||
|
||||
@route('/static/<filename>')
|
||||
def serve_static_file(filename):
|
||||
static_root = os.path.join(project_dir(), 'static')
|
||||
return static_file(filename, root=static_root)
|
||||
|
||||
@hook('before_request')
|
||||
def set_locale():
|
||||
"""Set the locale for all categories to the first lang in Accept-Language
|
||||
header. Default to fr_FR.UTF-8
|
||||
"""
|
||||
accept_language = request.get_header('Accept-Language', 'fr-FR')
|
||||
first_lang = accept_language.split(';')[0].split(',')[0]
|
||||
lang = first_lang.translate(str.maketrans('-', '_')) + '.UTF-8'
|
||||
locale.setlocale(locale.LC_ALL, lang)
|
||||
|
||||
@hook('before_request')
|
||||
def connect_to_db():
|
||||
models.db.connect()
|
||||
|
||||
@hook('after_request')
|
||||
def close_db_connection():
|
||||
models.db.close()
|
||||
Reference in New Issue
Block a user