Friday, January 18, 2019

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