Module src.page

Expand source code
import os.path

from fitz import fitz
from flask_restful import Resource
import globals
from src import auth
from webargs.flaskparser import use_kwargs, parser, abort
from webargs import fields
from bson import json_util, ObjectId
import json

filesDB = globals.filesDB

auth_args = {"Authorization": fields.Str(required=True)}

# I'm trying to get the data from the fixed_layout_lines collection, but only the documents that have
# the current field set to 1


class GetPageData(Resource):
    fileData_args = {"id": fields.Str(
        required=True), "pageNum": fields.Str(required=True)}

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(fileData_args, location="query")
    def get(self, id, Authorization, pageNum):
        """
        I'm trying to get the data from the fixed_layout_lines collection and fixed_layout_boxes
        collection based on the pageId from the files collection

        :param id: The id of the document
        :param Authorization: Bearer
        eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTkz
        :param pageNum: The page number of the document
        :return: A list of dictionaries.
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            pipeline = [
                {
                    "$match": {
                        "_id": ObjectId(id),
                    }
                },
                {
                    '$unwind': '$Pages'
                },
                {
                    "$match": {
                        "Pages.PageNum": int(pageNum),
                    }
                },
                {
                    "$lookup":
                        {
                            'from': 'fixed_layout_lines',
                            'localField': "Pages.PageID",
                            'foreignField': 'pageId',
                            'pipeline': [
                                {
                                    "$match":
                                        {
                                            "$expr": {"$eq": ["$current", 1]}
                                        }
                                },
                                {
                                    "$sort": {"pageLineIndex": 1}
                                },
                            ],
                            'as': 'PageData'
                        }
                }, {
                    "$lookup":
                        {
                            'from': 'fixed_layout_boxes',
                            'localField': "Pages.PageID",
                            'foreignField': 'pageId',
                            'pipeline': [
                                {
                                    "$sort": {"boxIndex": 1}
                                },
                            ],
                            'as': 'Boxes'
                        }
                },
                {
                    "$project": {
                        "_id": 1,
                        "PageCount": "$TotalPages",
                        "PageID": "$Pages.PageID",
                        "PageNum": "$Pages.PageNum",
                        "Image": "$Pages.Image",
                        "Redacted_Image": "$Pages.Redacted_Image",
                        "h_multiplier": "$Pages.Height-Multipler",
                        "w_multiplier": "$Pages.Width-Multipler",
                        "PageData": 1,
                        "Boxes": 1
                    }
                }
            ]
            file = list(filesDB.aggregate(pipeline))
            return json.loads(json_util.dumps(file)), 200
        else:
            return "Unauthorized! Access Denied", 401


# It deletes all the lines and boxes from the database that are associated with the page id, and then
# it creates new lines with the same data as the old lines, but with a cursor of 1 and a current of 1
class PageReset(Resource):
    @use_kwargs(auth_args, location="headers")
    @use_kwargs({"id": fields.Str(required=True)}, location="query")
    def post(self, Authorization, id):
        """
        It deletes all the lines and boxes from the database that have a pageId of the id passed in, and
        then it creates new lines and boxes with the same pageId and cursor and current values of 1

        :param Authorization: The token that is generated when the user logs in
        :param id: The id of the page to be reset
        :return: The return value is a tuple of the form (body, status, headers)
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            globals.linesDB.delete_many(
                {
                    "$and": [
                        {
                            "pageId": id
                        },
                        {
                            "cursor":
                            {
                                "$ne": 0
                            }
                        }
                    ]
                }
            )

            newLines = []
            for record in globals.linesDB.find(
                {
                    "pageId": id
                }
            ):
                record["_id"] = ObjectId()
                record["cursor"] = 1
                record["current"] = 1
                newLines.append(record)

            globals.linesDB.insert_many(newLines)

            globals.boxesDB.delete_many(
                {
                    "pageId": id
                }
            )
            return {"msg": "Page Reset Successfully"}, 200

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


