I wrote this simple API to be able to send logs from the client to MongoDB. Even though this works and fits my need, I would like to point out some concerns that I have regarding the following:
- Is it efficient to be calling the instance of MongoClient for every request?
- Do I need to close the instance of MongoClient after the request is successful?
- A more Pythonic way to return responses?
from flask import Flask, jsonify, request, Response
from flask_restful import Resource, Api
from pymongo import MongoClient
import json
app = Flask(__name__)
api = Api(app)
USER = "user"
PASS = "pw"
MONGO_URI = 'mongodb://%s:%[email protected]/test' % (USER, PASS)
PORT = 19788
def db_conn():
client = MongoClient(MONGO_URI, PORT)
return client
def insert_record(args):
client = db_conn()
replycode = 0
try:
db = client['test']
posts = db.users
posts.insert(args)
except:
replycode = 1
return replycode
def select_record(args={}):
client = db_conn()
db = client['test']
result = db.users.find(args)
return result
class CreatUser(Resource):
def post(self):
try:
content = request.get_json()
if "Vehicle" not in content:
return jsonify({"Result": "Vehicle number not in passed arguments"}), 400
else:
vehicle = content['Vehicle']
reply = insert_record(content)
if reply == 0:
return jsonify({"Result" : "Successfully inserted user: " + vehicle}), 201
else:
return jsonify({"Result" : "Failed to insert data. Check logs for more details"}), 400
except Exception as e:
return jsonify({'Error' : str(e)}), 500
class ViewUser(Resource):
def get(self):
from bson import json_util
results = select_record()
final = []
for result in results:
result.pop("_id")
final.append(result)
return jsonify(results=final), 200
api.add_resource(CreatUser, "/api/create")
api.add_resource(ViewUser, "/api/view")
if __name__ == "__main__":
app.run(debug=True)