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
===============================

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

MongoDB: Collections name in db

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.collection_names()

  output = []
  for s in star:
    # output.append({'address' : s['address'], 'name' : s['name']})
    output.append(s)

  return jsonify({'result' : star})


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

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


RESULT
================================
{
  "result": [
    "insert", 
    "esawal", 
    "customers", 
    "flightData"
  ]
}
================================

Thursday, January 17, 2019

UseFull

For Installation Setup

https://www.w3schools.com/python/

All Docs
=====================
https://docs.mongodb.com/manual/reference/method/db.collection.find/
https://specify.io/systems/mongodb/features-and-usecases



WebSite

https://www.bogotobogo.com/python/MongoDB_PyMongo/python_MongoDB_RESTAPI_with_Flask.php

https://flask-pymongo.readthedocs.io/en/latest/

https://www.slideshare.net/slideshow/embed_code/13539139

https://help.pythonanywhere.com/pages/Flask/

http://flask.pocoo.org/docs/1.0/quickstart/#a-minimal-application

1. Find Query Help

https://specify.io/how-tos/find-documents-in-mongodb-using-the-mongo-shell


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"
    }
}
===========================================

MongoDB: Find One method


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)

# 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})


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

OUTPUT

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

{
  "result": [
    {
      "address": "Apple st 652",
      "name": "Amy"
    }
  ]
}

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




22

MongoDB: Find Query



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)
==============================

RESPONSE

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

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


MONGO DB Command line Output

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


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

Tuesday, January 15, 2019

Authentication

DEF

Library
=====================================================
There is a small Flask extension that can help with this, written by no other than yours truly. So let's go ahead and install Flask-HTTPAuth:
$ flask/bin/pip install flask-httpauth
=====================================================


CODE
=====================================================
from flask import Flask, jsonify
from flask import make_response
from flask_httpauth import HTTPBasicAuth


app = Flask(__name__)

auth = HTTPBasicAuth()

@app.route("/<string:username>",  methods=['GET'])
def get_auth(username):
    return get_password(username)

@auth.get_password
def get_password(username):
    if username == 'divakar':
        return 'python'
    return unauthorized()

#    return None   ------you can use this instead of return unauthorized()

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 401)

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

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


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

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


DETAIL-

The get_password function is a callback function that the extension will use to obtain the password for a given user. In a more complex system this function could check a user database, but in this case we just have a single user so there is no need for that.
The error_handler callback will be used by the extension when it needs to send the unauthorized error code back to the client. Like we did with other error codes, here we customize the response so that is contains JSON instead of HTML.
With the authentication system setup, all that is left is to indicate which functions need to be protected, by adding the @auth.login_required decorator. For example:
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
@auth.login_required
def get_tasks():
    return jsonify({'tasks': tasks})

22

DELETE Method

DEF

CODE
===============================================
from flask import Flask, jsonify
from flask import abort
from flask import request

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]


@app.route('/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    tasks.remove(task[0])
    return jsonify({'result': True})

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

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


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

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


RESPONSE
===============================================
{
    "result": true
}
===============================================

PUT method

DEF

Code
================================
from flask import Flask, jsonify
from flask import abort
from flask import request

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]


@app.route('/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    if not request.json:
        abort(400)
    if 'title' in request.json and type(request.json['title']) != str:
        abort(400)
    if 'description' in request.json and type(request.json['description']) is not str:
        abort(400)
    if 'done' in request.json and type(request.json['done']) is not bool:
        abort(400)
    task[0]['title'] = request.json.get('title', task[0]['title'])
    task[0]['description'] = request.json.get('description', task[0]['description'])
    task[0]['done'] = request.json.get('done', task[0]['done'])
    return jsonify({'task': task[0]})

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

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

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

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

RESPONSE
===============================
{
    "task": {
        "description": "Milk, Cheese, Pizza, Fruit, Tylenol",
        "done": false,
        "id": 2,
        "title": "Buy groceries"
    }
}

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

Insert using POST method


DEF -

CODE
====================================
from flask import Flask, jsonify
from flask import abort
from flask import request

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]


@app.route('/', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        abort(400)
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)
    return jsonify({'task': task}), 201


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

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


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

RESPONSE
=======================================================

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



Monday, January 14, 2019

Error format

By Deault Error



To Get Error in JSON format.

use below code-

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

from flask import Flask, jsonify
from flask import make_response
from flask import abort

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

@app.route("/<int:task_id>",  methods=['GET'])
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    return jsonify({'task': task[0]})


@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

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

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

OutPut







22

Simple GET method with ID


Def -


from flask import Flask, jsonify
from flask import abort

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

@app.route("/<int:task_id>",  methods=['GET'])
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    return jsonify({'task': task[0]})



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



==================>OUTPUT<==================




2.










22

Simple GET API

from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

@app.route("/")
def hello():

    return jsonify({'task': tasks})


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



=====================output



22