@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.
    """
    code, msg = getattr(err, 'status_code', 400), getattr(
        err, 'message', 'Invalid Request')
    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.
    """
    code, msg = getattr(err, 'status_code', 400), getattr(
        err, 'message', 'Invalid Request')
    if not error_status_code:
        abort(400, errors=err.messages)
    else:
        abort(error_status_code, errors=err.messages)

Classes

class GetPageData

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 GetPageData(Resource):
    fileData_args = {"id": fields.Str(
        required=True), "pageNum": fields.Str(required=True)}

    @use_kwargs(auth_args, location="headers")
    @use_kwargs(fileData_args, location="query")
    def get(self, id, Authorization, pageNum):
        """
        I'm trying to get the data from the fixed_layout_lines collection and fixed_layout_boxes
        collection based on the pageId from the files collection

        :param id: The id of the document
        :param Authorization: Bearer
        eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTkz
        :param pageNum: The page number of the document
        :return: A list of dictionaries.
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            pipeline = [
                {
                    "$match": {
                        "_id": ObjectId(id),
                    }
                },
                {
                    '$unwind': '$Pages'
                },
                {
                    "$match": {
                        "Pages.PageNum": int(pageNum),
                    }
                },
                {
                    "$lookup":
                        {
                            'from': 'fixed_layout_lines',
                            'localField': "Pages.PageID",
                            'foreignField': 'pageId',
                            'pipeline': [
                                {
                                    "$match":
                                        {
                                            "$expr": {"$eq": ["$current", 1]}
                                        }
                                },
                                {
                                    "$sort": {"pageLineIndex": 1}
                                },
                            ],
                            'as': 'PageData'
                        }
                }, {
                    "$lookup":
                        {
                            'from': 'fixed_layout_boxes',
                            'localField': "Pages.PageID",
                            'foreignField': 'pageId',
                            'pipeline': [
                                {
                                    "$sort": {"boxIndex": 1}
                                },
                            ],
                            'as': 'Boxes'
                        }
                },
                {
                    "$project": {
                        "_id": 1,
                        "PageCount": "$TotalPages",
                        "PageID": "$Pages.PageID",
                        "PageNum": "$Pages.PageNum",
                        "Image": "$Pages.Image",
                        "Redacted_Image": "$Pages.Redacted_Image",
                        "h_multiplier": "$Pages.Height-Multipler",
                        "w_multiplier": "$Pages.Width-Multipler",
                        "PageData": 1,
                        "Boxes": 1
                    }
                }
            ]
            file = list(filesDB.aggregate(pipeline))
            return json.loads(json_util.dumps(file)), 200
        else:
            return "Unauthorized! Access Denied", 401

Ancestors

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

Class variables

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

Methods

def get(self, id, Authorization, pageNum)

I'm trying to get the data from the fixed_layout_lines collection and fixed_layout_boxes collection based on the pageId from the files collection

:param id: The id of the document :param Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTkz :param pageNum: The page number of the document :return: A list of dictionaries.

Expand source code
@use_kwargs(auth_args, location="headers")
@use_kwargs(fileData_args, location="query")
def get(self, id, Authorization, pageNum):
    """
    I'm trying to get the data from the fixed_layout_lines collection and fixed_layout_boxes
    collection based on the pageId from the files collection

    :param id: The id of the document
    :param Authorization: Bearer
    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTkz
    :param pageNum: The page number of the document
    :return: A list of dictionaries.
    """
    if auth.verify(str(Authorization).split(" ")[1]):
        pipeline = [
            {
                "$match": {
                    "_id": ObjectId(id),
                }
            },
            {
                '$unwind': '$Pages'
            },
            {
                "$match": {
                    "Pages.PageNum": int(pageNum),
                }
            },
            {
                "$lookup":
                    {
                        'from': 'fixed_layout_lines',
                        'localField': "Pages.PageID",
                        'foreignField': 'pageId',
                        'pipeline': [
                            {
                                "$match":
                                    {
                                        "$expr": {"$eq": ["$current", 1]}
                                    }
                            },
                            {
                                "$sort": {"pageLineIndex": 1}
                            },
                        ],
                        'as': 'PageData'
                    }
            }, {
                "$lookup":
                    {
                        'from': 'fixed_layout_boxes',
                        'localField': "Pages.PageID",
                        'foreignField': 'pageId',
                        'pipeline': [
                            {
                                "$sort": {"boxIndex": 1}
                            },
                        ],
                        'as': 'Boxes'
                    }
            },
            {
                "$project": {
                    "_id": 1,
                    "PageCount": "$TotalPages",
                    "PageID": "$Pages.PageID",
                    "PageNum": "$Pages.PageNum",
                    "Image": "$Pages.Image",
                    "Redacted_Image": "$Pages.Redacted_Image",
                    "h_multiplier": "$Pages.Height-Multipler",
                    "w_multiplier": "$Pages.Width-Multipler",
                    "PageData": 1,
                    "Boxes": 1
                }
            }
        ]
        file = list(filesDB.aggregate(pipeline))
        return json.loads(json_util.dumps(file)), 200
    else:
        return "Unauthorized! Access Denied", 401
class PageReset

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 PageReset(Resource):
    @use_kwargs(auth_args, location="headers")
    @use_kwargs({"id": fields.Str(required=True)}, location="query")
    def post(self, Authorization, id):
        """
        It deletes all the lines and boxes from the database that have a pageId of the id passed in, and
        then it creates new lines and boxes with the same pageId and cursor and current values of 1

        :param Authorization: The token that is generated when the user logs in
        :param id: The id of the page to be reset
        :return: The return value is a tuple of the form (body, status, headers)
        """
        if auth.verify(str(Authorization).split(" ")[1]):
            globals.linesDB.delete_many(
                {
                    "$and": [
                        {
                            "pageId": id
                        },
                        {
                            "cursor":
                            {
                                "$ne": 0
                            }
                        }
                    ]
                }
            )

            newLines = []
            for record in globals.linesDB.find(
                {
                    "pageId": id
                }
            ):
                record["_id"] = ObjectId()
                record["cursor"] = 1
                record["current"] = 1
                newLines.append(record)

            globals.linesDB.insert_many(newLines)

            globals.boxesDB.delete_many(
                {
                    "pageId": id
                }
            )
            return {"msg": "Page Reset 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 post(self, Authorization, id)

It deletes all the lines and boxes from the database that have a pageId of the id passed in, and then it creates new lines and boxes with the same pageId and cursor and current values of 1

:param Authorization: The token that is generated when the user logs in :param id: The id of the page to be reset :return: The return value is a tuple of the form (body, status, headers)

Expand source code
@use_kwargs(auth_args, location="headers")
@use_kwargs({"id": fields.Str(required=True)}, location="query")
def post(self, Authorization, id):
    """
    It deletes all the lines and boxes from the database that have a pageId of the id passed in, and
    then it creates new lines and boxes with the same pageId and cursor and current values of 1

    :param Authorization: The token that is generated when the user logs in
    :param id: The id of the page to be reset
    :return: The return value is a tuple of the form (body, status, headers)
    """
    if auth.verify(str(Authorization).split(" ")[1]):
        globals.linesDB.delete_many(
            {
                "$and": [
                    {
                        "pageId": id
                    },
                    {
                        "cursor":
                        {
                            "$ne": 0
                        }
                    }
                ]
            }
        )

        newLines = []
        for record in globals.linesDB.find(
            {
                "pageId": id
            }
        ):
            record["_id"] = ObjectId()
            record["cursor"] = 1
            record["current"] = 1
            newLines.append(record)

        globals.linesDB.insert_many(newLines)

        globals.boxesDB.delete_many(
            {
                "pageId": id
            }
        )
        return {"msg": "Page Reset Successfully"}, 200

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