Monday, January 21, 2019

Debugger In Python

In Window

PyCharm

STEP-1: Toggle the line(Enabling debugging )
STEP-2: Right click on file --> Debug
STEP-3: Hit API from rest client like postman, advance rest client
STEP-4: Use F8 to move line by line or F9 to move toggle point by point.


Note - If debugging is not working in PyCharm.

STEP-1

for Windows and Linux
File | Settings | Build, Execution, Deployment | Python Debugger
for macOS
PyCharm | Preferences | Build, Execution, Deployment | Python Debugger

Shortcut - Ctrl+Alt+S

STEP-2

 and uncheck the option "PyQt compatible".


Saturday, January 19, 2019

MongoDB: Run on Manual IP Address



Def

CODE
===========================================
from flask import Flask
from flask import jsonify
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})


if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host='0.0.0.0', port=8000, debug=True) # It pick your system default IP
    # or You can enter manual IP address of your pc
    # app.run(host='192.168.1.102', port=8000, debug=True)

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


REQUEST AND RESPONSE
================================================

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

MongoDB: InsertMany


Def


CODE
==============================
from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
from bson.json_util import dumps

app = Flask(__name__)

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

mongo = PyMongo(app)


@app.route('/', methods=['POST'])
def add_star():
  try:
    myDB = mongo.db["customers"]

    try:
      if not request.json['name']:
        return jsonify({'responseCoe':400, 'message': 'Name is Empty'})
    except KeyError:
      return jsonify({'responseCoe': 400, 'message': 'Name not found'})

    try:
      if not request.json['address']:
        return jsonify({'responseCode':400, 'message': 'Address is Empty'})
    except KeyError:
      return jsonify({'responseCoe': 400, 'message': 'Address not found'})

    name = request.json['name']
    address = request.json['address']
    star_id = myDB.insert_one({'name': name, 'address': address})
    return jsonify({'result' : "Success"})
  except Exception:
      return dumps({'error': "400"})

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


OUTPUT
===============================

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

Friday, January 18, 2019

MongoDB : (InsertOne) If key not available in json

Def

CODE
==================================

from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
from bson.json_util import dumps

app = Flask(__name__)

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

mongo = PyMongo(app)


@app.route('/', methods=['POST'])
def add_star():
    try:
        myDB = mongo.db["customers"]

        try:
            if not request.json['name']:
                return jsonify({'responseCoe': 400, 'message': 'Name is Empty'})
        except KeyError:
            return jsonify({'responseCoe': 400, 'message': 'Name not found'})

        try:
            if not request.json['address']:
                return jsonify({'responseCode': 400, 'message': 'Address is Empty'})
        except KeyError:
            return jsonify({'responseCoe': 400, 'message': 'Address not found'})

        name = request.json['name']
        address = request.json['address']
        star_id = myDB.insert_one({'name': name, 'address': address})

        output = []
        for s in myDB.find():
            output.append({'name': name, 'address': address})
        return jsonify({'result': output})
    except Exception:
        return dumps({'error': "400"})


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

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


REQUEST & RESPONSE
==================================

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




MongoDB: Validation if value is empty


Def : If any key's value is empty then check validation



CODE
===================================
from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
from bson.json_util import dumps

app = Flask(__name__)

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

mongo = PyMongo(app)


@app.route('/', methods=['POST'])
def add_star():
  try:
    myDB = mongo.db["customers"]

    if not request.json['name']:
      return jsonify({'responseCoe':400, 'message': 'Name is Empty'})
    if not request.json['address']:
      return jsonify({'responseCode':400, 'message': 'Address is Empty'})

    name = request.json['name']
    address = request.json['address']
    star_id = myDB.insert_one({'name': name, 'address': address})
    return jsonify({'result' : "Success"})
  except Exception:
      return dumps({'error': "400"})

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

MongoDB : Delete multiple value

Def - We are


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=['DELETE'])
def add_star():
  myDB = mongo.db["customers"]
  name = request.json['name']
  # address = request.json['address']
  star_id = myDB.delete_many({'name': name})
  # OR TO DELETE ONE
  # new_star = myDB.find()
  star_id = myDB.delete_many({'name': name})
  output = []
  for s in myDB.find():
    output.append({'name' : s['name'], 'address' : s['address']})
  return jsonify({'result' : output})

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

OUTOUT
======================================

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


DELETE ONE
=======================================
star_id = myDB.delete_many({'name': name})
=======================================









MongoDB: Exception Handling

Def

Code
=============================
from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
from bson.json_util import dumps

app = Flask(__name__)

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

mongo = PyMongo(app)


@app.route('/', methods=['POST'])
def add_star():
  try:
    star = mongo.db["customers"]
    name = request.json['name']
    address = request.json['address']
    if name and address:
        star_id = star.insert({'name': name, 'address': address})
    return dumps({'message': 'SUCCESS'})
  except Exception:
    return dumps({'error' : "400"})

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


RESULT
===============================

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