-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathweb.py
51 lines (41 loc) · 1.38 KB
/
web.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import flask, youtube, requests
app = flask.Flask(__name__)
@app.route('/')
def home():
return flask.render_template('home.html')
@app.route('/api/search/<id>')
def search_by_id(id):
try:
return flask.jsonify({
'error': None,
'data': youtube.video(id)
})
except Exception, e:
raise ApiException(e)
@app.route('/download/<id>/')
@app.route('/download/<id>/<resolution>/')
@app.route('/download/<id>/<resolution>/<extension>/')
def download_by_id(id, resolution=None, extension=None):
stream = youtube.stream_url(id, resolution, extension)
binary = requests.get(stream['url'], stream=True)
return flask.Response(
binary,
headers={'Content-Disposition': 'attachment; '
'filename='+stream['filename']})
class ApiException(Exception):
pass
@app.errorhandler(ApiException)
def error(e):
return flask.jsonify({'error': str(e)}), 404
@app.errorhandler(Exception)
def error(e):
#FIXME: a decorator to avoid having to place a try/except block
# around each api function (eg. search_by_id)
if app.debug:
raise # triggers werkzeug debugger
else:
#FIXME: template this
return ('<h1><strong>404 - </strong>'
'Something went wrong, sorry.</h1>')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)