1
1

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.

PythonのRequestsで一つのキーに複数画像のリストを持たせて投げる

Last updated at Posted at 2019-06-13

方法

{('images', open('sample1.jpg', 'rb')), ('images', open('sample2.jpg', 'rb'))}

として渡すと['images']に配列として入って渡される。

サンプルコードではFlaskでサーバーを立てて受け取る。

環境

  • Python 3.7.0
  • Flask 1.0.3
  • requests 2.22.0

サンプルコード

sample_request.py
import requests

file_path_list = ['sample1.jpg', 'sample2.jpg']
files = {('images', open(file, 'rb')) for file in file_path_list}
res = requests.post('http://127.0.0.1:5000/post', files=files)

print(res.status_code)
print(res.json())
server.py
import flask
from flask import Flask, abort, jsonify, request

app = Flask(__name__)


@app.route('/post', methods=['POST'])
def post():
    if not request.files:
        abort(400)

    files = request.files.getlist('images')
    print(files)
    return jsonify({'message': 'ok'})


if __name__ == '__main__':
    app.debug = True
    app.run()

実行

$ python server.py
 * Serving Flask app "server" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 251-266-307

上記のように待機している状態で以下を実行。

$ python sample_request.py
200
{'message': 'ok'}

配列として渡される。

$ python server.py
...略
[<FileStorage: 'sample1.jpg' (None)>, <FileStorage: 'sample2.jpg' (None)>]
127.0.0.1 - - [14/Jun/2019 01:43:04] "POST /post HTTP/1.1" 200 -
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?