Thursday, January 17, 2019

MongoDB: Post method and return Response

DEF


CODE
===========================================
from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'esawal'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/esawal'

mongo = PyMongo(app)

# @app.route('/', methods=['GET'])
# def get_all_stars():
#   star = mongo.db["customers"]
#
#   output = []
#   for s in star.find():
#     output.append({'address' : s['address'], 'name' : s['name']})
#
#
#   return jsonify({'result' : output})

# FIND ONE
# @app.route('/<string:name>', methods=['GET'])
# def get_one_star(name):
#   star = mongo.db["customers"]
#   s = star.find_one({'name' : name})
#   output = []
#   if s:
#     output.append({'address': s['address'], 'name': s['name']})
#   else:
#     output = "No such name"
#   return jsonify({'result' : output})
#


@app.route('/', methods=['POST'])
def add_star():
  star = mongo.db["customers"]
  name = request.json['name']
  address = request.json['address']
  star_id = star.insert({'name': name, 'address': address})
  new_star = star.find_one({'_id': star_id })
  output = {'name' : new_star['name'], 'address' : new_star['address']}
  return jsonify({'result' : output})

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

REQUEST
===========================================

===========================================

RESPONSE
===========================================
{
    "result": {
        "address": "Saket Delhi",
        "name": "Divakar"
    }
}
===========================================

No comments:

Post a Comment