リモートワークで暇だったので、PythonのwebフレームワークであるFlaskとYoutube-dlを使って、Youtubeの動画をダウンロードできるサイトを作ってみました。
前提知識
・【Python】youtube-dlでmp4/mp3をYoutubeからダウンロードする
・【Python】FlaskによるWebアプリ開発①~簡単なWebページを表示させてみる
・【Python】FlaskによるWebアプリ開発③~formタグでのデータのGET/POST送信
ソースコード
<app.py>
from flask import Flask, render_template, request, send_file
from subprocess import call
# init_application
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/download_video')
def download_mp4():
url = request.args.get('url')
filename = 'test'
cmd = 'youtube-dl -o export_tmp/videos/' + \
filename + ' --no-cache-dir ' + url
call(cmd.split(' '), shell=False)
try:
return send_file(
'export_tmp\\videos\\test.mp4',
as_attachment=True,
attachment_filename='test.mp4',
mimetype='video/mp4'
)
except:
return send_file(
'export_tmp\\videos\\test.mkv',
as_attachment=True,
attachment_filename='test.mp4',
mimetype='video/mp4'
)
else:
return send_file(
'export_tmp\\videos\\test.webm',
as_attachment=True,
attachment_filename='test.mp4',
mimetype='video/mp4'
)
if __name__ == "__main__":
app.run(debug=True)
Youtube-dlコマンドの各種オプションについてはhttps://masayoshi-9a7ee.hatenablog.com/entry/20150905/1441414821にまとまっていて非常に分かりやすかったのでカスタマイズしたい場合はここを参考にしてください。
レンタルサーバーにデプロイするときにひっかったのは動画のダウンロードの際にキャッシュを/httpdの.cacheに書き込もうとしていて権限エラーになった点。
コマンド引数に--no-cache-dirを入れることでキャッシュを書き込まないようにすることで解決したましたが、気付かず結構手間取りました。
<index.html>
<!DOCTYPE html>
<html>
<head>
<title>YouTube ダウンローダー</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<h1 class="heading">YouTube ダウンローダー</h1>
<form action="/download_video" method="get">
<input class="URL-input" name='url' placeholder="Video URL e.g. https://www.youtube.com/watch?v=MtN1YnoL46Q">
<button type='submit' class="convert-button">mp4</button></a>
</form>
</body>
<script src='/static/js/script.js'></script>
</html>
<style.css>
* {
text-align: center;
}
.heading {
font-family: Arial;
margin-top:40vh;
}
.URL-input, .convert-button {
font-size:1.3em;
padding:5px 10px;
}
.URL-input {
border-radius:4px 0px 0px 4px;
width:30em;
text-align: left;
border:2px solid #EEEEEE;
background: #EEEEEE;
outline:none;
}
.URL-input:focus {
border:2px solid #0485ff;
}
.convert-button {
border-radius:0px 4px 4px 0px;
border:2px solid #0485ff;
background: #0485ff;
color:white;
}
ディレクトリ配置などについてはgithubにサンプルコードを上げているのにそちらを参考にしてください。
【Github】https://github.com/beginerSE/Youtube_downloader
完成したサイト→https://dl-fd8ac.firebaseapp.com/


コメント