0
\$\begingroup\$

I`m trying to make an API for Flask together with MongoDB, before that I used the SQL DB using SQLAlchemy and there I used models for organizing the database.

Now I'm a bit confused how to organize code for working with DB. Since the standard MongoDB client does not provide an opportunity to create models, and I did not like Mongoengine, I decided to move any database methods into a separate class:

import uuid
from datetime import datetime

from flask import request
from werkzeug.security import generate_password_hash

from app import mongo


class User:

    db = mongo.db.users

    def new_user(self):
        '''New user Registration.

        Request body (JSON):
            email (str)
            username (str)
            password (str)
        Returns:
            status, result (tuple):
                100, user (dict) - in case of successful registration
                102, None - one of the parameters is missing
                201, None - such user already exists
        '''

        try:
            data = {
                '_id': uuid.uuid4().hex,
                'email': request.json['email'],
                'username': request.json['username'],
                'password': generate_password_hash(
                    request.json['password']),
                'createdAt': datetime.utcnow()
            }
        except KeyError:
            return 102, None

        user = self.db.find_one({
            '$or': [
                {'email': data['email']},
                {'username': data['username']}
            ]
        })

        if not user:
            self.db.insert_one(data)
            return 100, data
        else:
            return 201, None

    def login(self):
        pass

    def get_data(self):
        pass

from flask import Blueprint, jsonify, request

from app.models import User


users = Blueprint('users', __name__)


@users.route('/users/new_user', methods=['POST'])
def new_user():
    '''Adding a new user to the database.
    '''

    status, user = User().new_user()

    if status == 100:
        return jsonify({'status': True, 'code': 100, 'result': user})
    elif status == 102:
        return jsonify({
            'status': False, 'code': 102,
            'result': 'missing one of parameters'})
    elif status == 201:
        return jsonify({
            'status': False, 'code': 201, 'result': 'user already exists'})

But it looks very strange to me, if there are many keys in the document and I need to somehow handle them in the route, it will be very unintuitive.

Now I am thinking of making a model by analogy with models from SQLAlchemy, so that class variables represent keys in documents, as well as simple methods for queries in the database. But it can also cause a lot of confusion. I just want to try to avoid code duplication as well as variability for reuse.

I will accept any advice or hints as to how it should be "right". Unfortunately I have not found a project structure using MongoDB.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply state the task accomplished by the code. Please see How to get the best value out of Code Review: Asking Questions for guidance on writing good question titles. \$\endgroup\$ Mar 6 at 15:25

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.