flask bank restful api
1 minute read
BANK rest api
# flask , flask_restful, pymongo, bcrypt library
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
from pymongo import MongoClient
import bcrypt
# Create Flask object
# Create flask_restful object with Flask object input
app = Flask(__name__)
api = Api(app)
# Create MongoClient object
# Create new mongo db MoneyManagementDB
# Create new collections users
client = MongoClient("mongodb://db:27017")
db = client.MoneyManagementDB
users = db["Users"]
# Create Register resource
class Register(Resource):
# post method
def post(self):
# from flask request.get_json()
#Step 1 is to get posted data by the user
postedData = request.get_json()
#Get the data
username = postedData["username"]
password = postedData["password"] #"123xyz"
# if user doesn't exist in db, 301 status returns
if UserExist(username):
retJson = {
'status':301,
'msg': 'Invalid Username'
}
return jsonify(retJson)
# password encrypted
hashed_pw = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
# user collections inserts the new person in users collections
#Store username and pw into the database
users.insert({
"Username": username,
"Password": hashed_pw,
"Own":0,
"Debt":0
})
retJson = {
"status": 200,
"msg": "You successfully signed up for the API"
}
return jsonify(retJson)
# return debt from user['Username'][0]['Debt']
def debtWithUser(username):
debt = users.find({
"Username":username
})[0]["Debt"]
return debt
def generateReturnDictionary(status, msg):
retJson = {
"status": status,
"msg": msg
}
return retJson
# mongodb collection_name.update method
# update mongo db Own field in user collections
def updateAccount(username, balance):
users.update({
"Username": username
},{
"$set":{
"Own": balance
}
})
def updateDebt(username, balance):
users.update({
"Username": username
},{
"$set":{
"Debt": balance
}
})
api.add_resource(Register, '/register')
api.add_resource(Add, '/add')
api.add_resource(Transfer, '/transfer')
api.add_resource(Balance, '/balance')
api.add_resource(TakeLoan, '/takeloan')
api.add_resource(PayLoan, '/payloan')
if __name__=="__main__":
app.run(host='0.0.0.0')
docker yml file
version: '3'
services:
web:
build: ./web
ports:
- "5000:5000"
links:
- db
db:
build: ./db