Skip to main content
Notice removed Authoritative reference needed by ellaRT
Bounty Ended with potfur's answer chosen by ellaRT
Tweeted twitter.com/StackCodeReview/status/820441505072549888
improve formatting, add mongodb tag
Source Link
Gareth Rees
  • 50.1k
  • 3
  • 130
  • 211
  1. Is it efficient to be calling the instance of MongoClient for every request?

    Is it efficient to be calling the instance of MongoClient for every request?
  2. Do I need to close the instance of MongoClient after the request is successful?

    Do I need to close the instance of MongoClient after the request is successful?
  3. 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)
    
    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)
  1. Is it efficient to be calling the instance of MongoClient for every request?

  2. Do I need to close the instance of MongoClient after the request is successful?

  3. 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)
    
  1. Is it efficient to be calling the instance of MongoClient for every request?
  2. Do I need to close the instance of MongoClient after the request is successful?
  3. 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)
Notice added Authoritative reference needed by ellaRT
Bounty Started worth 50 reputation by ellaRT
Source Link
ellaRT
  • 243
  • 3
  • 13

RESTful APIs (Create, Read) with flask-restful

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:

  1. Is it efficient to be calling the instance of MongoClient for every request?

  2. Do I need to close the instance of MongoClient after the request is successful?

  3. 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)