LoginSignup
2
0

More than 5 years have passed since last update.

Dockerコンテナ上のPythonでファイルのmime-typeを識別したい

Last updated at Posted at 2018-03-17

やりたかったこと&この記事でやること

 Dockerコンテナ上で動作するflaskを使ったWebアプリケーションで、ファイルがアップロードされた時にそのファイルのmime-typeを知りたかった。ダウンロードするときにもmime-typeを指定しないとブラウザで画像表示ができないかも、と思ったため。
 そこで、とりあえずコンテナ上でファイルのmime-typeを取得できるか確認する。

構成

実装

Githubにて。https://github.com/touka9029/python_magic_docker

ポイントはAlpine Linuxのapk libmagicをDockerfileで追加する。
https://pkgs.alpinelinux.org/package/edge/main/x86/libmagic

FROM python:3.6.4-alpine3.7

RUN set -e; \
        apk add --no-cache --virtual .build-deps \
            libmagic \
            ; \
        pip install --upgrade pip; \
        pip install python-magic;

COPY testdata /testdata

python-magic が使えるか確認。
コンテナ立ち上げ&コンテナ上でシェル操作

docker-compose up -d --build
(--略--)
docker exec -ti python_magic sh

コンテナ上でpython実行

python3
Python 3.6.4 (default, Jan 10 2018, 05:20:21)
[GCC 6.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import magic
>>> magic.from_file("testdata/lena.jpg")
'JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, comment: "Created with GIMP", baseline, precision 8, 320x320, frames 3'

>>> magic.from_file("testdata/my_icon.png")
'PNG image data, 420 x 420, 8-bit/color RGB, non-interlaced'

>>> magic.from_file("testdata/my_icon.png", mime=True)
'image/png'

mime-type取得できました。

libmagicとはなんぞや?

This functionality is exposed to the command line by the Unix command file.

python-magicのUsageより引用。そもそもpython-magicはUnix commandのfileを拡張(ラッパー)したライブラリのようです。
fileコマンドはUnixでファイルの種類を調べる際に使うコマンドのようで、その時に使用しているのがlibmagicというパッケージなのかな、という認識です。

Windowsで使う場合はlibmagicに代わるdllファイルを所定のフォルダに配置しないといけないようですね。

2
0
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
2
0