4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

X-SendFileを用いて静的ファイルをサーブ

Last updated at Posted at 2014-01-10

情報の鮮度

  • 2014-01-10時点
  • Debian GNU/Linux 7.3 (wheezy)/Ubuntu 13.10
  • Python 2.7 (apt-get経由)
  • django 1.4〜1.5

バックグラウンドとmod_auth_tkt の問題

こちらの続きです。
http://qiita.com/amedama/items/3f2197cadc1ea7d6374e

  • djangoのWebサイト上に動的に増減するプロジェクトがあるとします
    • 例えばRedmineみたいなプロジェクト管理ソフトを作るとしましょ
  • プロジェクトに参加しているユーザにだけ静的ファイルを見せたいことがあります
  • このシナリオに mod_auth_tkt はマッチしません
    • TKTAuthToken の値を動的に変更するのが面倒というか、そのまんまだと割と無理というか……
    • Apacheの環境変数を %{ENV:SOMETHING} みたいに指定できないんですよね、実装みた限り。
    • 2.4 から Define が導入されたということで、使える、かも、しれませんが
    • 一瞬本気でmod_auth_tktを修正しようと思ったんですが、さいきん全然開発されてないのな。
  • ていうか管理めんどいじゃー!
    • apacheの設定で使う定数とdjangoの定数を共有させてくれー

X-SendFile

で、X-SendFileです。

これがResponseヘッダに含まれていると、WSGIアプリの配下のWebサーバ、つまり今回はApacheが、
ユーザに応答を返す前に勝手にそのパスを展開してユーザにファイルを送り始める、というもんです。
nginx周りの記事の方が多いのですが、べつにモジュール入れればApacheでも動きます。

パフォーマンスに関する評価は、……もちろんスルー。

DBにファイルが含まれてたりすると多分ダメです。

Debian/UbuntuのApache2の場合は libapache2-mod-xsendfile を入れます。

# prepare "@project_member_required" by yourself
@login_required
@project_member_required
def download_project_file(request, project_name, file_name):
    response = HttpResponse()
    # prepare this function by yourself
    download_path = construct_path_from_file_name(file_name))
    response['X-Sendfile'] = download_path
    response['Content-Type'] = ''
    return response

上記の場合、

  • ログインしてなければログイン画面が出ます。
  • プロジェクトメンバーでなければ @project_member_required が怒ります (という風に作ります)
  • ファイルがなければApacheがその場で怒ります。

Apacheの設定上で

XSendFile on
XSendFilePath /opt/yourproject/downloads

とかやると /opt/yourproject/downloads がホワイトリストに登録されます。
逆に言うと、パスの指定を間違えると何も送信されません。

参考: https://tn123.org/mod_xsendfile/

おまけ

django-sendfile (https://github.com/johnsensible/django-sendfile)

"django X-SendFile" のググり結果で先頭に出てくるのですが地雷です。
これはdjango上でファイルを読み込んで展開してコンテンツで返す実装で、効率的とは程遠いものです。

最後に

コメントをお待ちしております。

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?