Module src.box

Expand source code
import pymongo
from flask_restful import Resource, reqparse
import globals
from src import auth
from webargs.flaskparser import use_kwargs, parser, abort
from webargs import fields, validate
from bson import json_util, ObjectId
import json


boxes_args = reqparse.RequestParser()
# Adding a new argument to the parser.
boxes_args.add_argument("Authorization", type=str,
                        help="Unauthorize", required=True, location="headers")
# Adding a new argument to the parser.
boxes_args.add_argument("DataIndexes", type=str,
                        help="Please Provide DataIndexes", required=True)
# Adding a new argument to the parser.
boxes_args.add_argument(
    "Page", type=int, help="Please Provide Page Number", required=True)

boxesDB = globals.boxesDB
auth_args = {"Authorization": fields.Str(required=True)}
boxData = {
    "fileId": fields.Str(required=True),
    "pageId": fields.Str(required=True),
    # "coordinates": fields.List(fields.Dict(keys=fields.Str(), values=fields.Str())),
    "coordinates": fields.List(fields.Float(required=True)),
    "linesData": fields.List(fields.Dict(required=True)),
    "innerText": fields.Str(required=True),
    "tagName": fields.Str(required=True),
    "linesId": fields.List(fields.Str(required=True)),
    "boxIndex": fields.Integer(required=True)
}


# It's a post request that takes in a bunch of data and returns a message and a status code
class NewBox(Resource):

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(boxData)
    def post(self, Authorization, fileId, pageId, coordinates, innerText, tagName, linesId, boxIndex, linesData):
        """
        It takes in a bunch of parameters, and if the Authorization header is valid, it inserts a
        document into the database

        :param Authorization: The token that is generated when the user logs in
        :param fileId: The id of the file that the box belongs to
        :param pageId: The page number of the document
        :param coordinates: [x, y, width, height]
        :param innerText: The text inside the box
        :param tagName: "p"
        :param linesId: [lineId1, lineId2, lineId3, ...]
        :param boxIndex: The index of the box in the page
        :param linesData: [{
        :return: The return value is a tuple of the form (body, status, headers)
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            id = str(boxesDB.insert_one({
                "fileId": fileId,
                "pageId": pageId,
                "coordinates": coordinates,
                "innerText": innerText,
                "tagName": tagName,
                "linesId": linesId,
                "linesData": linesData,
                "boxIndex": boxIndex
            }).inserted_id)
            return {"msg": id}, 200
        else:
            return {"msg": "Unauthorized! Access Denied"}, 401


# This class is used to delete a box from the database
class deleteBox(Resource):
    boxId = {"id": fields.Str(required=True)}

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(boxId, location="query")
    def delete(self, Authorization, id):
        """
        If the user is authorized, delete the document with the given id

        :param Authorization: The token that is generated when the user logs in
        :param id: The id of the box you want to delete
        :return: The return value is a tuple of the response object and the status code.
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            boxesDB.delete_one({"_id": ObjectId(id)})
            return {"msg": "Deleted Successfully"}, 200
        else:
            return {"msg": "Unauthorized! Access Denied"}, 401


