LoginSignup
1
0

More than 1 year has passed since last update.

postされたファイル(画像やExcelファイル等)をDBに登録

Last updated at Posted at 2022-08-09

postされたファイルをDBに登録

①request.filesで取得したファイルをbyte型に変換する。

qiita.py
f = request.files['filename'].stream
file = bytes(f)

②pandasのDataFrameを利用し、DBに登録する。

pandasとsqlalchemyはインストールしておく。

$ pip install pandas
$ pip install sqlalchemy

DB登録までのソース。

qiita.py
import pandas as pd
from sqlalchemy import create_engine

#接続文字列 user、passwd、localhost、databaseをそれぞれ今回の対象に入れ替える。
engine = create_engine('mysql://user:passwd@localhost/database?charset=utf8')
#DataFrameにファイルを格納
#この時 if_exists がappendだとinsertされる
#tablenameを入れたいテーブルに入れ替える
#かっこがないとインデックスのエラーが出るので、必ず使うこと→{'file':[file]}
df = pd.DataFrame({'file':[file]})
#データ更新部分
df.to_sql(
           name = 'tablename',
           con = engine,
           if_exists='append', 
           index = False,
           chunksize = 10000,
           method = "multi",
          )

※ファイルを格納するデータ型は、Blob型に。

insert文に直接「%s」でファイルをバイト変換したを組み込み、実行してみたが書き方が間違っているといわれ
色々試してみたが正解が見つけられなかった。
なので、pandasを使ってみたが個人的にはSQL文を直書きしたい人間なので微妙な感じ。
まだPythonを触れて、一週間前後なのでもしかしたら見つかるかもしれない。

Part2(https://qiita.com/v4ns/items/18df62d59a4cb6c6d843)

1
0
2

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