0
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 1 year has passed since last update.

HTTPリクエストで受け取ったデータをMongoDBに格納する

Posted at

ESP32からHTTPリクエストで受け取ったデータをMongoDBに格納します.

サーバー側

サーバー側でapp.pyを作成して実行させておきます.

app.py
from flask import Flask, request
from pymongo import MongoClient

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
client = MongoClient('mongodb://localhost:27017/')
db = client['iot_data']
collection1 = db['data']

@app.route('/data', methods = ['POST'])
def save_data():
    chunk_size = 1024
    file_data = b''

    file_size = int(request.headers.get('Content-Length'))

    while file_size > 0:
        chunk = request.stream.read(chunk_size)
        file_data += chunk
        file_size -= len(chunk)

    chunk_count = len(file_data) // chunk_size
    for i in range(chunk_count + 1):
        start = i * chunk_size
        end = start + chunk_size
        chunk_data = file_data[start:end]

    image_id = collection1.insert_one({'image': chunk_data}).inserted_id
    return 'Data saved successfully!', 201

if __name__ == '__main__':
    app.run(host='0.0.0.0', port = 5000)

以下のコマンドで常時バックグラウンド実行させておけば,実験の際にsshして動かす手間を省けます.

$ nohup python3 app.py &

ESP側

以下のコードでHTTPリクエストでサーバーに送信します.サーバーと同一のネットワークに接続してください.
ここではimage_dataを送っています.お好きなデータに置き換えてください.

send()
def send():
    image_data = mkb()
    url = 'http://192.168.100.140:5000/data'
    files = {'image':('received_image.jpg',image_data)}

    try:
        response = urequests.post(url, json=files)
        if response.status_code == 201:
            print('Data saved successfully')
        else:
            print('Failed to save data.')
        response.close()
    except Exception as e:
        print(e)
        pass
0
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
0
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?