# I'm trying to update a document in MongoDB using the PUT method
class updateBox(Resource):

    boxData["id"] = fields.Str(required=True)

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(boxData)
    def put(self, Authorization, id, fileId, pageId, coordinates, innerText, tagName, linesId, boxIndex, linesData):
        """
        It updates the document in the database with the given id, with the given data

        :param Authorization: The token generated by the login API
        :param id: ObjectId of the document
        :param fileId: The id of the file that the box belongs to
        :param pageId: The page number of the document
        :param coordinates: [{x: 0, y: 0}, {x: 0, y: 0}]
        :param innerText: The text inside the box
        :param tagName: "p"
        :param linesId: is the id of the line that the box belongs to
        :param boxIndex: The index of the box in the page
        :param linesData: [{
        :return: The return value is a tuple of the form (response, status, headers)
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            boxesDB.update_one({
                "_id": ObjectId(id)
            },
                {
                    "$set": {
                        "fileId": fileId,
                        "pageId": pageId,
                        "coordinates": coordinates,
                        "innerText": innerText,
                        "linesData": linesData,
                        "tagName": tagName,
                        "linesId": linesId,
                        "boxIndex": boxIndex
                    }
            }
            )
            return {"msg": "Updated Successfully"}, 200

        else:
            return {"msg": "Unauthorized! Access Denied"}, 401


# I'm trying to update the boxIndex field of the boxesDB collection based on the order of the boxId
# list
class reArrangeBoxes(Resource):
    reArrangeData = {
        "boxId": fields.List(fields.Str(required=True)),
        "pageId": fields.Str(required=True),
    }

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(reArrangeData)
    def put(self, Authorization, boxId, pageId):
        """
        I'm trying to update the boxIndex of each box in the page based on the order of the boxIds in
        the request body

        :param Authorization: The token that is generated when the user logs in
        :param boxId: ["5e8f8f8f8f8f8f8f8f8f8f8f", "5e8f8f8f8f8f8f8f8f8f8f8f"]
        :param pageId: The id of the page that the boxes are on
        :return: The return value is a tuple. The first element is a list of dictionaries. The second
        element is an integer.
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            pageBoxes = list(boxesDB.find({"pageId": pageId}))
            for boxIndex in range(0, len(pageBoxes)):
                try:
                    index = boxId.index(str(pageBoxes[boxIndex]["_id"]))
                    boxesDB.update_one(pageBoxes[boxIndex], {
                                       '$set': {"boxIndex": index}})
                except:
                    ""
            return json.loads(json_util.dumps(boxesDB.find({"pageId": pageId}, {"_id": 1}).sort("boxIndex", pymongo.ASCENDING))), 200
        else:
            return {"msg": "Unauthorized! Access Denied"}, 401


# This error handler is necessary for usage with Flask-RESTful
@parser.error_handler
def handle_request_parsing_error(err, req, schema, *, error_status_code, error_headers):
    """webargs error handler that uses Flask-RESTful's abort function to return
    a JSON error response to the client.
    """
    if not error_status_code:
        abort(400, errors=err.messages)
    else:
        abort(error_status_code, errors=err.messages)

Functions

def handle_request_parsing_error(err, req, schema, *, error_status_code, error_headers)

webargs error handler that uses Flask-RESTful's abort function to return a JSON error response to the client.

Expand source code
@parser.error_handler
def handle_request_parsing_error(err, req, schema, *, error_status_code, error_headers):
    """webargs error handler that uses Flask-RESTful's abort function to return
    a JSON error response to the client.
    """
    if not error_status_code:
        abort(400, errors=err.messages)
    else:
        abort(error_status_code, errors=err.messages)

Classes

class NewBox

Represents an abstract RESTful resource. Concrete resources should extend from this class and expose methods for each supported HTTP method. If a resource is invoked with an unsupported HTTP method, the API will return a response with status 405 Method Not Allowed. Otherwise the appropriate method is called and passed all arguments from the url rule used when adding the resource to an Api instance. See :meth:~flask_restful.Api.add_resource for details.

