Reputation: 1
I am trying to pass data via an http request through the flask python framework and insert it into mongodb with the help of pymongo.
My code is as such:
from flask import Flask, request
import json
from pymongo import MongoClient
from bson import json_util
from bson.objectid import ObjectId
#setting up the flask app
app=Flask(__name__)
#connecting to mongoDB
client=MongoClient('localhost', 27017)
db = client["test"] #db name
col=db["test"] #collection name
@app.route('/data/insert/', methods=['GET'])
def insert():
if request.method == 'GET':
result = request.data('docs')
col.insert(result)
return "it worked!\n"
if __name__=='__main__':
app.run()
I am passing data through the url:
127.0.0.1:5000/data/insert/docs={"hello":"world"}
the weird thing is that it's accepting the data and even spitting it back out when I try to simply return it in string format, but it needs to be converted or accessed in a way that I'm missing.
Ps. I already tried the proper escaped characters for the brackets and double-quotes.
Upvotes: 0
Views: 1874
Reputation: 55922
I'm guessing that result = request.data('docs')
is returning a string,
I believe insert
requires a dictionary, not a string
Perhaps, somethign like:
result = json.loads(request.data('docs'))
The above uses python's built in json
library to try and parse the docs
string into python datatypes. Remember to handle the case if docs
is invalid JSON!
Upvotes: 2