Module licenseware.app_builder.uploads_namespace.filenames_validation_namespace

Given a list of filenames return validation analysis response

Notice we are using build_restx_model function to generate the swagger body required for the request.

Notice also the separation of creating the resource and the given namespace.

Expand source code
"""

Given a list of filenames return validation analysis response

Notice we are using `build_restx_model` function to generate the swagger body required for the request. 

Notice also the separation of creating the resource and the given namespace. 

"""


from flask import request
from flask_restx import Namespace, Resource
from marshmallow import Schema, fields

from licenseware.decorators.auth_decorators import authorization_check
from licenseware.decorators import failsafe
from licenseware.utils.logger import log
from licenseware.common import marshmallow_to_restx_model

from licenseware.uploader_builder import UploaderBuilder
from typing import List



class FilenamesValidationSchema(Schema):
    filenames = fields.List(fields.Str, required=True)

class FilenamesRespValidationSchema(Schema):
    status = fields.Str()
    filename = fields.Str()
    message = fields.Str()

class FilenamesRespSchema(Schema):
    status = fields.Str(metadata=dict(description="Statuses: `success` or `failed`"))
    message = fields.Str()
    validation = fields.List(fields.Nested(FilenamesRespValidationSchema))
    event_id = fields.Str(metadata=dict(description="The `event_id` which needs to be returned as a query param when uploading these files"))
    

def create_uploader_resource(uploader:UploaderBuilder):
             
    class FilenameValidate(Resource): 
        @failsafe(fail_code=500)
        @authorization_check
        def post(self):
            return uploader.validate_filenames(request)
        
    return FilenameValidate



def get_filenames_validation_namespace(ns: Namespace, uploaders:List[UploaderBuilder]):
    
    filenames_model = marshmallow_to_restx_model(ns, FilenamesValidationSchema)
    filenames_resp_model = marshmallow_to_restx_model(ns, FilenamesRespSchema)

    for uploader in uploaders:
        
        if uploader.validator_class is None: continue
        
        UR = create_uploader_resource(uploader)
           
        @ns.doc(
            description='Validating the list of filenames provided',
            responses={
                402 : 'Quota exceeded',
                403 : "Missing `Tenant` or `Authorization` information",
                500 : 'Something went wrong while handling the request' 
            }
        )
        @ns.expect(filenames_model)
        @ns.response(code=200, description="Filenames validation response", model=filenames_resp_model)
        class TempUploaderResource(UR): ...

        
        # Adding extra swagger query parameters if provided
        if uploader.query_params_on_validation:
            
            params_dict = {}
            for param_name, param_description in uploader.query_params_on_validation.items():
                params_dict[param_name] = { 'description': param_description }
            
            TempUploaderResource.__apidoc__.update({'params': params_dict})
        
        
        UploaderResource = type(
            uploader.uploader_id.replace("_", "").capitalize() + 'filenames',
            (TempUploaderResource, ),
            {}
        )
        
        ns.add_resource(UploaderResource, uploader.upload_validation_path) 
           

    return ns
    

Functions

def create_uploader_resource(uploader: UploaderBuilder)
Expand source code
def create_uploader_resource(uploader:UploaderBuilder):
             
    class FilenameValidate(Resource): 
        @failsafe(fail_code=500)
        @authorization_check
        def post(self):
            return uploader.validate_filenames(request)
        
    return FilenameValidate
def get_filenames_validation_namespace(ns: flask_restx.namespace.Namespace, uploaders: List[UploaderBuilder])
Expand source code
def get_filenames_validation_namespace(ns: Namespace, uploaders:List[UploaderBuilder]):
    
    filenames_model = marshmallow_to_restx_model(ns, FilenamesValidationSchema)
    filenames_resp_model = marshmallow_to_restx_model(ns, FilenamesRespSchema)

    for uploader in uploaders:
        
        if uploader.validator_class is None: continue
        
        UR = create_uploader_resource(uploader)
           
        @ns.doc(
            description='Validating the list of filenames provided',
            responses={
                402 : 'Quota exceeded',
                403 : "Missing `Tenant` or `Authorization` information",
                500 : 'Something went wrong while handling the request' 
            }
        )
        @ns.expect(filenames_model)
        @ns.response(code=200, description="Filenames validation response", model=filenames_resp_model)
        class TempUploaderResource(UR): ...

        
        # Adding extra swagger query parameters if provided
        if uploader.query_params_on_validation:
            
            params_dict = {}
            for param_name, param_description in uploader.query_params_on_validation.items():
                params_dict[param_name] = { 'description': param_description }
            
            TempUploaderResource.__apidoc__.update({'params': params_dict})
        
        
        UploaderResource = type(
            uploader.uploader_id.replace("_", "").capitalize() + 'filenames',
            (TempUploaderResource, ),
            {}
        )
        
        ns.add_resource(UploaderResource, uploader.upload_validation_path) 
           

    return ns

Classes

class FilenamesRespSchema (*, only: Union[Sequence[str], Set[str], None] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict[~KT, ~VT]] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)

Base schema class with which to define custom schemas.

Example usage:

.. code-block:: python

import datetime as dt
from dataclasses import dataclass

from marshmallow import Schema, fields


@dataclass
class Album:
    title: str
    release_date: dt.date


class AlbumSchema(Schema):
    title = fields.Str()
    release_date = fields.Date()


album = Album("Beggars Banquet", dt.date(1968, 12, 6))
schema = AlbumSchema()
data = schema.dump(album)
data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}

