2
\$\begingroup\$

The functions below are from a class of slave function which interact with my mongo database. The purpose is to serve a Flask based API by responding with the appropriate data required along with the status code. The following 5 functions are

  1. Init
  2. Add Data
  3. Return/Fetch Data
  4. Search Data
  5. Delete Data

The request is to optimize each function so that it abides the best prctices and becomes as error free as possible.

1. Init The init method initializes an object for the class which forms a connection to the Mongo Database. The database has 2 collections which are to be used by this class, the same are made into the list_client and dets_client object.

def __init__(self, app):
        URI = "mongodb://127.0.0.1:27017/source"
        mongo = PyMongo(app, URI)
        self.list_client = mongo.db['subjects.list']
        self.dets_client = mongo.db['subjects.dets']

2. Add Data The add_sub_list function is used to add a new subject to the database. This is done when a user sends a POST request to the appropriate route with the data in {col_code:code, title:name, sub_code:code} format. The link is a parameter to be made by the data the function recieves from the API and has to be consumed by in the project later. The initail try expect statements are there to prevent wrong data being added. ex- College does not exist or parameters sent are wrong. The if condition is to prevent duplication of data. The function adds new data to the first collection(sub_list) while making an instance of the same subject in the second collection(sub-data).

def add_sub_list(self, sub_data):
        # NOTE: Function data col_code, {"title": name, "sub_code": code}
        try:
            if not self.list_client.find_one({"sub.sub_code": sub_data['sub_code'], "col_code": sub_data['col_code']}):
                if not self.list_client.find_one({"sub.title": sub_data['title'], "col_code": sub_data['col_code']}):
                    self.dets_client.insert_one(sub_data)
                    col_code = sub_data.pop("col_code")
                    link = '/{}/{}'.format(self.list_client.find_one({"col_code": col_code})
                                           ["college"], sub_data["sub_code"])
                    sub_data['link'] = link
                    self.list_client.find_one_and_update(
                        {"col_code": col_code}, {'$push': {'sub': sub_data}}, upsert=True)
                    return {"status": 200, "data": "Success"}
                else:
                    return {"status": 403, "data": "Subject already Exists"}
            else:
                return {"status": 403, "data": "Subject already Exists"}
        except KeyError:
            return {"status": 404, "data": "Wrong Parameters"}
        except TypeError:
            return {"status": 404, "data": "No such College"}

3. Fetch Data The get_all function fetches the complete data in the list collection the {_id: 0} has to be added as the data is further converted into JSON format by the API method which called it.

 def get_all(self):
    print([colls for colls in
                     self.list_client.find({}, {'_id': 0})])
    return {"status": 200,
            "data": [colls for colls in
                     self.list_client.find({}, {'_id': 0, 'sub._id':0})]}

4. Search Data The search function is used to search for relevent subjects from the details collection as the user sends a term which can be a substring of the title of a subject. The results are further optimized by the user sending the college code along with the data, but that is optional, thus the if condition. This Function has the most potental to be optimized and improved.

def search(self, data):
    term = re.compile('{}'.format(data['term']), re.IGNORECASE)
    if data['col_code']:
        return {"status": 200, "data": [x for x in self.dets_client.find(
            {"title": term, "col_code": data["col_code"]}, {"_id": 0, "title": 1, "sub_code": 1, "col_code": 1})]}
    else:
        return {"status": 200, "data": [x for x in self.dets_client.find(
            {"title": term}, {"_id": 0, "title": 1, "sub_code": 1, "col_code": 1})]}

5. Delete Data The rem_sub function is used to remove a subject from the list as well as the details collection. Update is used in list removal as the subject is actually a subdocument in an array.

 def rem_sub(self, sub_data):
    try:
        if self.list_client.find_one({"sub.sub_code": sub_data['sub_code'], "col_code": sub_data['col_code']}):
            self.dets_client.remove({'sub_code': sub_data})
            col_code = sub_data.pop("col_code")
            self.list_client.update(
                {"col_code": col_code}, {'$pull': {'sub': sub_data}})
            return {"status": 200, "data": "Success"}
        else:
            return {"status": 403, "data": "Subject Does not Exists in the given college"}
    except KeyError:
        return {"status": 404, "data": "Wrong Parameters"}
    except TypeError:
        return {"status": 404, "data": "No such College"}

I feel that this code is not at all optimized and can be improved greatly and would really need best practices to be implimented. Any suggestions are welcome.

\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review. This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. Questions should include a description of what the code does \$\endgroup\$ – Zeta Oct 23 '18 at 5:58
  • \$\begingroup\$ @Zeta Alright, I'll add a few more methods and comments on how the overall class works \$\endgroup\$ – bhaskar Oct 24 '18 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.