Python: how to store data in mongo via http put

I am trying to create a REST API application using the python framework

I would like to be able to embed data in mongodb through an HTTP PUT request.

So far, I can get a response from mongodb using HTTP GET.

Please help me insert INSERT data into mongodb via HTTP PUT.

JSON format I need to insert the following:

{"_id": "id_1", "key_1": "value_1"} 

[I use this extension to get and put an http response]

 import json import bottle from bottle import route, run, request, abort from pymongo import Connection connection = Connection('localhost', 27017) db = connection.mydatabase @route('/documents', method='PUT') def put_document(): data = request.body.readline() if not data: abort(400, 'No data received') entity = json.loads(data) if not entity.has_key('_id'): abort(400, 'No _id specified') try: db['documents'].save(entity) except ValidationError as ve: abort(400, str(ve)) @route('/documents/:id', method='GET') def get_document(id): entity = db['documents'].find_one({'_id':id}) if not entity: abort(404, 'No document with id %s' % id) return entity run(host='localhost', port=8080) 
+4
source share
1 answer

The following revised version of your code works as you expected:

 import json from bottle import route, run, request, abort from pymongo import Connection connection = Connection('localhost', 27017) db = connection.mydatabase @route('/documents', method='PUT') def put_document(): data = request.body.readline() print(data) if not data: abort(400, 'No data received') entity = json.loads(data) if not entity.has_key('_id'): abort(400, 'No _id specified') try: db.documents.insert(entity) except ValidationError as ve: abort(400, str(ve)) @route('/documents/<_id>', method='GET') def get_document(_id): entity = db.documents.find_one({'_id': _id}) if not entity: abort(404, 'No document with id %s' % _id) return entity run(host='localhost', port=8080) 

I have MongoDB executing and executing a script, running the server on localhost port 8080 , I then execute the following commands in the shell with the expected results:

 $ echo '{"_id": "id_1", "key_1": "value_1", "key_2": "value_2"}' | curl -X PUT -d @- http://localhost:8080/documents $ curl http://localhost:8080/documents/id_1 {"_id": "id_1", "key_1": "value_1", "key_2": "value_2"} 
+2
source

Source: https://habr.com/ru/post/1438483/


All Articles