:param only: Whitelist of the declared fields to select when instantiating the Schema. If None, all fields are used. Nested fields can be represented with dot delimiters. :param exclude: Blacklist of the declared fields to exclude when instantiating the Schema. If a field appears in both only and exclude, it is not used. Nested fields can be represented with dot delimiters. :param many: Should be set to True if obj is a collection so that the object will be serialized to a list. :param context: Optional context passed to :class:fields.Method and :class:fields.Function fields. :param load_only: Fields to skip during serialization (write-only fields) :param dump_only: Fields to skip during deserialization (read-only fields) :param partial: Whether to ignore missing fields and not require any fields declared. Propagates down to Nested fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE.

Changed in version: 3.0.0

prefix parameter removed.

Changed in version: 2.0.0

__validators__, __preprocessors__, and __data_handlers__ are removed in favor of marshmallow.decorators.validates_schema, marshmallow.decorators.pre_load and marshmallow.decorators.post_dump. __accessor__ and __error_handler__ are deprecated. Implement the handle_error and get_attribute methods instead.

Expand source code
class FilenamesRespSchema(Schema):
    status = fields.Str(metadata=dict(description="Statuses: `success` or `failed`"))
    message = fields.Str()
    validation = fields.List(fields.Nested(FilenamesRespValidationSchema))
    event_id = fields.Str(metadata=dict(description="The `event_id` which needs to be returned as a query param when uploading these files"))

Ancestors

  • marshmallow.schema.Schema
  • marshmallow.base.SchemaABC

Class variables

var event_id
var message
var opts
var status
var validation
class FilenamesRespValidationSchema (*, only: Union[Sequence[str], Set[str], None] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict[~KT, ~VT]] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)

Base schema class with which to define custom schemas.

Example usage:

.. code-block:: python

import datetime as dt
from dataclasses import dataclass

from marshmallow import Schema, fields


@dataclass
class Album:
    title: str
    release_date: dt.date


class AlbumSchema(Schema):
    title = fields.Str()
    release_date = fields.Date()


album = Album("Beggars Banquet", dt.date(1968, 12, 6))
schema = AlbumSchema()
data = schema.dump(album)
data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}

:param only: Whitelist of the declared fields to select when instantiating the Schema. If None, all fields are used. Nested fields can be represented with dot delimiters. :param exclude: Blacklist of the declared fields to exclude when instantiating the Schema. If a field appears in both only and exclude, it is not used. Nested fields can be represented with dot delimiters. :param many: Should be set to True if obj is a collection so that the object will be serialized to a list. :param context: Optional context passed to :class:fields.Method and :class:fields.Function fields. :param load_only: Fields to skip during serialization (write-only fields) :param dump_only: Fields to skip during deserialization (read-only fields) :param partial: Whether to ignore missing fields and not require any fields declared. Propagates down to Nested fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE.

Changed in version: 3.0.0

prefix parameter removed.

Changed in version: 2.0.0

__validators__, __preprocessors__, and __data_handlers__ are removed in favor of marshmallow.decorators.validates_schema, marshmallow.decorators.pre_load and marshmallow.decorators.post_dump. __accessor__ and __error_handler__ are deprecated. Implement the handle_error and get_attribute methods instead.

Expand source code
class FilenamesRespValidationSchema(Schema):
    status = fields.Str()
    filename = fields.Str()
    message = fields.Str()

Ancestors

  • marshmallow.schema.Schema
  • marshmallow.base.SchemaABC

Class variables

var filename
var message
var opts
var status
class FilenamesValidationSchema (*, only: Union[Sequence[str], Set[str], None] = None, exclude: Union[Sequence[str], Set[str]] = (), many: bool = False, context: Optional[Dict[~KT, ~VT]] = None, load_only: Union[Sequence[str], Set[str]] = (), dump_only: Union[Sequence[str], Set[str]] = (), partial: Union[bool, Sequence[str], Set[str]] = False, unknown: Optional[str] = None)

Base schema class with which to define custom schemas.

Example usage:

.. code-block:: python

import datetime as dt
from dataclasses import dataclass

from marshmallow import Schema, fields


@dataclass
class Album:
    title: str
    release_date: dt.date


class AlbumSchema(Schema):
    title = fields.Str()
    release_date = fields.Date()


album = Album("Beggars Banquet", dt.date(1968, 12, 6))
schema = AlbumSchema()
data = schema.dump(album)
data  # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'}

:param only: Whitelist of the declared fields to select when instantiating the Schema. If None, all fields are used. Nested fields can be represented with dot delimiters. :param exclude: Blacklist of the declared fields to exclude when instantiating the Schema. If a field appears in both only and exclude, it is not used. Nested fields can be represented with dot delimiters. :param many: Should be set to True if obj is a collection so that the object will be serialized to a list. :param context: Optional context passed to :class:fields.Method and :class:fields.Function fields. :param load_only: Fields to skip during serialization (write-only fields) :param dump_only: Fields to skip during deserialization (read-only fields) :param partial: Whether to ignore missing fields and not require any fields declared. Propagates down to Nested fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE.

Changed in version: 3.0.0

prefix parameter removed.

Changed in version: 2.0.0

__validators__, __preprocessors__, and __data_handlers__ are removed in favor of marshmallow.decorators.validates_schema, marshmallow.decorators.pre_load and marshmallow.decorators.post_dump. __accessor__ and __error_handler__ are deprecated. Implement the handle_error and get_attribute methods instead.

Expand source code
class FilenamesValidationSchema(Schema):
    filenames = fields.List(fields.Str, required=True)

Ancestors

  • marshmallow.schema.Schema
  • marshmallow.base.SchemaABC

Class variables

var filenames
var opts