Python の mimetypes.guess_type() で .geojson を変換できるようにする (original) (raw)
Python 標準ライブラリ mimetypes を使って GeoJSON ファイル名 (.geojson) から MIME タイプに変換しようとしたら (None, None)
になってしまった😇
import mimetypes mimetypes.guess_type('example.geojson') (None, None)
前提条件
- Python 3.12
mimetypes.types_map
を確認する
MIME タイプのマッピングは環境によって異なる場合があって,今回は macOS (Sonoma) と AWS Lambda 関数 (Python 3.12) で mimetypes.types_map
の値から JSON 関連のマッピングを確認してみた.やはり .geojson
のマッピングはなかった🥲
macOS (Sonoma)
{'.json': 'application/json', '.jsonml': 'application/jsonml+json'}
AWS Lambda 関数 (Python 3.12)
{'.json': 'application/json'}
mimetypes.add_type()
で追加する
mimetypes.add_type()
でマッピングを追加すれば OK👌
mimetypes.add_type('application/geo+json', '.geojson') mimetypes.guess_type('example.geojson') ('application/geo+json', None)
knownfiles を確認する
MIME タイプのマッピング (knownfiles) は mimetypes.knownfiles
で確認できる.
mimetypes.knownfiles ['/etc/mime.types', '/etc/httpd/mime.types', '/etc/httpd/conf/mime.types', '/etc/apache/mime.types', '/etc/apache2/mime.types', '/usr/local/etc/httpd/conf/mime.types', '/usr/local/lib/netscape/mime.types', '/usr/local/etc/httpd/conf/mime.types', '/usr/local/etc/mime.types']
macOS だと /etc/apache2/mime.types
に knownfiles があって,JSON 関連のマッピングを確認してみた.
mimetypes.types_map
の値と同じで application/json
と application/jsonml+json
はサポートされていて,application/geo+json
はコメントアウトになっていた💡
$ grep -i json /etc/apache2/mime.types
application/json json
application/jsonml+json jsonml
Python 3.13 だと
ちなみに Python 3.13 のドキュメントを読むと mimetypes.guess_type()
は soft deprecated(警告は出ずに引き続き使える非推奨)になっていて,今後は mimetypes.guess_file_type()
を使うことになりそう📝 覚えておこう〜
Deprecated since version 3.13: Passing a file path instead of URL is soft deprecated. Use guess_file_type() for this.
import mimetypes mimetypes.guess_file_type('example.json') ('application/json', None)