Expand source code
class NewBox(Resource):

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(boxData)
    def post(self, Authorization, fileId, pageId, coordinates, innerText, tagName, linesId, boxIndex, linesData):
        """
        It takes in a bunch of parameters, and if the Authorization header is valid, it inserts a
        document into the database

        :param Authorization: The token that is generated when the user logs in
        :param fileId: The id of the file that the box belongs to
        :param pageId: The page number of the document
        :param coordinates: [x, y, width, height]
        :param innerText: The text inside the box
        :param tagName: "p"
        :param linesId: [lineId1, lineId2, lineId3, ...]
        :param boxIndex: The index of the box in the page
        :param linesData: [{
        :return: The return value is a tuple of the form (body, status, headers)
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            id = str(boxesDB.insert_one({
                "fileId": fileId,
                "pageId": pageId,
                "coordinates": coordinates,
                "innerText": innerText,
                "tagName": tagName,
                "linesId": linesId,
                "linesData": linesData,
                "boxIndex": boxIndex
            }).inserted_id)
            return {"msg": id}, 200
        else:
            return {"msg": "Unauthorized! Access Denied"}, 401

Ancestors

  • flask_restful.Resource
  • flask.views.MethodView
  • flask.views.View

Class variables

var methods : Optional[List[str]]

Methods

def post(self, Authorization, fileId, pageId, coordinates, innerText, tagName, linesId, boxIndex, linesData)

It takes in a bunch of parameters, and if the Authorization header is valid, it inserts a document into the database

:param Authorization: The token that is generated when the user logs in :param fileId: The id of the file that the box belongs to :param pageId: The page number of the document :param coordinates: [x, y, width, height] :param innerText: The text inside the box :param tagName: "p" :param linesId: [lineId1, lineId2, lineId3, …] :param boxIndex: The index of the box in the page :param linesData: [{ :return: The return value is a tuple of the form (body, status, headers)

Expand source code
@use_kwargs(auth_args, location="headers")
@use_kwargs(boxData)
def post(self, Authorization, fileId, pageId, coordinates, innerText, tagName, linesId, boxIndex, linesData):
    """
    It takes in a bunch of parameters, and if the Authorization header is valid, it inserts a
    document into the database

    :param Authorization: The token that is generated when the user logs in
    :param fileId: The id of the file that the box belongs to
    :param pageId: The page number of the document
    :param coordinates: [x, y, width, height]
    :param innerText: The text inside the box
    :param tagName: "p"
    :param linesId: [lineId1, lineId2, lineId3, ...]
    :param boxIndex: The index of the box in the page
    :param linesData: [{
    :return: The return value is a tuple of the form (body, status, headers)
    """
    if auth.verify(str(Authorization).split(" ")[1]):
        id = str(boxesDB.insert_one({
            "fileId": fileId,
            "pageId": pageId,
            "coordinates": coordinates,
            "innerText": innerText,
            "tagName": tagName,
            "linesId": linesId,
            "linesData": linesData,
            "boxIndex": boxIndex
        }).inserted_id)
        return {"msg": id}, 200
    else:
        return {"msg": "Unauthorized! Access Denied"}, 401
class deleteBox

Represents an abstract RESTful resource. Concrete resources should extend from this class and expose methods for each supported HTTP method. If a resource is invoked with an unsupported HTTP method, the API will return a response with status 405 Method Not Allowed. Otherwise the appropriate method is called and passed all arguments from the url rule used when adding the resource to an Api instance. See :meth:~flask_restful.Api.add_resource for details.

Expand source code
class deleteBox(Resource):
    boxId = {"id": fields.Str(required=True)}

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(boxId, location="query")
    def delete(self, Authorization, id):
        """
        If the user is authorized, delete the document with the given id

        :param Authorization: The token that is generated when the user logs in
        :param id: The id of the box you want to delete
        :return: The return value is a tuple of the response object and the status code.
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            boxesDB.delete_one({"_id": ObjectId(id)})
            return {"msg": "Deleted Successfully"}, 200
        else:
            return {"msg": "Unauthorized! Access Denied"}, 401

Ancestors

  • flask_restful.Resource
  • flask.views.MethodView
  • flask.views.View

Class variables

var boxId
var methods : Optional[List[str]]

Methods

def delete(self, Authorization, id)

If the user is authorized, delete the document with the given id

:param Authorization: The token that is generated when the user logs in :param id: The id of the box you want to delete :return: The return value is a tuple of the response object and the status code.

Expand source code
@use_kwargs(auth_args, location="headers")
@use_kwargs(boxId, location="query")
def delete(self, Authorization, id):
    """
    If the user is authorized, delete the document with the given id

    :param Authorization: The token that is generated when the user logs in
    :param id: The id of the box you want to delete
    :return: The return value is a tuple of the response object and the status code.
    """
    if auth.verify(str(Authorization).split(" ")[1]):
        boxesDB.delete_one({"_id": ObjectId(id)})
        return {"msg": "Deleted Successfully"}, 200
    else:
        return {"msg": "Unauthorized! Access Denied"}, 401
class reArrangeBoxes

Represents an abstract RESTful resource. Concrete resources should extend from this class and expose methods for each supported HTTP method. If a resource is invoked with an unsupported HTTP method, the API will return a response with status 405 Method Not Allowed. Otherwise the appropriate method is called and passed all arguments from the url rule used when adding the resource to an Api instance. See :meth:~flask_restful.Api.add_resource for details.

Expand source code
class reArrangeBoxes(Resource):
    reArrangeData = {
        "boxId": fields.List(fields.Str(required=True)),
        "pageId": fields.Str(required=True),
    }

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(reArrangeData)
    def put(self, Authorization, boxId, pageId):
        """
        I'm trying to update the boxIndex of each box in the page based on the order of the boxIds in
        the request body

        :param Authorization: The token that is generated when the user logs in
        :param boxId: ["5e8f8f8f8f8f8f8f8f8f8f8f", "5e8f8f8f8f8f8f8f8f8f8f8f"]
        :param pageId: The id of the page that the boxes are on
        :return: The return value is a tuple. The first element is a list of dictionaries. The second
        element is an integer.
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            pageBoxes = list(boxesDB.find({"pageId": pageId}))
            for boxIndex in range(0, len(pageBoxes)):
                try:
                    index = boxId.index(str(pageBoxes[boxIndex]["_id"]))
                    boxesDB.update_one(pageBoxes[boxIndex], {
                                       '$set': {"boxIndex": index}})
                except:
                    ""
            return json.loads(json_util.dumps(boxesDB.find({"pageId": pageId}, {"_id": 1}).sort("boxIndex", pymongo.ASCENDING))), 200
        else:
            return {"msg": "Unauthorized! Access Denied"}, 401

Ancestors

  • flask_restful.Resource
  • flask.views.MethodView
  • flask.views.View

Class variables

var methods : Optional[List[str]]
var reArrangeData

Methods

def put(self, Authorization, boxId, pageId)

I'm trying to update the boxIndex of each box in the page based on the order of the boxIds in the request body

:param Authorization: The token that is generated when the user logs in :param boxId: ["5e8f8f8f8f8f8f8f8f8f8f8f", "5e8f8f8f8f8f8f8f8f8f8f8f"] :param pageId: The id of the page that the boxes are on :return: The return value is a tuple. The first element is a list of dictionaries. The second element is an integer.

Expand source code
@use_kwargs(auth_args, location="headers")
@use_kwargs(reArrangeData)
def put(self, Authorization, boxId, pageId):
    """
    I'm trying to update the boxIndex of each box in the page based on the order of the boxIds in
    the request body

    :param Authorization: The token that is generated when the user logs in
    :param boxId: ["5e8f8f8f8f8f8f8f8f8f8f8f", "5e8f8f8f8f8f8f8f8f8f8f8f"]
    :param pageId: The id of the page that the boxes are on
    :return: The return value is a tuple. The first element is a list of dictionaries. The second
    element is an integer.
    """
    if auth.verify(str(Authorization).split(" ")[1]):
        pageBoxes = list(boxesDB.find({"pageId": pageId}))
        for boxIndex in range(0, len(pageBoxes)):
            try:
                index = boxId.index(str(pageBoxes[boxIndex]["_id"]))
                boxesDB.update_one(pageBoxes[boxIndex], {
                                   '$set': {"boxIndex": index}})
            except:
                ""
        return json.loads(json_util.dumps(boxesDB.find({"pageId": pageId}, {"_id": 1}).sort("boxIndex", pymongo.ASCENDING))), 200
    else:
        return {"msg": "Unauthorized! Access Denied"}, 401
class updateBox

Represents an abstract RESTful resource. Concrete resources should extend from this class and expose methods for each supported HTTP method. If a resource is invoked with an unsupported HTTP method, the API will return a response with status 405 Method Not Allowed. Otherwise the appropriate method is called and passed all arguments from the url rule used when adding the resource to an Api instance. See :meth:~flask_restful.Api.add_resource for details.

Expand source code
class updateBox(Resource):

    boxData["id"] = fields.Str(required=True)

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(boxData)
    def put(self, Authorization, id, fileId, pageId, coordinates, innerText, tagName, linesId, boxIndex, linesData):
        """
        It updates the document in the database with the given id, with the given data

        :param Authorization: The token generated by the login API
        :param id: ObjectId of the document
        :param fileId: The id of the file that the box belongs to
        :param pageId: The page number of the document
        :param coordinates: [{x: 0, y: 0}, {x: 0, y: 0}]
        :param innerText: The text inside the box
        :param tagName: "p"
        :param linesId: is the id of the line that the box belongs to
        :param boxIndex: The index of the box in the page
        :param linesData: [{
        :return: The return value is a tuple of the form (response, status, headers)
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            boxesDB.update_one({
                "_id": ObjectId(id)
            },
                {
                    "$set": {
                        "fileId": fileId,
                        "pageId": pageId,
                        "coordinates": coordinates,
                        "innerText": innerText,
                        "linesData": linesData,
                        "tagName": tagName,
                        "linesId": linesId,
                        "boxIndex": boxIndex
                    }
            }
            )
            return {"msg": "Updated Successfully"}, 200

        else:
            return {"msg": "Unauthorized! Access Denied"}, 401

Ancestors

  • flask_restful.Resource
  • flask.views.MethodView
  • flask.views.View

Class variables

var methods : Optional[List[str]]

Methods

def put(self, Authorization, id, fileId, pageId, coordinates, innerText, tagName, linesId, boxIndex, linesData)

It updates the document in the database with the given id, with the given data

:param Authorization: The token generated by the login API :param id: ObjectId of the document :param fileId: The id of the file that the box belongs to :param pageId: The page number of the document :param coordinates: [{x: 0, y: 0}, {x: 0, y: 0}] :param innerText: The text inside the box :param tagName: "p" :param linesId: is the id of the line that the box belongs to :param boxIndex: The index of the box in the page :param linesData: [{ :return: The return value is a tuple of the form (response, status, headers)

Expand source code
@use_kwargs(auth_args, location="headers")
@use_kwargs(boxData)
def put(self, Authorization, id, fileId, pageId, coordinates, innerText, tagName, linesId, boxIndex, linesData):
    """
    It updates the document in the database with the given id, with the given data

    :param Authorization: The token generated by the login API
    :param id: ObjectId of the document
    :param fileId: The id of the file that the box belongs to
    :param pageId: The page number of the document
    :param coordinates: [{x: 0, y: 0}, {x: 0, y: 0}]
    :param innerText: The text inside the box
    :param tagName: "p"
    :param linesId: is the id of the line that the box belongs to
    :param boxIndex: The index of the box in the page
    :param linesData: [{
    :return: The return value is a tuple of the form (response, status, headers)
    """
    if auth.verify(str(Authorization).split(" ")[1]):
        boxesDB.update_one({
            "_id": ObjectId(id)
        },
            {
                "$set": {
                    "fileId": fileId,
                    "pageId": pageId,
                    "coordinates": coordinates,
                    "innerText": innerText,
                    "linesData": linesData,
                    "tagName": tagName,
                    "linesId": linesId,
                    "boxIndex": boxIndex
                }
        }
        )
        return {"msg": "Updated Successfully"}, 200

    else:
        return {"msg": "Unauthorized! Access Denied"}, 401