id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
900
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/verbs.py
tbone.resources.verbs.MethodNotImplemented
class MethodNotImplemented(HttpError): status = METHOD_NOT_IMPLEMENTED msg = 'The specified HTTP method is not implemented'
class MethodNotImplemented(HttpError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
3
0
3
3
2
0
3
3
2
0
4
0
0
901
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/verbs.py
tbone.resources.verbs.NotFound
class NotFound(HttpError): status = NOT_FOUND msg = 'Resource not found'
class NotFound(HttpError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
3
0
3
3
2
0
3
3
2
0
4
0
0
902
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/verbs.py
tbone.resources.verbs.Unauthorized
class Unauthorized(HttpError): status = UNAUTHORIZED msg = 'Unauthorized'
class Unauthorized(HttpError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
3
0
3
3
2
0
3
3
2
0
4
0
0
903
475Cumulus/TBone
475Cumulus_TBone/tbone/testing/__init__.py
tbone.testing.App
class App(object): def __init__(self, db=None, **kwargs): self.db = db
class App(object): def __init__(self, db=None, **kwargs): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
1
1
1
3
0
3
3
1
0
3
3
1
1
1
0
1
904
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/routers.py
tbone.resources.routers.Router
class Router(object): ''' Creates a url list for a group of resources. Handles endpoint url prefixes. Calls ``Resource.connect_signal_receiver`` for every ``Resource`` that is registered ''' def __init__(self, name): self.name = name self._registry = {} def register(self, resource, endpoint): ''' This methods registers a resource with the router and connects all receivers to their respective signals :param resource: The resource class to register :type resource: A subclass of ``Resource`` class :param endpoint: the name of the resource's endpoint as it appears in the URL :type endpoint: str ''' if not issubclass(resource, Resource): raise ValueError('Not and instance of ``Resource`` subclass') # register resource self._registry[endpoint] = resource # connect signal receivers resource.connect_signal_receivers() def unregister(self, endpoint): if endpoint in self._registry: del(self._registry[endpoint]) def endpoints(self): return list(self._registry) def urls_old(self, protocol=Resource.Protocol.http): ''' Iterate through all resources registered with this router and create a list endpoint and a detail endpoint for each one. Uses the router name as prefix and endpoint name of the resource when registered, to assemble the url pattern. Uses the constructor-passed url method or class for generating urls ''' url_patterns = [] for endpoint, resource_class in self._registry.items(): setattr(resource_class, 'api_name', self.name) setattr(resource_class, 'resource_name', endpoint) # append any nested resources the resource may have nested = [] for route in resource_class.nested_routes('/%s/%s/' % (self.name, endpoint)): route = route._replace(handler=resource_class.wrap_handler(route.handler, protocol)) nested.append(route) url_patterns.extend(nested) # append resource as list url_patterns.append(Route( path='/%s/%s/' % (self.name, endpoint), handler=resource_class.as_list(protocol), methods=resource_class.route_methods(), name='{}_{}_list'.format(self.name, endpoint).replace('/', '_') )) # append resource as detail url_patterns.append(Route( path='/%s/%s/%s/' % (self.name, endpoint, resource_class.route_param('pk')), handler=resource_class.as_detail(protocol), methods=resource_class.route_methods(), name='{}_{}_detail'.format(self.name, endpoint).replace('/', '_') )) return url_patterns def urls_regex(self, protocol=Resource.Protocol.http): ''' Iterate through all resources registered with this router and create a list endpoint and a detail endpoint for each one. Uses the router name as prefix and endpoint name of the resource when registered, to assemble the url pattern. Uses the constructor-passed url method or class for generating urls ''' url_patterns = [] for endpoint, resource_class in self._registry.items(): setattr(resource_class, 'api_name', self.name) setattr(resource_class, 'resource_name', endpoint) # append any nested handlers the resource may have nested = [] def formatter(param, type=str): return '(?P<%s>[\w\d_.-]+)' % param for route in resource_class.nested_routes('/(?P<api_name>{})/(?P<resource_name>{})/'.format(self.name, endpoint), formatter): route = route._replace(handler=resource_class.wrap_handler(route.handler, protocol)) nested.append(route) url_patterns.extend(nested) # append resource as list url_patterns.append(Route( path='/(?P<api_name>{})/(?P<resource_name>{})/$'.format(self.name, endpoint), handler=resource_class.as_list(protocol), methods=resource_class.route_methods(), name='{}_{}list'.format(self.name, endpoint).replace('/', '_') )) # append resource as detail url_patterns.append(Route( path='/(?P<api_name>{})/(?P<resource_name>{})/(?P<pk>[\w\d_.-]+)/$'.format(self.name, endpoint), handler=resource_class.as_detail(protocol), methods=resource_class.route_methods(), name='{}_{}_detail'.format(self.name, endpoint).replace('/', '_') )) return url_patterns def urls(self, regex=False, protocol=Resource.Protocol.http): def format_route_list(*args): if regex: return '/(?P<api_name>{})/(?P<resource_name>{})/{}'.format(*args) else: return '/{}/{}/'.format(*args) def format_route_detail(*args): if regex: return '/(?P<api_name>{0})/(?P<resource_name>{1})/(?P<pk>[\w\d_.-]+)/{3}'.format(*args) else: return '/{0}/{1}/{2}/'.format(*args) def format_pk(pk, type=str): if regex: return '(?P<{}>[\w\d_.-]+)'.format(pk) else: return resource_class.route_param(pk) url_patterns = [] for endpoint, resource_class in self._registry.items(): setattr(resource_class, 'api_name', self.name) setattr(resource_class, 'resource_name', endpoint) # append any nested resources the resource may have nested = [] for route in resource_class.nested_routes(format_route_list(self.name, endpoint, ''), format_pk): # replace nested handler with a wrapped function route = route._replace(handler=resource_class.wrap_handler(route.handler, protocol)) nested.append(route) url_patterns.extend(nested) # append resource as list url_patterns.append(Route( path=format_route_list(self.name, endpoint, '$'), handler=resource_class.as_list(protocol), methods=resource_class.route_methods(), name='{}_{}_list'.format(self.name, endpoint).replace('/', '_') )) # append resource as detail url_patterns.append(Route( path=format_route_detail(self.name, endpoint, resource_class.route_param('pk'), '$'), handler=resource_class.as_detail(protocol), methods=resource_class.route_methods(), name='{}_{}_detail'.format(self.name, endpoint).replace('/', '_') )) return url_patterns async def dispatch(self, app, payload): ''' Dispatches an incoming request and passes it to the relevant resource returning the response. :param app: Application handler. must be passed as part of the request :param payload: The request payload, contains all the parameters of the request ''' handler = None params = {} # parse request url, separating query params if any url = urlparse(payload['href']) path = url.path params.update(dict(parse_qsl(url.query))) params.update(payload.get('args', {})) # find the matching url , getting handler and arguments for route in self.urls(True, Resource.Protocol.websocket): match = re.match(route.path, path) if match: handler = route.handler params.update(match.groupdict()) break if handler: request = Request( app=app, key=payload.get('key', None), method=payload.get('method', 'GET'), url=path, args=params, headers=payload.get('headers', None), body=payload.get('body', {}) ) response = await handler(request) return response return None
class Router(object): ''' Creates a url list for a group of resources. Handles endpoint url prefixes. Calls ``Resource.connect_signal_receiver`` for every ``Resource`` that is registered ''' def __init__(self, name): pass def register(self, resource, endpoint): ''' This methods registers a resource with the router and connects all receivers to their respective signals :param resource: The resource class to register :type resource: A subclass of ``Resource`` class :param endpoint: the name of the resource's endpoint as it appears in the URL :type endpoint: str ''' pass def unregister(self, endpoint): pass def endpoints(self): pass def urls_old(self, protocol=Resource.Protocol.http): ''' Iterate through all resources registered with this router and create a list endpoint and a detail endpoint for each one. Uses the router name as prefix and endpoint name of the resource when registered, to assemble the url pattern. Uses the constructor-passed url method or class for generating urls ''' pass def urls_regex(self, protocol=Resource.Protocol.http): ''' Iterate through all resources registered with this router and create a list endpoint and a detail endpoint for each one. Uses the router name as prefix and endpoint name of the resource when registered, to assemble the url pattern. Uses the constructor-passed url method or class for generating urls ''' pass def formatter(param, type=str): pass def urls_old(self, protocol=Resource.Protocol.http): pass def format_route_list(*args): pass def format_route_detail(*args): pass def format_pk(pk, type=str): pass async def dispatch(self, app, payload): ''' Dispatches an incoming request and passes it to the relevant resource returning the response. :param app: Application handler. must be passed as part of the request :param payload: The request payload, contains all the parameters of the request ''' pass
13
5
17
1
12
4
2
0.4
1
7
3
0
8
2
8
8
197
21
126
35
113
50
85
35
72
4
1
2
26
905
475Cumulus/TBone
475Cumulus_TBone/tbone/dispatch/channels/mem.py
tbone.dispatch.channels.mem.MemoryChannel
class MemoryChannel(Channel): ''' Represents a channel for event pub/sub based on in-memory queue. uses ``asyncio.Queue`` to manage events. ''' def __init__(self, **kwargs): self._queue = asyncio.Queue() async def publish(self, key, data=None): document = { 'key': key, 'data': data } await self._queue.put(document) return data async def consume_events(self): while True: data = await self._queue.get()
class MemoryChannel(Channel): ''' Represents a channel for event pub/sub based on in-memory queue. uses ``asyncio.Queue`` to manage events. ''' def __init__(self, **kwargs): pass async def publish(self, key, data=None): pass async def consume_events(self): pass
4
1
4
0
4
0
1
0.31
1
0
0
0
3
1
3
11
20
3
13
7
9
4
10
7
6
2
2
1
4
906
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/phone_number.py
tbone.data.fields.phone_number.PhoneNumber
class PhoneNumber(phonenumbers.phonenumber.PhoneNumber): ''' extend phonenumbers.phonenumber.PhoneNumber with easier accessors ''' FORMATS = { 'E164': phonenumbers.PhoneNumberFormat.E164, 'INTERNATIONAL': phonenumbers.PhoneNumberFormat.INTERNATIONAL, 'NATIONAL': phonenumbers.PhoneNumberFormat.NATIONAL, 'RFC3966': phonenumbers.PhoneNumberFormat.RFC3966, } default_format = 'INTERNATIONAL' _region = '' def __repr__(self): fmt = self.FORMATS[self.default_format] return '<{} {}>'.format(self.__class__.__name__, self.format_as(fmt)) @classmethod def from_string(cls, phone_number, region=None): try: phone_number_obj = cls() phonenumbers.parse(number=phone_number, region=region, keep_raw_input=True, numobj=phone_number_obj) return phone_number_obj except phonenumbers.phonenumberutil.NumberParseException: return None def is_valid(self): return phonenumbers.is_valid_number(self) @property def as_international(self): return self.format_as(phonenumbers.PhoneNumberFormat.INTERNATIONAL) @property def as_e164(self): return self.format_as(phonenumbers.PhoneNumberFormat.E164) @property def as_national(self): return self.format_as(phonenumbers.PhoneNumberFormat.NATIONAL) @property def as_rfc3966(self): return self.format_as(phonenumbers.PhoneNumberFormat.RFC3966) @property def digits(self): return self.format_as(phonenumbers.PhoneNumberFormat.E164)[1:] def format_as(self, format): return phonenumbers.format_number(self, format) def __len__(self): return len(self.__unicode__()) def __eq__(self, other): ''' Override parent equality because we store only string representation of phone number, so we must compare only this string representation ''' if (isinstance(other, PhoneNumber) or isinstance(other, phonenumbers.phonenumber.PhoneNumber) or isinstance(other, str)): fmt = self.FORMATS['E164'] if isinstance(other, str): # convert string to phonenumbers.phonenumber.PhoneNumber instance try: other = phonenumbers.phonenumberutil.parse(other) except phonenumbers.phonenumberutil.NumberParseException: # Conversion is not possible, thus not equal return False other_string = phonenumbers.format_number(other, fmt) return self.format_as(fmt) == other_string else: return False
class PhoneNumber(phonenumbers.phonenumber.PhoneNumber): ''' extend phonenumbers.phonenumber.PhoneNumber with easier accessors ''' def __repr__(self): pass @classmethod def from_string(cls, phone_number, region=None): pass def is_valid(self): pass @property def as_international(self): pass @property def as_e164(self): pass @property def as_national(self): pass @property def as_rfc3966(self): pass @property def digits(self): pass def format_as(self, format): pass def __len__(self): pass def __eq__(self, other): ''' Override parent equality because we store only string representation of phone number, so we must compare only this string representation ''' pass
18
2
4
0
4
1
1
0.16
1
1
0
0
10
0
11
11
77
12
56
25
38
9
41
19
29
4
1
3
15
907
475Cumulus/TBone
475Cumulus_TBone/tbone/dispatch/carriers/aiohttp_websocket.py
tbone.dispatch.carriers.aiohttp_websocket.AioHttpWebSocketCarrier
class AioHttpWebSocketCarrier(object): def __init__(self, websocket): self._socket = websocket async def deliver(self, data): try: self._socket.send_str( json.dumps(data, cls=ExtendedJSONEncoder) ) return True except Exception as ex: logger.exception(ex) return False
class AioHttpWebSocketCarrier(object): def __init__(self, websocket): pass async def deliver(self, data): pass
3
0
6
0
6
0
2
0
1
2
1
0
2
1
2
2
14
2
12
5
9
0
10
4
7
2
1
1
3
908
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/examples/chatrooms/backend/models.py
models.Room.Meta
class Meta: name = 'rooms'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
909
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/examples/chatrooms/backend/models.py
models.Entry.Meta
class Meta: name = 'entries' creation_args = { 'capped': True, 'max': CAPACITY, 'size': CAPACITY * ENTRY_SIZE }
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7
0
7
3
6
0
3
3
2
0
0
0
0
910
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/examples/movies/backend/resources.py
backend.resources.MovieResource.Meta
class Meta: object_class = Movie
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
911
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/examples/blog/backend/resources.py
backend.resources.EntryResource.Meta
class Meta: object_class = Entry
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
912
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/examples/movies/backend/models.py
backend.models.Movie.Meta
class Meta: indices = [ { 'name': '_fts', 'fields': [ ('title', TEXT), ('plot', TEXT), ('cast', TEXT), ('genres', TEXT) ] } ]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
12
0
12
2
11
0
2
2
1
0
0
0
0
913
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.BooleanField
class BooleanField(BaseField): '''A boolean field type. In addition to ``True`` and ``False``, coerces these values: + For ``True``: "True", "true", "1" + For ``False``: "False", "false", "0" ''' _data_type = bool _python_type = bool
class BooleanField(BaseField): '''A boolean field type. In addition to ``True`` and ``False``, coerces these values: + For ``True``: "True", "true", "1" + For ``False``: "False", "false", "0" ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
31
10
2
3
3
2
5
3
3
2
0
4
0
0
914
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/phone_number.py
tbone.data.fields.phone_number.PhoneNumberField
class PhoneNumberField(StringField): ERRORS = { 'invalid': "Invalid phone number", } def to_data(self, value): if value is None: return None if isinstance(value, PhoneNumber): return value.as_e164 phone_number = PhoneNumber.from_string(value) if phone_number: return phone_number.as_e164 raise ValueError(self._errors['invalid']) def add_to_class(self, cls, name): ''' Overrides the base class to add a PhoheNumberDescriptor rather than the standard FieldDescriptor ''' self.model_class = cls setattr(cls, name, PhoneNumberDescriptor(self)) self._bound = True
class PhoneNumberField(StringField): def to_data(self, value): pass def add_to_class(self, cls, name): ''' Overrides the base class to add a PhoheNumberDescriptor rather than the standard FieldDescriptor ''' pass
3
1
8
0
7
2
3
0.18
1
3
2
0
2
2
2
33
22
2
17
7
14
3
15
7
12
4
5
1
5
915
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/phone_number.py
tbone.data.fields.phone_number.PhoneNumberDescriptor
class PhoneNumberDescriptor(object): ''' Descriptor for the phone number field. returns a PhoneNumber object. use like this: customer.phone_number.as_international customer.phone_number.as_national customer.phone_number.as_e164 ''' def __init__(self, field): self.field = field def __get__(self, instance=None, owner=None): if instance is None: raise AttributeError( "The '%s' attribute can only be accessed from %s instances." % (self.field.name, owner.__name__)) value = instance.__dict__[self.field] if value is None or isinstance(value, PhoneNumber): return value return PhoneNumber.from_string(value) def __set__(self, instance, value): instance.__dict__[self.field] = value
class PhoneNumberDescriptor(object): ''' Descriptor for the phone number field. returns a PhoneNumber object. use like this: customer.phone_number.as_international customer.phone_number.as_national customer.phone_number.as_e164 ''' def __init__(self, field): pass def __get__(self, instance=None, owner=None): pass def __set__(self, instance, value): pass
4
1
4
0
4
0
2
0.5
1
2
1
0
3
1
3
3
23
2
14
6
10
7
12
6
8
3
1
1
5
916
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.DateField
class DateField(DTBaseField): ''' Date field, exposes datetime.date as the python field ''' _python_type = datetime.date def _import(self, value): if isinstance(value, self._python_type): return value dt = super(DateField, self)._import(value) return None if dt is None else dt.date()
class DateField(DTBaseField): ''' Date field, exposes datetime.date as the python field ''' def _import(self, value): pass
2
1
5
0
5
0
3
0.14
1
1
0
0
1
0
1
34
9
1
7
4
5
1
7
4
5
3
5
1
3
917
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.DateTimeField
class DateTimeField(DTBaseField): ''' Date field, exposes datetime.datetime as the python field ''' _python_type = datetime.datetime
class DateTimeField(DTBaseField): ''' Date field, exposes datetime.datetime as the python field ''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
33
3
0
2
2
1
1
2
2
1
0
5
0
0
918
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.FloatField
class FloatField(NumberField): ''' A field that validates input as an Integer ''' _data_type = float _python_type = float
class FloatField(NumberField): ''' A field that validates input as an Integer ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
33
6
0
3
3
2
3
3
3
2
0
5
0
0
919
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.IntegerField
class IntegerField(NumberField): ''' A field that validates input as an Integer ''' _data_type = int _python_type = int
class IntegerField(NumberField): ''' A field that validates input as an Integer ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
33
6
0
3
3
2
3
3
3
2
0
5
0
0
920
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.NumberField
class NumberField(BaseField): ERRORS = { 'min': "Value should be greater than or equal to {0}.", 'max': "Value should be less than or equal to {0}.", } def __init__(self, min=None, max=None, **kwargs): self.min = min self.max = max super(NumberField, self).__init__(**kwargs) @validator def range(self, value): if self.min is not None and value < self.min: raise ValueError(self._errors['min'].format(self.min)) if self.max is not None and value > self.max: raise ValueError(self._errors['max'].format(self.max)) return value
class NumberField(BaseField): def __init__(self, min=None, max=None, **kwargs): pass @validator def range(self, value): pass
4
0
6
1
5
0
2
0
1
2
0
2
2
2
2
33
21
5
16
7
12
0
12
6
9
3
4
1
4
921
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.StringField
class StringField(BaseField): ''' Unicode string field ''' _data_type = str _python_type = str
class StringField(BaseField): ''' Unicode string field ''' pass
1
1
0
0
0
0
0
0.33
1
0
0
3
0
0
0
31
4
0
3
3
2
1
3
3
2
0
4
0
0
922
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.TimeField
class TimeField(DTBaseField): ''' Date field, exposes datetime.date as the python field ''' _python_type = datetime.time def _import(self, value): if isinstance(value, self._python_type): return value dt = super(TimeField, self)._import(value) return None if dt is None else dt.time()
class TimeField(DTBaseField): ''' Date field, exposes datetime.date as the python field ''' def _import(self, value): pass
2
1
5
0
5
0
3
0.14
1
1
0
0
1
0
1
34
9
1
7
4
5
1
7
4
5
3
5
1
3
923
475Cumulus/TBone
475Cumulus_TBone/tbone/data/models.py
tbone.data.models.Model
class Model(ModelSerializer, metaclass=ModelMeta): ''' Base class for all data models. This is the heart of the ODM. Provides field declaration and export methods implementations. Example: .. code-block:: python class Person(Model): first_name = StringField() last_name = StringField() ''' def __init__(self, data={}, **kwargs): self._data = {} if bool(data): self.import_data(data) self.validate() def __repr__(self): desc = self.description() if desc is None: return '<%s instance>' % self.__class__.__name__ return '<%s instance: %s>' % (self.__class__.__name__, desc) def __iter__(self): ''' Implements iterator on model matching only fields with data matching them ''' return (key for key in self._fields if key in self._data) def __eq__(self, other): ''' Override equal operator to compare field values ''' if self is other: return True if type(self) is not type(other): return NotImplemented for k in self: if getattr(self, k) != getattr(other, k): return False return True def description(self): ''' Adds an instance description to the class's ``repr``. Override in sub classes to provide desired functionality ''' return None @classmethod def fields(cls): # return list(iter(cls._fields)) return iter(cls._fields) def items(self): return [(field, self._data[field]) for field in self] @classmethod def _validate(cls, data): try: for name, field in cls._fields.items(): field.validate(data.get(name)) except Exception as ex: raise Exception('Failed to validate field "{}" model "{}"'.format(name, cls.__name__), ex) def validate(self): ''' Performs model data validation by iterating through all model fields and validating the field's data according to the field's internal validation rules or validation methods provided during model declaration ''' self._validate(self._data) def _convert(self, data, native): converted_data = {} for name, field in self._fields.items(): value = data.get(name) if value is None and field._export_if_none is False: continue if native is True: conversion_func = field.to_python else: conversion_func = field.to_data converted_data[name] = conversion_func(value) return converted_data def import_data(self, data: dict): ''' Imports data into model and converts to python form. Model fields and container of model fields retain their model class structure. Merges with existing if data is partial ''' if not isinstance(data, dict): raise ValueError('Cannot import data not as dict') self._data.update(data) for name, field in self._fields.items(): self._data[name] = field._import(self._data.get(name)) or field.default def export_data(self, native=True): ''' Export the model into a dictionary. This method does not include projection rules and export methods ''' return self._convert(self._data, native)
class Model(ModelSerializer, metaclass=ModelMeta): ''' Base class for all data models. This is the heart of the ODM. Provides field declaration and export methods implementations. Example: .. code-block:: python class Person(Model): first_name = StringField() last_name = StringField() ''' def __init__(self, data={}, **kwargs): pass def __repr__(self): pass def __iter__(self): ''' Implements iterator on model matching only fields with data matching them ''' pass def __eq__(self, other): ''' Override equal operator to compare field values ''' pass def description(self): ''' Adds an instance description to the class's ``repr``. Override in sub classes to provide desired functionality ''' pass @classmethod def fields(cls): pass def items(self): pass @classmethod def _validate(cls, data): pass def validate(self): ''' Performs model data validation by iterating through all model fields and validating the field's data according to the field's internal validation rules or validation methods provided during model declaration ''' pass def _convert(self, data, native): pass def import_data(self, data: dict): ''' Imports data into model and converts to python form. Model fields and container of model fields retain their model class structure. Merges with existing if data is partial ''' pass def export_data(self, native=True): ''' Export the model into a dictionary. This method does not include projection rules and export methods ''' pass
15
7
7
0
5
2
2
0.52
2
4
0
33
10
1
12
30
106
18
58
25
43
30
55
22
42
5
3
2
25
924
475Cumulus/TBone
475Cumulus_TBone/tbone/data/models.py
tbone.data.models.ModelOptions
class ModelOptions(object): ''' A configuration class for data Models. Provides all the defaults and allows overriding inside the model's definition using the ``Meta`` class :param name: The name of the data model. Persistency mixins use this to determine the name of the data collection in the datastore. Defaults to the class's name with ``None``. :param namespace: Defines a namespace for the model name. Used by persistency mixins to prepend to the collection's name :param exclude_fields: Exclude fields inherited by one of the base classes of the model. Useful for creating similar models with small differences in fields :param exclude_serialize_methods: Exclude serialize methods inherited by one of the base classes of the model. Useful for creating similar models with small differences in serialize methods :param concrete: Defines the model as concrete and not abstract. This is useful for persistency mixins to determine if the model should be created in the database. :type concrete: Boolean - Default is ``True`` :param creation_args: Used when creating a MongoDB collection for passing creation arguments :param indices: Used for definding database indices ''' name = None namespace = None concrete = True exclude_fields = [] exclude_serialize = [] creation_args = {} indices = [] def __init__(self, meta=None): if meta: for attr in dir(meta): if not attr.startswith('_'): setattr(self, attr, getattr(meta, attr))
class ModelOptions(object): ''' A configuration class for data Models. Provides all the defaults and allows overriding inside the model's definition using the ``Meta`` class :param name: The name of the data model. Persistency mixins use this to determine the name of the data collection in the datastore. Defaults to the class's name with ``None``. :param namespace: Defines a namespace for the model name. Used by persistency mixins to prepend to the collection's name :param exclude_fields: Exclude fields inherited by one of the base classes of the model. Useful for creating similar models with small differences in fields :param exclude_serialize_methods: Exclude serialize methods inherited by one of the base classes of the model. Useful for creating similar models with small differences in serialize methods :param concrete: Defines the model as concrete and not abstract. This is useful for persistency mixins to determine if the model should be created in the database. :type concrete: Boolean - Default is ``True`` :param creation_args: Used when creating a MongoDB collection for passing creation arguments :param indices: Used for definding database indices ''' def __init__(self, meta=None): pass
2
1
5
0
5
0
4
1.92
1
0
0
0
1
0
1
1
45
7
13
10
11
25
13
10
11
4
1
3
4
925
475Cumulus/TBone
475Cumulus_TBone/tbone/data/models.py
tbone.data.models.ModelSerializer
class ModelSerializer(object): ''' Mixin class for adding nonblocking serialization methods. Provides serialization methods to data primitives and to python types. Performs serialization taking into account projection attributes and serialize methods ''' async def serialize(self, native=False): ''' Returns a serialized from of the model taking into account projection rules and ``@serialize`` decorated methods. :param native: Deternines if data is serialized to Python native types or primitive form. Defaults to ``False`` ''' data = {} # iterate through all fields for field_name, field in self._fields.items(): # serialize field data raw_data = self._data.get(field_name) # add field's data to model data based on projection settings if field._projection != None: # noqa E711 field_data = await field.serialize(raw_data, native) if field_data: data[field_name] = field_data elif field._projection == True: # noqa E711 data[field_name] = None # iterate through all export methods for name, func in self._serialize_methods.items(): data[name] = await func(self) return data async def deserialize(self, data: dict, silent=True): ''' Deserializes a Python ``dict`` into the model by assigning values to their respective fields. Ignores data attributes that do not match one of the Model's fields. Ignores data attributes who's matching fields are declared with the ``readonly`` attribute Validates the data after import. Override in sub classes to modify or add to deserialization behavior :param data: Python dictionary with data :type data: ``dict`` :param silent: Determines if an exception is thrown if illegal fields are passed. Such fields can be non existent or readonly. Default is True :type silent: ``bool`` ''' self.import_data(self. _deserialize(data)) self.validate() def _deserialize(self, data: dict, silent=True) -> dict: ''' Internal deserialize method for sifting out unacceptable data for the model ''' deserialized_data = {} for name, field in self._fields.items(): if field._readonly is False and name in data: deserialized_data[name] = data.get(name) return deserialized_data
class ModelSerializer(object): ''' Mixin class for adding nonblocking serialization methods. Provides serialization methods to data primitives and to python types. Performs serialization taking into account projection attributes and serialize methods ''' async def serialize(self, native=False): ''' Returns a serialized from of the model taking into account projection rules and ``@serialize`` decorated methods. :param native: Deternines if data is serialized to Python native types or primitive form. Defaults to ``False`` ''' pass async def deserialize(self, data: dict, silent=True): ''' Deserializes a Python ``dict`` into the model by assigning values to their respective fields. Ignores data attributes that do not match one of the Model's fields. Ignores data attributes who's matching fields are declared with the ``readonly`` attribute Validates the data after import. Override in sub classes to modify or add to deserialization behavior :param data: Python dictionary with data :type data: ``dict`` :param silent: Determines if an exception is thrown if illegal fields are passed. Such fields can be non existent or readonly. Default is True :type silent: ``bool`` ''' pass def _deserialize(self, data: dict, silent=True) -> dict: ''' Internal deserialize method for sifting out unacceptable data for the model ''' pass
4
4
17
1
7
9
3
1.39
1
1
0
1
3
0
3
3
58
5
23
11
19
32
22
11
18
6
1
3
10
926
475Cumulus/TBone
475Cumulus_TBone/tbone/db/models.py
tbone.db.models.MongoCollectionMixin
class MongoCollectionMixin(object): ''' Mixin for data models, provides a persistency layer over a MongoDB collection ''' @property def db(self): return getattr(self, '_db', None) @property def pk(self): return getattr(self, self.primary_key) @classmethod def process_query(cls, query): ''' modify queries before sending to db ''' return dict(query) @classmethod def get_collection_name(cls): ''' Gets the full name of the collection, as declared by the ModelOptions class like so: namespace.name If no namespace or name is provided, the class's lowercase name is used ''' if hasattr(cls, '_meta'): np = getattr(cls._meta, 'namespace', None) cname = getattr(cls._meta, 'name', None) if np: return '{}.{}'.format(np, cname or cls.__name__.lower()) return cname or cls.__name__.lower() @staticmethod def connection_retries(): ''' returns the number of connection retries. Subclass to obtain this variable from the app's global settings ''' return range(5) @classmethod async def check_reconnect_tries_and_wait(cls, reconnect_number, method_name): if reconnect_number >= options.db_connection_retries: return True else: timeout = options.db_reconnect_timeout logger.warning('ConnectionFailure #{0} in {1}.{2}. Waiting {3} seconds'.format( reconnect_number + 1, cls.__name__, method_name, timeout )) await asyncio.sleep(timeout) @classmethod async def count(cls, db, filters={}): for i in cls.connection_retries(): try: result = await db[cls.get_collection_name()].count_documents(filters) return result except ConnectionFailure as ex: exceed = await cls.check_reconnect_tries_and_wait(i, 'count') if exceed: raise ex @classmethod async def find_one(cls, db, query): result = None if db is None: raise Exception('Missing DB connection') query = cls.process_query(query) for i in cls.connection_retries(): try: result = await db[cls.get_collection_name()].find_one(query) if result: result = cls.create_model(result) return result except ConnectionFailure as ex: exceed = await cls.check_reconnect_tries_and_wait(i, 'find_one') if exceed: raise ex @classmethod def get_cursor(cls, db, query={}, projection=None, sort=[]): query = cls.process_query(query) return db[cls.get_collection_name()].find(filter=query, projection=projection, sort=sort) @classmethod async def create_index(cls, db, indices, **kwargs): for i in cls.connection_retries(): try: result = await db[cls.get_collection_name()].create_index(indices, **kwargs) except ConnectionFailure as e: exceed = await cls.check_reconnect_tries_and_wait(i, 'create_index') if exceed: raise e else: return result @classmethod async def find(cls, cursor): result = None for i in cls.connection_retries(): try: result = await cursor.to_list(length=None) for i in range(len(result)): result[i] = cls.create_model(result[i]) return result except ConnectionFailure as e: exceed = await cls.check_reconnect_tries_and_wait(i, 'find') if exceed: raise e @classmethod async def distinct(cls, db, key): for i in cls.connection_retries(): try: result = await db[cls.get_collection_name()].distinct(key) return result except ConnectionFailure as ex: exceed = await cls.check_reconnect_tries_and_wait(i, 'distinct') if exceed: raise ex @classmethod async def delete_entries(cls, db, query): ''' Delete documents by given query. ''' query = cls.process_query(query) for i in cls.connection_retries(): try: result = await db[cls.get_collection_name()].delete_many(query) return result except ConnectionFailure as ex: exceed = await cls.check_reconnect_tries_and_wait(i, 'delete_entries') if exceed: raise ex async def delete(self, db): ''' Delete document ''' for i in self.connection_retries(): try: return await db[self.get_collection_name()].delete_one({self.primary_key: self.pk}) except ConnectionFailure as ex: exceed = await self.check_reconnect_tries_and_wait(i, 'delete') if exceed: raise ex @classmethod def create_model(cls, data: dict, fields=None): ''' Creates model instance from data (dict). ''' if fields is None: fields = set(cls._fields.keys()) else: if not isinstance(fields, set): fields = set(fields) new_keys = set(data.keys()) - fields if new_keys: for new_key in new_keys: del data[new_key] return cls(data) def prepare_data(self, data=None): ''' Prepare data for persistency by exporting it to native form and making sure we're not persisting with a null primary key. ''' data = data or self.export_data(native=True) # make sure we don't persist a null _id and let MongoDB auto-generate it if '_id' in data and data['_id'] is None: del data['_id'] return data async def save(self, db=None): ''' If object has _id, then object will be created or fully rewritten. If not, object will be inserted and _id will be assigned. ''' self._db = db or self.db data = self.prepare_data() # validate object self.validate() # connect to DB to save the model for i in self.connection_retries(): try: created = False if '_id' in data else True result = await self.db[self.get_collection_name()].insert_one(data) self._id = result.inserted_id # emit post save asyncio.ensure_future(post_save.send( sender=self.__class__, db=self.db, instance=self, created=created) ) break except ConnectionFailure as ex: exceed = await self.check_reconnect_tries_and_wait(i, 'save') if exceed: raise ex async def insert(self, db=None): ''' If object has _id then a DuplicateError will be thrown. If not, object will be inserted and _id will be assigned. ''' self._db = db or self.db data = self.prepare_data() # validate object self.validate() for i in self.connection_retries(): try: created = False if '_id' in data else True result = await db[self.get_collection_name()].insert_one(data) self._id = result.inserted_id # emit post save asyncio.ensure_future(post_save.send( sender=self.__class__, db=self.db, instance=self, created=created) ) break except ConnectionFailure as ex: exceed = await self.check_reconnect_tries_and_wait(i, 'insert') if exceed: raise ex async def update(self, db=None, data=None): ''' Update the entire document by replacing its content with new data, retaining its primary key ''' db = db or self.db if data: # update model explicitely with a new data structure # merge the current model's data with the new data self.import_data(data) # prepare data for database update data = self.prepare_data() # data = {x: ndata[x] for x in ndata if x in data or x == self.primary_key} else: data = self.export_data(native=True) if self.primary_key not in data or data[self.primary_key] is None: raise Exception('Missing object primary key') query = {self.primary_key: self.pk} for i in self.connection_retries(): try: result = await db[self.get_collection_name()].find_one_and_replace( filter=query, replacement=data, return_document=ReturnDocument.AFTER ) if result: updated_obj = self.create_model(result) updated_obj._db = db # emit post save asyncio.ensure_future(post_save.send( sender=self.__class__, db=db, instance=updated_obj, created=False) ) return updated_obj return None except ConnectionFailure as ex: exceed = await self.check_reconnect_tries_and_wait(i, 'update') if exceed: raise ex @classmethod async def modify(cls, db, key, data: dict): ''' Partially modify a document by providing a subset of its data fields to be modified :param db: Handle to the MongoDB database :param key: The primary key of the database object being modified. Usually its ``_id`` :param data: The data set to be modified :type data: ``dict`` ''' if data is None: raise BadRequest('Failed to modify document. No data fields to modify') # validate partial data cls._validate(data) query = {cls.primary_key: key} for i in cls.connection_retries(): try: result = await db[cls.get_collection_name()].find_one_and_update( filter=query, update={'$set': data}, return_document=ReturnDocument.AFTER ) if result: updated_obj = cls.create_model(result) updated_obj._db = db # emit post save asyncio.ensure_future(post_save.send( sender=cls, db=db, instance=updated_obj, created=False) ) return updated_obj return None except ConnectionFailure as ex: exceed = await cls.check_reconnect_tries_and_wait(i, 'update') if exceed: raise ex
class MongoCollectionMixin(object): ''' Mixin for data models, provides a persistency layer over a MongoDB collection ''' @property def db(self): pass @property def pk(self): pass @classmethod def process_query(cls, query): ''' modify queries before sending to db ''' pass @classmethod def get_collection_name(cls): ''' Gets the full name of the collection, as declared by the ModelOptions class like so: namespace.name If no namespace or name is provided, the class's lowercase name is used ''' pass @staticmethod def connection_retries(): ''' returns the number of connection retries. Subclass to obtain this variable from the app's global settings ''' pass @classmethod async def check_reconnect_tries_and_wait(cls, reconnect_number, method_name): pass @classmethod async def count(cls, db, filters={}): pass @classmethod async def find_one(cls, db, query): pass @classmethod def get_cursor(cls, db, query={}, projection=None, sort=[]): pass @classmethod async def create_index(cls, db, indices, **kwargs): pass @classmethod async def find_one(cls, db, query): pass @classmethod async def distinct(cls, db, key): pass @classmethod async def delete_entries(cls, db, query): ''' Delete documents by given query. ''' pass async def delete_entries(cls, db, query): ''' Delete document ''' pass @classmethod def create_model(cls, data: dict, fields=None): ''' Creates model instance from data (dict). ''' pass def prepare_data(self, data=None): ''' Prepare data for persistency by exporting it to native form and making sure we're not persisting with a null primary key. ''' pass async def save(self, db=None): ''' If object has _id, then object will be created or fully rewritten. If not, object will be inserted and _id will be assigned. ''' pass async def insert(self, db=None): ''' If object has _id then a DuplicateError will be thrown. If not, object will be inserted and _id will be assigned. ''' pass async def update(self, db=None, data=None): ''' Update the entire document by replacing its content with new data, retaining its primary key ''' pass @classmethod async def modify(cls, db, key, data: dict): ''' Partially modify a document by providing a subset of its data fields to be modified :param db: Handle to the MongoDB database :param key: The primary key of the database object being modified. Usually its ``_id`` :param data: The data set to be modified :type data: ``dict`` ''' pass
36
12
14
0
11
3
4
0.24
1
4
0
5
7
3
20
20
315
28
233
95
197
56
183
68
162
7
1
3
71
927
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/examples/chatrooms/backend/resources.py
resources.EntryResource.Meta
class Meta: object_class = Entry authentication = UserAuthentication() # revert order by creation, we want to display by order of entry decending sort = [('_id', -1)] hypermedia = False
class Meta: pass
1
0
0
0
0
0
0
0.2
0
0
0
0
0
0
0
0
5
0
5
5
4
1
5
5
4
0
0
0
0
928
475Cumulus/TBone
475Cumulus_TBone/tbone/dispatch/carriers/__init__.py
tbone.dispatch.carriers.Carrier
class Carrier(object): async def deliver(self, data): pass
class Carrier(object): async def deliver(self, data): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
4
1
3
2
1
0
3
2
1
1
1
0
1
929
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/flask_resty/api.py
flask_resty.api.Api
class Api: """The Api object controls the Flask-RESTy extension. This can either be bound to an individual Flask application passed in at initialization, or to multiple applications via :py:meth:`init_app`. After initializing an application, use this object to register resources with :py:meth:`add_resource`, either to the bound application by default or to an explicitly-specified application object via the `app` keyword argument. Use :py:meth:`add_ping` to add a ping endpoint for health checks. Once registered, Flask-RESTy will convert all HTTP errors thrown by the application to JSON. By default your API will be rooted at '/'. Pass `prefix` to specify a custom root. :param app: The Flask application object. :type app: :py:class:`flask.Flask` :param str prefix: The API path prefix. """ def __init__(self, app=None, prefix=""): if app: self._app = app self.init_app(app) else: self._app = None self.prefix = prefix def init_app(self, app): """Initialize an application for use with Flask-RESTy. :param app: The Flask application object. :type app: :py:class:`flask.Flask` """ app.extensions["resty"] = FlaskRestyState(self) app.register_error_handler(ApiError, handle_api_error) app.register_error_handler(HTTPException, handle_http_exception) def _get_app(self, app): app = app or self._app assert app, "no application specified" return app def add_resource( self, base_rule, base_view, alternate_view=None, *, alternate_rule=None, id_rule=None, app=None, ): """Add a REST resource. :param str base_rule: The URL rule for the resource. This will be prefixed by the API prefix. :param ApiView base_view: Class-based view for the resource. :param ApiView alternate_view: If specified, an alternate class-based view for the resource. Usually, this will be a detail view, when the base view is a list view. :param alternate_rule: If specified, the URL rule for the alternate view. This will be prefixed by the API prefix. This is mutually exclusive with `id_rule`, and must not be specified if `alternate_view` is not specified. :type alternate_rule: str or None :param id_rule: If specified, a suffix to append to `base_rule` to get the alternate view URL rule. If `alternate_view` is specified, and `alternate_rule` is not, then this defaults to '<id>'. This is mutually exclusive with `alternate_rule`, and must not be specified if `alternate_view` is not specified. :type id_rule: str or None :param app: If specified, the application to which to add the route(s). Otherwise, this will be the bound application, if present. :type app: :py:class:`flask.Flask` :raises AssertionError: If no Flask application is bound or specified. """ if alternate_view: if not alternate_rule: id_rule = id_rule or DEFAULT_ID_RULE alternate_rule = posixpath.join(base_rule, id_rule) else: assert id_rule is None else: assert alternate_rule is None assert id_rule is None app = self._get_app(app) endpoint = self._get_endpoint(base_view, alternate_view) base_rule_full = f"{self.prefix}{base_rule}" base_view_func = base_view.as_view(endpoint) if not alternate_view: app.add_url_rule(base_rule_full, view_func=base_view_func) return alternate_rule_full = f"{self.prefix}{alternate_rule}" alternate_view_func = alternate_view.as_view(endpoint) @functools.wraps(base_view_func) def view_func(*args, **kwargs): if flask.request.url_rule.rule == base_rule_full: return base_view_func(*args, **kwargs) else: return alternate_view_func(*args, **kwargs) app.add_url_rule( base_rule_full, view_func=view_func, endpoint=endpoint, methods=base_view.methods, ) app.add_url_rule( alternate_rule_full, view_func=view_func, endpoint=endpoint, methods=alternate_view.methods, ) def _get_endpoint(self, base_view, alternate_view): base_view_name = base_view.__name__ if not alternate_view: return base_view_name alternate_view_name = alternate_view.__name__ if len(alternate_view_name) < len(base_view_name): return alternate_view_name else: return base_view_name def add_ping(self, rule, *, status_code=200, app=None): """Add a ping route. :param str rule: The URL rule. This will not use the API prefix, as the ping endpoint is not really part of the API. :param int status_code: The ping response status code. The default is 200 rather than the more correct 204 because many health checks look for 200s. :param app: If specified, the application to which to add the route. Otherwise, this will be the bound application, if present. :type app: :py:class:`flask.Flask` :raises AssertionError: If no Flask application is bound or specified. """ app = self._get_app(app) @app.route(rule) def ping(): return "", status_code
class Api: '''The Api object controls the Flask-RESTy extension. This can either be bound to an individual Flask application passed in at initialization, or to multiple applications via :py:meth:`init_app`. After initializing an application, use this object to register resources with :py:meth:`add_resource`, either to the bound application by default or to an explicitly-specified application object via the `app` keyword argument. Use :py:meth:`add_ping` to add a ping endpoint for health checks. Once registered, Flask-RESTy will convert all HTTP errors thrown by the application to JSON. By default your API will be rooted at '/'. Pass `prefix` to specify a custom root. :param app: The Flask application object. :type app: :py:class:`flask.Flask` :param str prefix: The API path prefix. ''' def __init__(self, app=None, prefix=""): pass def init_app(self, app): '''Initialize an application for use with Flask-RESTy. :param app: The Flask application object. :type app: :py:class:`flask.Flask` ''' pass def _get_app(self, app): pass def add_resource( self, base_rule, base_view, alternate_view=None, *, alternate_rule=None, id_rule=None, app=None, ): '''Add a REST resource. :param str base_rule: The URL rule for the resource. This will be prefixed by the API prefix. :param ApiView base_view: Class-based view for the resource. :param ApiView alternate_view: If specified, an alternate class-based view for the resource. Usually, this will be a detail view, when the base view is a list view. :param alternate_rule: If specified, the URL rule for the alternate view. This will be prefixed by the API prefix. This is mutually exclusive with `id_rule`, and must not be specified if `alternate_view` is not specified. :type alternate_rule: str or None :param id_rule: If specified, a suffix to append to `base_rule` to get the alternate view URL rule. If `alternate_view` is specified, and `alternate_rule` is not, then this defaults to '<id>'. This is mutually exclusive with `alternate_rule`, and must not be specified if `alternate_view` is not specified. :type id_rule: str or None :param app: If specified, the application to which to add the route(s). Otherwise, this will be the bound application, if present. :type app: :py:class:`flask.Flask` :raises AssertionError: If no Flask application is bound or specified. ''' pass @functools.wraps(base_view_func) def view_func(*args, **kwargs): pass def _get_endpoint(self, base_view, alternate_view): pass def add_ping(self, rule, *, status_code=200, app=None): '''Add a ping route. :param str rule: The URL rule. This will not use the API prefix, as the ping endpoint is not really part of the API. :param int status_code: The ping response status code. The default is 200 rather than the more correct 204 because many health checks look for 200s. :param app: If specified, the application to which to add the route. Otherwise, this will be the bound application, if present. :type app: :py:class:`flask.Flask` :raises AssertionError: If no Flask application is bound or specified. ''' pass @app.route(rule) def ping(): pass
11
4
17
2
10
5
2
0.71
0
2
2
0
6
2
6
6
154
24
76
29
56
54
50
18
41
4
0
2
15
930
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_args.py
tests.test_args.schemas.NameDefaultSchema
class NameDefaultSchema(Schema): name = fields.String(**{LOAD_DEFAULT_KWARG: "foo"})
class NameDefaultSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
931
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/authentication.py
flask_resty.authentication.HeaderAuthentication
class HeaderAuthentication(HeaderAuthenticationBase): """Header authentication component where the token is the credential. This authentication component is useful for simple applications where the token itself is the credential, such as when it is a fixed secret shared between the client and the server that uniquely identifies the client. """ def get_credentials_from_token(self, token): return token
class HeaderAuthentication(HeaderAuthenticationBase): '''Header authentication component where the token is the credential. This authentication component is useful for simple applications where the token itself is the credential, such as when it is a fixed secret shared between the client and the server that uniquely identifies the client. ''' def get_credentials_from_token(self, token): pass
2
1
2
0
2
0
1
1.67
1
0
0
2
1
0
1
7
10
2
3
2
1
5
3
2
1
1
2
0
1
932
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_args.py
tests.test_args.schemas.NameListSchema
class NameListSchema(Schema): names = fields.List(fields.String(), data_key="name", required=True)
class NameListSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
933
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
tests.test_pagination.schemas.WidgetSchema
class WidgetSchema(Schema): id = fields.Integer(as_string=True) size = fields.Integer() name = fields.String() is_cool = fields.Boolean()
class WidgetSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
5
0
5
4
4
0
5
4
4
0
1
0
0
934
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
tests.test_pagination.schemas.WidgetValidateSchema
class WidgetValidateSchema(WidgetSchema): size = fields.Integer(validate=validate.Range(max=1))
class WidgetValidateSchema(WidgetSchema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
2
0
0
935
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
tests.test_pagination.test_pagination_cursor_parsing.View
class View(GenericModelView): model = models["widget"] schema = schemas["widget"] sorting = Sorting("id", "size", "is_cool") pagination = RelayCursorPagination() def get(self): return self.list() def post(self): return self.create()
class View(GenericModelView): def get(self): pass def post(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
63
12
3
9
7
6
0
9
7
6
1
4
0
2
936
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.models.Child
class Child(db.Model): __tablename__ = "children" id = Column(Integer, primary_key=True) name = Column(String) parent_id = Column(ForeignKey(Parent.id)) parent = relationship( Parent, foreign_keys=parent_id, backref="children" ) other_parent_id = Column(ForeignKey(Parent.id)) other_parent = relationship(Parent, foreign_keys=other_parent_id)
class Child(db.Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
13
3
10
7
9
0
8
7
7
0
1
0
0
937
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.models.Parent
class Parent(db.Model): __tablename__ = "parents" id = Column(Integer, primary_key=True) name = Column(String)
class Parent(db.Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
1
4
3
3
0
4
3
3
0
1
0
0
938
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.routes.ChildView
class ChildView(GenericModelView): model = models["child"] schema = schemas["child"] base_query_options = (raiseload("*"),) related = Related(parent=RelatedId(ParentView, "parent_id")) def get(self, id): return self.retrieve(id) def put(self, id): return self.update(id)
class ChildView(GenericModelView): def get(self, id): pass def put(self, id): pass
3
0
2
0
2
0
1
0
1
0
0
1
2
0
2
63
13
4
9
7
6
0
9
7
6
1
4
0
2
939
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.routes.ChildWithOtherParentView
class ChildWithOtherParentView(ChildView): related = ChildView.related | Related( other_parent=Related(models["parent"]) )
class ChildWithOtherParentView(ChildView): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
63
4
0
4
2
3
0
2
2
1
0
5
0
0
940
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.routes.NestedChildView
class NestedChildView(GenericModelView): model = models["child"] schema = schemas["child"] related = Related(parent=ParentView) def put(self, id): return self.update(id)
class NestedChildView(GenericModelView): def put(self, id): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
62
8
2
6
5
4
0
6
5
4
1
4
0
1
941
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.routes.NestedParentView
class NestedParentView(ParentView): related = Related(children=lambda: ChildView()) def put(self, id): return self.update(id)
class NestedParentView(ParentView): def put(self, id): pass
2
0
2
0
2
0
1
0
1
1
1
0
1
0
1
64
5
1
4
3
2
0
4
3
2
1
5
0
1
942
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.routes.ParentView
class ParentView(GenericModelView): model = models["parent"] schema = schemas["parent"] related = Related(children=RelatedId(lambda: ChildView(), "child_ids")) def get(self, id): return self.retrieve(id) def put(self, id): return self.update(id)
class ParentView(GenericModelView): def get(self, id): pass def put(self, id): pass
3
0
2
0
2
0
1
0
1
1
1
2
2
0
2
63
11
3
8
6
5
0
8
6
5
1
4
0
2
943
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.routes.ParentWithCreateView
class ParentWithCreateView(ParentView): related = Related(children=Related(models["child"])) def put(self, id): return self.update(id)
class ParentWithCreateView(ParentView): def put(self, id): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
64
5
1
4
3
2
0
4
3
2
1
5
0
1
944
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.schemas.ChildSchema
class ChildSchema(Schema): @classmethod def get_query_options(cls, load): return ( load.joinedload(models["child"].parent), load.joinedload(models["child"].other_parent), ) id = fields.Integer(as_string=True) name = fields.String(required=True) parent = RelatedItem( ParentSchema, exclude=("children",), allow_none=True ) parent_id = fields.Integer( as_string=True, allow_none=True, load_only=True ) other_parent = fields.Nested( ParentSchema, exclude=("children",), allow_none=True )
class ChildSchema(Schema): @classmethod def get_query_options(cls, load): pass
3
0
5
0
5
0
1
0
1
0
0
0
0
0
1
1
21
3
18
7
15
0
8
6
6
1
1
0
1
945
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_related.py
tests.test_related.schemas.ParentSchema
class ParentSchema(Schema): id = fields.Integer(as_string=True) name = fields.String(required=True) children = RelatedItem( "ChildSchema", many=True, exclude=("parent", "other_parent") ) child_ids = fields.List(fields.Integer(as_string=True), load_only=True)
class ParentSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
8
1
7
4
6
0
5
4
4
0
1
0
0
946
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
tests.test_pagination.routes.WidgetListViewBase
class WidgetListViewBase(GenericModelView): model = models["widget"] schema = schemas["widget"] def get(self): return self.list() def post(self): return self.create()
class WidgetListViewBase(GenericModelView): def get(self): pass def post(self): pass
3
0
2
0
2
0
1
0
1
0
0
5
2
0
2
63
9
2
7
5
4
0
7
5
4
1
4
0
2
947
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_shell.py
tests.test_shell.models.Widget
class Widget(db.Model): __tablename__ = "widgets" id = Column(Integer, primary_key=True) name = Column(String, nullable=False) description = Column(String)
class Widget(db.Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
6
1
5
4
4
0
5
4
4
0
1
0
0
948
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_sorting.py
tests.test_sorting.models.Widget
class Widget(db.Model): __tablename__ = "widgets" id = Column(Integer, primary_key=True) name = Column(String) content = Column(String) size = Column(Integer)
class Widget(db.Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
1
6
5
5
0
6
5
5
0
1
0
0
949
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_sorting.py
tests.test_sorting.routes.FixedWidgetListView
class FixedWidgetListView(WidgetListView): sorting = FixedSorting("name,size") def get(self): return self.list()
class FixedWidgetListView(WidgetListView): def get(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
63
5
1
4
3
2
0
4
3
2
1
5
0
1
950
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_sorting.py
tests.test_sorting.routes.WidgetListView
class WidgetListView(GenericModelView): model = models["widget"] schema = schemas["widget"] sorting = Sorting( "name", "size", content_length=sql.func.length(Widget.content), content_length2=lambda model, field_name: sql.func.length( model.content ), ) def get(self): return self.list()
class WidgetListView(GenericModelView): def get(self): pass
2
0
2
0
2
0
1
0
1
0
0
1
1
0
1
62
15
2
13
5
11
0
6
5
4
1
4
0
1
951
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_sorting.py
tests.test_sorting.schemas.WidgetSchema
class WidgetSchema(Schema): id = fields.Integer(as_string=True) name = fields.String() content = fields.String() size = fields.Integer()
class WidgetSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
0
5
4
4
0
5
4
4
0
1
0
0
952
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_utils.py
tests.test_utils.test_settable_property.Foo
class Foo: @settable_property def value(self): return 3
class Foo: @settable_property def value(self): pass
3
0
2
0
2
0
1
0
0
0
0
0
1
0
1
1
4
0
4
3
1
0
3
2
1
1
0
0
1
953
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.models.Widget
class Widget(db.Model): __tablename__ = "widgets" id = Column(Integer, primary_key=True) name = Column(String, nullable=False, unique=True)
class Widget(db.Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
1
4
3
3
0
4
3
3
0
1
0
0
954
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.schemas.NestedSchema
class NestedSchema(Schema): value = fields.Integer()
class NestedSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
955
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.schemas.WidgetSchema
class WidgetSchema(Schema): id = fields.Integer(as_string=True) name = fields.String(required=True, allow_none=True) nested = fields.Nested(NestedSchema) nested_many = fields.Nested(NestedSchema, many=True)
class WidgetSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
0
5
4
4
0
5
4
4
0
1
0
0
956
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.views.AbortView
class AbortView(ApiView): def get(self): flask.abort(400)
class AbortView(ApiView): def get(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
25
3
0
3
2
1
0
3
2
1
1
2
0
1
957
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.views.DefaultErrorView
class DefaultErrorView(ApiView): def get(self): raise ApiError(int(flask.request.args.get("status_code", 400)))
class DefaultErrorView(ApiView): def get(self): pass
2
0
2
0
2
0
1
0
1
2
1
0
1
0
1
25
3
0
3
2
1
0
3
2
1
1
2
0
1
958
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.views.SlashView
class SlashView(ApiView): def get(self): return self.make_empty_response()
class SlashView(ApiView): def get(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
25
3
0
3
2
1
0
3
2
1
1
2
0
1
959
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.views.UncaughtView
class UncaughtView(ApiView): def get(self): raise RuntimeError()
class UncaughtView(ApiView): def get(self): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
25
3
0
3
2
1
0
3
2
1
1
2
0
1
960
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.views.WidgetFlushListView
class WidgetFlushListView(WidgetViewBase): def post(self): return self.create() def add_item(self, widget): super().add_item(widget) self.flush()
class WidgetFlushListView(WidgetViewBase): def post(self): pass def add_item(self, widget): pass
3
0
3
0
3
0
1
0
1
1
0
0
2
0
2
63
7
1
6
3
3
0
6
3
3
1
5
0
2
961
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_shell.py
tests.test_shell.schemas.WidgetSchema
class WidgetSchema(Schema): id = fields.Integer(as_string=True) name = fields.String(required=True) description = fields.String()
class WidgetSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
3
3
0
4
3
3
0
1
0
0
962
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_pagination.py
tests.test_pagination.routes.RelayCursorNoValidateListView
class RelayCursorNoValidateListView(RelayCursorListView): schema = schemas["widget_validate"] pagination = RelayCursorPagination( 2, page_info_arg="page_info", validate_values=False )
class RelayCursorNoValidateListView(RelayCursorListView): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
63
6
1
5
3
4
0
3
3
2
0
6
0
0
963
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/view.py
flask_resty.view.ModelView
class ModelView(ApiView): """Base class for API views tied to SQLAlchemy models. `ModelView` implements additional methods on top of those provided by `ApiView` to interact with SQLAlchemy models. The functionality in this class largely ties together the authorization and the model. It provides for access to the model query as appropriately filtered for authorized rows, and provides methods to create or update model instances from request data with authorization checks. It also provides functionality to apply filtering, sorting, and pagination when getting lists of items, and for resolving related items when deserializing request data. """ #: A declarative SQLAlchemy model. model = None #: An instance of :py:class:`filtering.Filtering`. filtering = None #: An instance of :py:class:`sorting.SortingBase`. sorting = None #: An instance of :py:class:`pagination.PaginationBase`. pagination = None #: An instance of :py:class:`related.Related`. related = None @settable_property def session(self): """Convenience property for the current SQLAlchemy session.""" return flask.current_app.extensions["sqlalchemy"].session @settable_property def query_raw(self): """The raw SQLAlchemy query for the view. This is the base query, without authorization filters or query options. By default, this is the query property on the model class. This can be overridden to remove filters attached to that query. """ return self.model.query @settable_property def query(self): """The SQLAlchemy query for the view. Override this to customize the query to fetch items in this view. By default, this applies the filter from the view's `authorization` and the query options from `base_query_options` and `query_options`. """ query = self.query_raw query = self.authorization.filter_query(query, self) query = query.options( *itertools.chain(self.base_query_options, self.query_options) ) return query #: Base query options to apply before `query_options`. #: #: Set this on a base class to define base query options for its #: subclasses, while still allowing those subclasses to define their own #: additional query options via `query_options`. #: #: For example, set this to ``(raiseload('*', sql_only=True),)`` to prevent #: all implicit SQL-emitting relationship loading, and force all #: relationship loading to be explicitly defined via `query_options`. base_query_options = () @settable_property def query_options(self): """Options to apply to the query for the view. Set this to configure relationship and column loading. By default, this calls the ``get_query_options`` method on the serializer with a `Load` object bound to the model, if that serializer method exists. :return: A sequence of query options. :rtype: tuple """ if not hasattr(self.serializer, "get_query_options"): return () return self.serializer.get_query_options(Load(self.model)) def get_list(self): """Retrieve a list of items. This takes the output of `get_list_query` and applies pagination. :return: The list of items. :rtype: list """ return self.paginate_list_query(self.get_list_query()) def get_list_query(self): """Build the query to retrieve a filtered and sorted list of items. :return: The list query. :rtype: :py:class:`sqlalchemy.orm.query.Query` """ query = self.query query = self.filter_list_query(query) query = self.sort_list_query(query) return query def filter_list_query(self, query): """Apply filtering as specified to the provided `query`. :param: A SQL query :type: :py:class:`sqlalchemy.orm.query.Query` :return: The filtered query :rtype: :py:class:`sqlalchemy.orm.query.Query` """ if not self.filtering: return query return self.filtering.filter_query(query, self) def sort_list_query(self, query): """Apply sorting as specified to the provided `query`. :param: A SQL query :type: :py:class:`sqlalchemy.orm.query.Query` :return: The sorted query :rtype: :py:class:`sqlalchemy.orm.query.Query` """ if not self.sorting: return query return self.sorting.sort_query(query, self) def paginate_list_query(self, query): """Retrieve the requested page from `query`. If :py:attr:`pagination` is configured, this will retrieve the page as specified by the request and the pagination configuration. Otherwise, this will retrieve all items from the query. :param: A SQL query :type: :py:class:`sqlalchemy.orm.query.Query` :return: The paginated query :rtype: :py:class:`sqlalchemy.orm.query.Query` """ if not self.pagination: return query.all() return self.pagination.get_page(query, self) def get_item_or_404(self, id, **kwargs): """Get an item by ID; raise a 404 if it not found. This will get an item by ID per `get_item` below. If no item is found, it will rethrow the `NoResultFound` exception as an HTTP 404. :param id: The item ID. :return: The item corresponding to the ID. :rtype: object """ try: item = self.get_item(id, **kwargs) except NoResultFound as e: raise NotFound() from e return item def get_item( self, id, *, with_for_update=False, create_transient_stub=False, ): """Get an item by ID. The ID should be the scalar ID value if `id_fields` specifies a single field. Otherwise, it should be a tuple of each ID field value, corresponding to the elements of `id_fields`. :param id: The item ID. :param bool with_for_update: If set, lock the item row for updating using ``FOR UPDATE``. :param bool create_transient_stub: If set, create and return a transient stub for the item using `create_stub_item` if it is not found. This will not save the stub to the database. :return: The item corresponding to the ID. :rtype: object """ try: # Can't use self.query.get(), because query might be filtered. item_query = self.query.filter( *( getattr(self.model, field) == value for field, value in self.get_id_dict(id).items() ) ) if with_for_update: item_query = item_query.with_for_update(of=self.model) item = item_query.one() except NoResultFound as e: if not create_transient_stub: raise try: item = self.create_stub_item(id) except ApiError: # Raise the original not found error instead of the # authorization error. raise e return item def deserialize(self, data_raw, **kwargs): """Load data using the :py:attr:`deserializer`. In addition to the functionality of :py:meth:`ApiView.deserialize`, this will resolve related items using the configured `related`. """ data = super().deserialize(data_raw, **kwargs) return self.resolve_related(data) def resolve_related(self, data): """Resolve all related fields per :py:attr:`related`. :param object data: A deserialized object :return: The object with related fields resolved :rtype: object """ if not self.related: return data return self.related.resolve_related(data) def resolve_related_item(self, data, **kwargs): """Retrieve the related item corresponding to the provided data stub. This is used by `Related` when this view is set for a field. :param dict data: Stub item data with ID fields. :return: The item corresponding to the ID in the data. :rtype: object """ try: id = self.get_data_id(data) except KeyError as e: raise ApiError(422, {"code": "invalid_related.missing_id"}) from e return self.resolve_related_id(id, **kwargs) def resolve_related_id(self, id, **kwargs): """Retrieve the related item corresponding to the provided ID. This is used by `Related` when a field is specified as a `RelatedId`. :param id: The item ID. :return: The item corresponding to the ID. :rtype: object """ try: item = self.get_item(id, **kwargs) except NoResultFound as e: raise ApiError(422, {"code": "invalid_related.not_found"}) from e return item def create_stub_item(self, id): """Create a stub item that corresponds to the provided ID. This is used by `get_item` when `create_transient_stub` is set. Override this to configure the creation of stub items. :param id: The item ID. :return: A transient stub item corresponding to the ID. :rtype: object """ return self.create_item(self.get_id_dict(id)) def create_item(self, data): """Create an item using the provided data. This will invoke `authorize_create_item` on the created item. Override this to configure the creation of items, e.g. by adding additional entries to `data`. :param dict data: The deserialized data. :return: The newly created item. :rtype: object """ item = self.create_item_raw(data) self.authorization.authorize_create_item(item) return item def create_item_raw(self, data): """As with `create_item`, but without the authorization check. This is used by `create_item`, which then applies the authorization check. Override this instead of `create_item` when applying other modifications to the item that should take place before running the authorization check. :param dict data: The deserialized data. :return: The newly created item. :rtype: object """ return self.model(**data) def add_item(self, item): """Add an item to the current session. This will invoke `authorize_save_item` on the item to add. :param object item: The item to add. """ self.authorization.authorize_save_item(item) self.add_item_raw(item) def add_item_raw(self, item): """As with `add_item`, but without the authorization check. This is used by `add_item`, which then applies the authorization check. :param object item: The item to add. """ self.session.add(item) def create_and_add_item(self, data): """Create an item using the provided data, then add it to the session. This uses `create_item` and `add_item`. Correspondingly, it will invoke both `authorize_create_item` and `authorize_save_item` on the item. :param dict data: The deserialized data. :return: The created and added item. :rtype: object """ item = self.create_item(data) self.add_item(item) return item def update_item(self, item, data): """Update an existing item with the provided data. This will invoke `authorize_update_item` using the provided item and data before updating the item, then `authorize_save_item` on the updated item afterward. Override this to configure the updating of items, e.g. by adding additional entries to `data`. :param object item: The item to update. :param dict data: The deserialized data. :return: The newly updated item. :rtype: object """ self.authorization.authorize_update_item(item, data) item = self.update_item_raw(item, data) or item self.authorization.authorize_save_item(item) return item def update_item_raw(self, item, data): """As with `update_item`, but without the authorization checks. Override this instead of `update_item` when applying other modifications to the item that should take place before and after the authorization checks in the above. :param object item: The item to update. :param dict data: The deserialized data. :return: The newly updated item. :rtype: object """ for key, value in data.items(): setattr(item, key, value) return item def upsert_item(self, id, data, with_for_update=False): """Update an existing item with the matching id or if the item does not exist yet, create and insert it. This combines `self.create_and_add_item` and `self.update_item` depending on if the item exists or not. :param id: The item's identifier. :param dict data: The data to insert or update. :param bool with_for_update: If set, lock the item row for updating using ``FOR UPDATE``. :return: a tuple consisting of the newly created or the updated item and True if the item was created, False otherwise. :rtype: object, bool """ try: item = self.get_item(id, with_for_update=with_for_update) except NoResultFound: item = self.create_and_add_item(data) return item, True else: item = self.update_item(item, data) or item return item, False def delete_item(self, item): """Delete an existing item. This will run `authorize_delete_item` on the item before deleting it. :param object item: The item to delete. :return: The deleted item. :rtype: object """ self.authorization.authorize_delete_item(item) item = self.delete_item_raw(item) or item return item def delete_item_raw(self, item): """As with `delete_item`, but without the authorization check. Override this to customize the delete behavior, e.g. by replacing the delete action with an update to mark the item deleted. :param object item: The item to delete. """ self.session.delete(item) def flush(self, *, objects=None): """Flush pending changes to the database. This will check database level invariants, and will throw exceptions as with `commit` if any invariant violations are found. It's a common pattern to call `flush`, then make external API calls, then call `commit`. The `flush` call will do a preliminary check on database-level invariants, making it less likely that the `commit` operation will fail, and reducing the risk of the external systems being left in an inconsistent state. :param objects: If specified, the specific objects to flush. Otherwise, all pending changes will be flushed. :return: """ try: # Flushing allows checking invariants without committing. self.session.flush(objects=objects) # Don't catch DataErrors here, as they arise from bugs in validation in # the schema. except IntegrityError as e: raise self.resolve_integrity_error(e) from e def commit(self): """Commit changes to the database. Any integrity errors that arise will be passed to `resolve_integrity_error`, which is expected to convert integrity errors corresponding to cross-row database-level invariant violations to HTTP 409 responses. :raises: :py:class:`ApiError` if the commit fails with integrity errors arising from foreign key or unique constraint violations. """ try: self.session.commit() # Don't catch DataErrors here, as they arise from bugs in validation in # the schema. except IntegrityError as e: raise self.resolve_integrity_error(e) from e def resolve_integrity_error(self, error): """Convert integrity errors to HTTP error responses as appropriate. Certain kinds of database integrity errors cannot easily be caught by schema validation. These errors include violations of unique constraints and of foreign key constraints. While it's sometimes possible to check for those in application code, it's often best to let the database handle those. This will then convert those integrity errors to HTTP 409 responses. On PostgreSQL, this uses additional integrity error details to not convert NOT NULL violations and CHECK constraint violations to HTTP 409 responses, as such checks should be done in the schema. :return: The resolved error. :rtype: :py:class:`Exception` """ original_error = error.orig if hasattr(original_error, "pgcode") and original_error.pgcode in ( "23502", # not_null_violation ): # Using the psycopg2 error code, we can tell that this was not from # an integrity error that was not a conflict. This means there was # a schema bug, so we emit an interal server error instead. return error flask.current_app.logger.warning( "handled integrity error", exc_info=error ) return ApiError(409, {"code": "invalid_data.conflict"}) def set_item_response_meta(self, item): """Set the appropriate response metadata for the response item. By default, this adds the item metadata from the pagination component. :param object item: The item in the response. """ super().set_item_response_meta(item) self.set_item_response_meta_pagination(item) def set_item_response_meta_pagination(self, item): """Set pagination metadata for the response item. This uses the configured pagination component to set pagination metadata for the response item. :param object item: The item in the response. """ if not self.pagination: return meta.update_response_meta(self.pagination.get_item_meta(item, self))
class ModelView(ApiView): '''Base class for API views tied to SQLAlchemy models. `ModelView` implements additional methods on top of those provided by `ApiView` to interact with SQLAlchemy models. The functionality in this class largely ties together the authorization and the model. It provides for access to the model query as appropriately filtered for authorized rows, and provides methods to create or update model instances from request data with authorization checks. It also provides functionality to apply filtering, sorting, and pagination when getting lists of items, and for resolving related items when deserializing request data. ''' @settable_property def session(self): '''Convenience property for the current SQLAlchemy session.''' pass @settable_property def query_raw(self): '''The raw SQLAlchemy query for the view. This is the base query, without authorization filters or query options. By default, this is the query property on the model class. This can be overridden to remove filters attached to that query. ''' pass @settable_property def query_raw(self): '''The SQLAlchemy query for the view. Override this to customize the query to fetch items in this view. By default, this applies the filter from the view's `authorization` and the query options from `base_query_options` and `query_options`. ''' pass @settable_property def query_options(self): '''Options to apply to the query for the view. Set this to configure relationship and column loading. By default, this calls the ``get_query_options`` method on the serializer with a `Load` object bound to the model, if that serializer method exists. :return: A sequence of query options. :rtype: tuple ''' pass def get_list(self): '''Retrieve a list of items. This takes the output of `get_list_query` and applies pagination. :return: The list of items. :rtype: list ''' pass def get_list_query(self): '''Build the query to retrieve a filtered and sorted list of items. :return: The list query. :rtype: :py:class:`sqlalchemy.orm.query.Query` ''' pass def filter_list_query(self, query): '''Apply filtering as specified to the provided `query`. :param: A SQL query :type: :py:class:`sqlalchemy.orm.query.Query` :return: The filtered query :rtype: :py:class:`sqlalchemy.orm.query.Query` ''' pass def sort_list_query(self, query): '''Apply sorting as specified to the provided `query`. :param: A SQL query :type: :py:class:`sqlalchemy.orm.query.Query` :return: The sorted query :rtype: :py:class:`sqlalchemy.orm.query.Query` ''' pass def paginate_list_query(self, query): '''Retrieve the requested page from `query`. If :py:attr:`pagination` is configured, this will retrieve the page as specified by the request and the pagination configuration. Otherwise, this will retrieve all items from the query. :param: A SQL query :type: :py:class:`sqlalchemy.orm.query.Query` :return: The paginated query :rtype: :py:class:`sqlalchemy.orm.query.Query` ''' pass def get_item_or_404(self, id, **kwargs): '''Get an item by ID; raise a 404 if it not found. This will get an item by ID per `get_item` below. If no item is found, it will rethrow the `NoResultFound` exception as an HTTP 404. :param id: The item ID. :return: The item corresponding to the ID. :rtype: object ''' pass def get_item_or_404(self, id, **kwargs): '''Get an item by ID. The ID should be the scalar ID value if `id_fields` specifies a single field. Otherwise, it should be a tuple of each ID field value, corresponding to the elements of `id_fields`. :param id: The item ID. :param bool with_for_update: If set, lock the item row for updating using ``FOR UPDATE``. :param bool create_transient_stub: If set, create and return a transient stub for the item using `create_stub_item` if it is not found. This will not save the stub to the database. :return: The item corresponding to the ID. :rtype: object ''' pass def deserialize(self, data_raw, **kwargs): '''Load data using the :py:attr:`deserializer`. In addition to the functionality of :py:meth:`ApiView.deserialize`, this will resolve related items using the configured `related`. ''' pass def resolve_related(self, data): '''Resolve all related fields per :py:attr:`related`. :param object data: A deserialized object :return: The object with related fields resolved :rtype: object ''' pass def resolve_related_item(self, data, **kwargs): '''Retrieve the related item corresponding to the provided data stub. This is used by `Related` when this view is set for a field. :param dict data: Stub item data with ID fields. :return: The item corresponding to the ID in the data. :rtype: object ''' pass def resolve_related_id(self, id, **kwargs): '''Retrieve the related item corresponding to the provided ID. This is used by `Related` when a field is specified as a `RelatedId`. :param id: The item ID. :return: The item corresponding to the ID. :rtype: object ''' pass def create_stub_item(self, id): '''Create a stub item that corresponds to the provided ID. This is used by `get_item` when `create_transient_stub` is set. Override this to configure the creation of stub items. :param id: The item ID. :return: A transient stub item corresponding to the ID. :rtype: object ''' pass def create_item(self, data): '''Create an item using the provided data. This will invoke `authorize_create_item` on the created item. Override this to configure the creation of items, e.g. by adding additional entries to `data`. :param dict data: The deserialized data. :return: The newly created item. :rtype: object ''' pass def create_item_raw(self, data): '''As with `create_item`, but without the authorization check. This is used by `create_item`, which then applies the authorization check. Override this instead of `create_item` when applying other modifications to the item that should take place before running the authorization check. :param dict data: The deserialized data. :return: The newly created item. :rtype: object ''' pass def add_item(self, item): '''Add an item to the current session. This will invoke `authorize_save_item` on the item to add. :param object item: The item to add. ''' pass def add_item_raw(self, item): '''As with `add_item`, but without the authorization check. This is used by `add_item`, which then applies the authorization check. :param object item: The item to add. ''' pass def create_and_add_item(self, data): '''Create an item using the provided data, then add it to the session. This uses `create_item` and `add_item`. Correspondingly, it will invoke both `authorize_create_item` and `authorize_save_item` on the item. :param dict data: The deserialized data. :return: The created and added item. :rtype: object ''' pass def update_item(self, item, data): '''Update an existing item with the provided data. This will invoke `authorize_update_item` using the provided item and data before updating the item, then `authorize_save_item` on the updated item afterward. Override this to configure the updating of items, e.g. by adding additional entries to `data`. :param object item: The item to update. :param dict data: The deserialized data. :return: The newly updated item. :rtype: object ''' pass def update_item_raw(self, item, data): '''As with `update_item`, but without the authorization checks. Override this instead of `update_item` when applying other modifications to the item that should take place before and after the authorization checks in the above. :param object item: The item to update. :param dict data: The deserialized data. :return: The newly updated item. :rtype: object ''' pass def upsert_item(self, id, data, with_for_update=False): '''Update an existing item with the matching id or if the item does not exist yet, create and insert it. This combines `self.create_and_add_item` and `self.update_item` depending on if the item exists or not. :param id: The item's identifier. :param dict data: The data to insert or update. :param bool with_for_update: If set, lock the item row for updating using ``FOR UPDATE``. :return: a tuple consisting of the newly created or the updated item and True if the item was created, False otherwise. :rtype: object, bool ''' pass def delete_item(self, item): '''Delete an existing item. This will run `authorize_delete_item` on the item before deleting it. :param object item: The item to delete. :return: The deleted item. :rtype: object ''' pass def delete_item_raw(self, item): '''As with `delete_item`, but without the authorization check. Override this to customize the delete behavior, e.g. by replacing the delete action with an update to mark the item deleted. :param object item: The item to delete. ''' pass def flush(self, *, objects=None): '''Flush pending changes to the database. This will check database level invariants, and will throw exceptions as with `commit` if any invariant violations are found. It's a common pattern to call `flush`, then make external API calls, then call `commit`. The `flush` call will do a preliminary check on database-level invariants, making it less likely that the `commit` operation will fail, and reducing the risk of the external systems being left in an inconsistent state. :param objects: If specified, the specific objects to flush. Otherwise, all pending changes will be flushed. :return: ''' pass def commit(self): '''Commit changes to the database. Any integrity errors that arise will be passed to `resolve_integrity_error`, which is expected to convert integrity errors corresponding to cross-row database-level invariant violations to HTTP 409 responses. :raises: :py:class:`ApiError` if the commit fails with integrity errors arising from foreign key or unique constraint violations. ''' pass def resolve_integrity_error(self, error): '''Convert integrity errors to HTTP error responses as appropriate. Certain kinds of database integrity errors cannot easily be caught by schema validation. These errors include violations of unique constraints and of foreign key constraints. While it's sometimes possible to check for those in application code, it's often best to let the database handle those. This will then convert those integrity errors to HTTP 409 responses. On PostgreSQL, this uses additional integrity error details to not convert NOT NULL violations and CHECK constraint violations to HTTP 409 responses, as such checks should be done in the schema. :return: The resolved error. :rtype: :py:class:`Exception` ''' pass def set_item_response_meta(self, item): '''Set the appropriate response metadata for the response item. By default, this adds the item metadata from the pagination component. :param object item: The item in the response. ''' pass def set_item_response_meta_pagination(self, item): '''Set pagination metadata for the response item. This uses the configured pagination component to set pagination metadata for the response item. :param object item: The item in the response. ''' pass
36
32
15
2
5
7
2
1.53
1
4
1
2
31
0
31
55
526
114
163
66
121
250
142
50
110
5
2
2
49
964
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/view.py
flask_resty.view.GenericModelView
class GenericModelView(ModelView): """Base class for API views implementing CRUD methods. `GenericModelView` provides basic implementations of the standard CRUD HTTP methods using the methods implemented in `ModelView`. In simple APIs, most view classes will extend `GenericModelView`, and will declare methods that immediately call the methods here. :: class WidgetViewBase(GenericModelView): model = models.Widget schema = models.WidgetSchema() class WidgetListView(WidgetViewBase): def get(self): return self.list() def post(self): return self.create() class WidgetView(WidgetViewBase): def get(self, id): return self.retrieve(id) def patch(self, id): return self.update(id, partial=True) def delete(self, id): return self.destroy(id) To extend or otherwise customize the behavior of the methods here, override the methods in `MethodView`. """ def list(self): """Return a list of items. This is the standard GET handler on a list view. :return: An HTTP 200 response. :rtype: :py:class:`flask.Response` """ items = self.get_list() return self.make_items_response(items) def retrieve(self, id, *, create_transient_stub=False): """Retrieve an item by ID. This is the standard ``GET`` handler on a detail view. :param id: The item ID. :param bool create_transient_stub: If set, create and retrieve a transient stub for the item if it is not found. This will not save the stub to the database. :return: An HTTP 200 response. :rtype: :py:class:`flask.Response` """ item = self.get_item_or_404( id, create_transient_stub=create_transient_stub ) return self.make_item_response(item) def create(self, *, allow_client_id=False): """Create a new item using the request data. This is the standard ``POST`` handler on a list view. :param bool allow_client_id: If set, allow the client to specify ID fields for the item. :return: An HTTP 201 response. :rtype: :py:class:`flask.Response` """ expected_id = None if allow_client_id else False data_in = self.get_request_data(expected_id=expected_id) item = self.create_and_add_item(data_in) self.commit() return self.make_created_response(item) def update( self, id, *, with_for_update=False, partial=False, ): """Update the item for the specified ID with the request data. This is the standard ``PUT`` handler on a detail view if `partial` is not set, or the standard ``PATCH`` handler if `partial` is set. :param id: The item ID. :param bool with_for_update: If set, lock the item row while updating using ``FOR UPDATE``. :param bool partial: If set, perform a partial update for the item, ignoring fields marked ``required`` on `deserializer`. :return: An HTTP 200 response. :rtype: :py:class:`flask.Response` """ item = self.get_item_or_404(id, with_for_update=with_for_update) data_in = self.get_request_data(expected_id=id, partial=partial) item = self.update_item(item, data_in) or item self.commit() return self.make_item_response(item) def upsert(self, id, *, with_for_update=False): """Upsert the item for the specified ID with the request data. This will update the item for the given ID, if that item exists. Otherwise, this will create a new item with the request data. :param id: The item ID. :param bool with_for_update: If set, lock the item row while updating using ``FOR UPDATE``. :return: An HTTP 200 or 201 response. :rtype: :py:class:`flask.Response` """ data_in = self.get_request_data(expected_id=id) item, created = self.upsert_item(id, data_in) self.commit() return ( self.make_created_response(item) if created else self.make_item_response(item) ) def destroy(self, id): """Delete the item for the specified ID. :param id: The item ID. :return: An HTTP 204 response. :rtype: :py:class:`flask.Response` """ item = self.get_item_or_404(id) item = self.delete_item(item) or item self.commit() return self.make_deleted_response(item)
class GenericModelView(ModelView): '''Base class for API views implementing CRUD methods. `GenericModelView` provides basic implementations of the standard CRUD HTTP methods using the methods implemented in `ModelView`. In simple APIs, most view classes will extend `GenericModelView`, and will declare methods that immediately call the methods here. :: class WidgetViewBase(GenericModelView): model = models.Widget schema = models.WidgetSchema() class WidgetListView(WidgetViewBase): def get(self): return self.list() def post(self): return self.create() class WidgetView(WidgetViewBase): def get(self, id): return self.retrieve(id) def patch(self, id): return self.update(id, partial=True) def delete(self, id): return self.destroy(id) To extend or otherwise customize the behavior of the methods here, override the methods in `MethodView`. ''' def list(self): '''Return a list of items. This is the standard GET handler on a list view. :return: An HTTP 200 response. :rtype: :py:class:`flask.Response` ''' pass def retrieve(self, id, *, create_transient_stub=False): '''Retrieve an item by ID. This is the standard ``GET`` handler on a detail view. :param id: The item ID. :param bool create_transient_stub: If set, create and retrieve a transient stub for the item if it is not found. This will not save the stub to the database. :return: An HTTP 200 response. :rtype: :py:class:`flask.Response` ''' pass def create(self, *, allow_client_id=False): '''Create a new item using the request data. This is the standard ``POST`` handler on a list view. :param bool allow_client_id: If set, allow the client to specify ID fields for the item. :return: An HTTP 201 response. :rtype: :py:class:`flask.Response` ''' pass def update( self, id, *, with_for_update=False, partial=False, ): '''Update the item for the specified ID with the request data. This is the standard ``PUT`` handler on a detail view if `partial` is not set, or the standard ``PATCH`` handler if `partial` is set. :param id: The item ID. :param bool with_for_update: If set, lock the item row while updating using ``FOR UPDATE``. :param bool partial: If set, perform a partial update for the item, ignoring fields marked ``required`` on `deserializer`. :return: An HTTP 200 response. :rtype: :py:class:`flask.Response` ''' pass def upsert(self, id, *, with_for_update=False): '''Upsert the item for the specified ID with the request data. This will update the item for the given ID, if that item exists. Otherwise, this will create a new item with the request data. :param id: The item ID. :param bool with_for_update: If set, lock the item row while updating using ``FOR UPDATE``. :return: An HTTP 200 or 201 response. :rtype: :py:class:`flask.Response` ''' pass def destroy(self, id): '''Delete the item for the specified ID. :param id: The item ID. :return: An HTTP 204 response. :rtype: :py:class:`flask.Response` ''' pass
7
7
18
3
7
8
1
1.71
1
0
0
15
6
0
6
61
147
36
41
23
28
70
29
17
22
2
3
0
8
965
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/authentication.py
flask_resty.authentication.NoOpAuthentication
class NoOpAuthentication: """An authentication component that provides no credentials.""" def authenticate_request(self): pass
class NoOpAuthentication: '''An authentication component that provides no credentials.''' def authenticate_request(self): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
0
1
1
5
1
3
2
1
1
3
2
1
1
0
0
1
966
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/authorization.py
flask_resty.authorization.HasAnyCredentialsAuthorization
class HasAnyCredentialsAuthorization( HasCredentialsAuthorizationBase, NoOpAuthorization ): """An authorization component that allows any action when authenticated. This doesn't check the credentials; it just checks that some valid credentials were provided. """ pass
class HasAnyCredentialsAuthorization( HasCredentialsAuthorizationBase, NoOpAuthorization ): '''An authorization component that allows any action when authenticated. This doesn't check the credentials; it just checks that some valid credentials were provided. ''' pass
1
1
0
0
0
0
0
1
2
0
0
2
0
0
0
14
10
2
4
3
1
4
2
1
1
0
2
0
0
967
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/authorization.py
flask_resty.authorization.HasCredentialsAuthorizationBase
class HasCredentialsAuthorizationBase(AuthorizationBase): """A base authorization component that requires some authentication. This authorization component doesn't check the credentials, but will block all requests that do not provide some credentials. """ def authorize_request(self): if self.get_request_credentials() is None: raise ApiError(401, {"code": "invalid_credentials.missing"})
class HasCredentialsAuthorizationBase(AuthorizationBase): '''A base authorization component that requires some authentication. This authorization component doesn't check the credentials, but will block all requests that do not provide some credentials. ''' def authorize_request(self): pass
2
1
3
0
3
0
2
1
1
1
1
2
1
0
1
8
10
2
4
2
2
4
4
2
2
2
1
1
2
968
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/authorization.py
flask_resty.authorization.NoOpAuthorization
class NoOpAuthorization(AuthorizationBase): """An authorization component that allows any action.""" def authorize_request(self): pass def filter_query(self, query, view): return query def authorize_save_item(self, item): pass def authorize_create_item(self, item): pass def authorize_update_item(self, item, data): pass def authorize_delete_item(self, item): pass
class NoOpAuthorization(AuthorizationBase): '''An authorization component that allows any action.''' def authorize_request(self): pass def filter_query(self, query, view): pass def authorize_save_item(self, item): pass def authorize_create_item(self, item): pass def authorize_update_item(self, item, data): pass def authorize_delete_item(self, item): pass
7
1
2
0
2
0
1
0.08
1
0
0
1
6
0
6
13
20
6
13
7
6
1
13
7
6
1
1
0
6
969
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/exceptions.py
flask_resty.exceptions.ApiError
class ApiError(Exception): """An API exception. When raised, Flask-RESTy will send an HTTP response with the provided `status_code` and the provided `errors` under the ``errors`` property as JSON. If :py:attr:`flask.Flask.debug` or :py:attr:`flask.Flask.testing` is True, the body will also contain the full traceback under the ``debug`` property. :param int status_code: The HTTP status code for the error response. :param dict errors: A list of dict with error data. """ def __init__(self, status_code, *errors): self.status_code = status_code self.body = {"errors": errors or self.get_default_errors(status_code)} if flask.current_app.debug or flask.current_app.testing: self.body["debug"] = traceback.format_exc() @classmethod def from_http_exception(cls, exc): return cls(exc.code, cls.get_error_from_http_exception(exc)) @classmethod def get_default_errors(cls, status_code): if status_code not in default_exceptions: return () exc = default_exceptions[status_code]() return (cls.get_error_from_http_exception(exc),) @classmethod def get_error_from_http_exception(cls, exc): return { "code": "_".join(word.lower() for word in exc.name.split()), "detail": exc.description, } @classmethod def from_validation_error( cls, status_code, error, format_validation_error ): return cls( status_code, *( format_validation_error(message, path) for message, path in iter_validation_errors(error.messages) ), ) def update(self, additional): """Add additional metadata to the error. Can be chained with further updates. :param dict additional: The additional metadata :return: The :py:class:`ApiError` that :py:meth:`update` was called on :rtype: :py:class:`ApiError` """ for error in self.body["errors"]: error.update(additional) # Allow e.g. `raise e.update(additional)`. return self @property def response(self): if flask.current_app.config.get("RESTY_TRAP_API_ERRORS"): raise self return flask.jsonify(self.body), self.status_code
class ApiError(Exception): '''An API exception. When raised, Flask-RESTy will send an HTTP response with the provided `status_code` and the provided `errors` under the ``errors`` property as JSON. If :py:attr:`flask.Flask.debug` or :py:attr:`flask.Flask.testing` is True, the body will also contain the full traceback under the ``debug`` property. :param int status_code: The HTTP status code for the error response. :param dict errors: A list of dict with error data. ''' def __init__(self, status_code, *errors): pass @classmethod def from_http_exception(cls, exc): pass @classmethod def get_default_errors(cls, status_code): pass @classmethod def get_error_from_http_exception(cls, exc): pass @classmethod def from_validation_error( cls, status_code, error, format_validation_error ): pass def update(self, additional): '''Add additional metadata to the error. Can be chained with further updates. :param dict additional: The additional metadata :return: The :py:class:`ApiError` that :py:meth:`update` was called on :rtype: :py:class:`ApiError` ''' pass @property def response(self): pass
13
2
7
1
5
1
2
0.39
1
0
0
0
3
2
7
17
73
16
41
19
26
16
25
12
17
2
3
1
11
970
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/fields.py
flask_resty.fields.DelimitedList
class DelimitedList(fields.List): """List represented as a comma-delimited string, for use with args_schema. Same as `marshmallow.fields.List`, except can load from either a list or a delimited string (e.g. "foo,bar,baz"). Directly taken from webargs: https://github.com/marshmallow-code/webargs/blob/de061e037285fd08a42d73be95bc779f2a4e3c47/src/webargs/fields.py#L47 :param Field cls_or_instance: A field class or instance. :param str delimiter: Delimiter between values. :param bool as_string: Dump values to string. """ delimiter = "," def __init__( self, cls_or_instance, delimiter=None, as_string=False, **kwargs ): super().__init__(cls_or_instance, **kwargs) self.delimiter = delimiter or self.delimiter self.as_string = as_string def _serialize(self, value, attr, obj): ret = super()._serialize(value, attr, obj) if self.as_string: return self.delimiter.join(format(each) for each in ret) return ret def _deserialize(self, value, attr, data, **kwargs): try: ret = ( value if marshmallow.utils.is_iterable_but_not_string(value) else value.split(self.delimiter) ) except AttributeError as error: raise self.make_error("invalid") from error return super()._deserialize(ret, attr, data, **kwargs)
class DelimitedList(fields.List): '''List represented as a comma-delimited string, for use with args_schema. Same as `marshmallow.fields.List`, except can load from either a list or a delimited string (e.g. "foo,bar,baz"). Directly taken from webargs: https://github.com/marshmallow-code/webargs/blob/de061e037285fd08a42d73be95bc779f2a4e3c47/src/webargs/fields.py#L47 :param Field cls_or_instance: A field class or instance. :param str delimiter: Delimiter between values. :param bool as_string: Dump values to string. ''' def __init__( self, cls_or_instance, delimiter=None, as_string=False, **kwargs ): pass def _serialize(self, value, attr, obj): pass def _deserialize(self, value, attr, data, **kwargs): pass
4
1
8
1
7
0
2
0.35
1
2
0
0
3
1
3
3
40
9
23
11
17
8
17
8
13
3
1
1
6
971
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/fields.py
flask_resty.fields.RelatedItem
class RelatedItem(fields.Nested): """A nested object field that only requires the ID on load. This class is a wrapper around :py:class:`marshmallow.fields.Nested` that provides simplified semantics in the context of a normalized REST API. When dumping, this field will dump the nested object as normal. When loading, this field will do a partial load to retrieve just the ID. This is because, when interacting with a resource that has a relationship to existing instances of another resource, the ID is sufficient to uniquely identify instances of the other resource. """ def _deserialize(self, value, *args, **kwargs): if self.many and not marshmallow.utils.is_collection(value): raise self.make_error( "type", input=value, type=value.__class__.__name__ ) # Do partial load of related item, as we only need the id. return self.schema.load(value, partial=True) def _validate_missing(self, value): # Do not display detailed error data on required fields in nested # schema - in this context, they're actually not required. super(fields.Nested, self)._validate_missing(value)
class RelatedItem(fields.Nested): '''A nested object field that only requires the ID on load. This class is a wrapper around :py:class:`marshmallow.fields.Nested` that provides simplified semantics in the context of a normalized REST API. When dumping, this field will dump the nested object as normal. When loading, this field will do a partial load to retrieve just the ID. This is because, when interacting with a resource that has a relationship to existing instances of another resource, the ID is sufficient to uniquely identify instances of the other resource. ''' def _deserialize(self, value, *args, **kwargs): pass def _validate_missing(self, value): pass
3
1
6
1
4
2
2
1.33
1
1
0
0
2
0
2
2
26
5
9
3
6
12
7
3
4
2
1
1
3
972
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/filtering.py
flask_resty.filtering.ColumnFilter
class ColumnFilter(FieldFilterBase): """A filter that operates on the value of a database column. This filter relies on the schema to deserialize the query argument values. `ColumnFilter` cannot normally be used for columns that do not appear on the schema, but such columns can be added to the schema with fields that have both `load_only` and `dump_only` set. :param str column_name: The name of the column to filter against. :param func operator: A callable that returns the filter expression given the column and the filter value. :param bool required: If set, fail if this filter is not specified. :param bool validate: If unset, bypass validation on the field. This is useful if the field specifies validation rule for inputs that are not relevant for filters. """ def __init__( self, column_name=None, operator=None, *, required=False, missing=marshmallow.missing, validate=True, **kwargs, ): super().__init__(**kwargs) if operator is None and callable(column_name): operator = column_name column_name = None if not operator: raise TypeError("must specify operator") self._has_explicit_column_name = column_name is not None self._column_name = column_name self._operator = operator self._fields = {} self._required = required self._missing = missing self._validate = validate def maybe_set_arg_name(self, arg_name): """Set `arg_name` as the column name if no explicit value is available. :param str arg_name: The name of the column to filter against. """ if self._has_explicit_column_name: return if self._column_name and self._column_name != arg_name: raise TypeError( "cannot use ColumnFilter without explicit column name for multiple arg names" ) self._column_name = arg_name def get_field(self, view): """Construct the marshmallow field for deserializing filter values. This takes the field from the deserializer, then creates a copy with the desired semantics around missing values. :param view: The view with the model we wish to filter for. :type view: :py:class:`ModelView` """ base_field = view.deserializer.fields[self._column_name] try: field = self._fields[base_field] except KeyError: # We don't want the default value handling on the original field, # as that's only relevant for object deserialization. field = copy.deepcopy(base_field) field.required = self._required if _USE_LOAD_DEFAULT: field.load_default = self._missing else: field.missing = self._missing self._fields[base_field] = field return field def get_filter_clause(self, view, value): column = getattr(view.model, self._column_name) return self._operator(column, value) def deserialize(self, field, value_raw): """Deserialize `value_raw`, optionally skipping validation. :param field: The marshmallow field. :type field: :py:class:`marshmallow.fields.Field` :param value_raw: The value to deserialize. :return: The deserialized value. """ if not self._validate: # We may not want to apply the same validation for filters as we do # on model fields. This bypasses the irrelevant handling of # missing and None values, and skips the validation check. return field._deserialize(value_raw, None, None) return super().deserialize(field, value_raw)
class ColumnFilter(FieldFilterBase): '''A filter that operates on the value of a database column. This filter relies on the schema to deserialize the query argument values. `ColumnFilter` cannot normally be used for columns that do not appear on the schema, but such columns can be added to the schema with fields that have both `load_only` and `dump_only` set. :param str column_name: The name of the column to filter against. :param func operator: A callable that returns the filter expression given the column and the filter value. :param bool required: If set, fail if this filter is not specified. :param bool validate: If unset, bypass validation on the field. This is useful if the field specifies validation rule for inputs that are not relevant for filters. ''' def __init__( self, column_name=None, operator=None, *, required=False, missing=marshmallow.missing, validate=True, **kwargs, ): pass def maybe_set_arg_name(self, arg_name): '''Set `arg_name` as the column name if no explicit value is available. :param str arg_name: The name of the column to filter against. ''' pass def get_field(self, view): '''Construct the marshmallow field for deserializing filter values. This takes the field from the deserializer, then creates a copy with the desired semantics around missing values. :param view: The view with the model we wish to filter for. :type view: :py:class:`ModelView` ''' pass def get_filter_clause(self, view, value): pass def deserialize(self, field, value_raw): '''Deserialize `value_raw`, optionally skipping validation. :param field: The marshmallow field. :type field: :py:class:`marshmallow.fields.Field` :param value_raw: The value to deserialize. :return: The deserialized value. ''' pass
6
4
17
3
10
4
2
0.63
1
3
0
0
5
7
5
17
108
23
52
25
37
33
40
16
34
3
2
2
12
973
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/filtering.py
flask_resty.filtering.Filtering
class Filtering: """Container for the arg filters on a :py:class:`ModelView`. :param dict kwargs: A mapping from filter field names to filters. """ def __init__(self, **kwargs): self._arg_filters = { arg_name: self.make_arg_filter(arg_name, arg_filter) for arg_name, arg_filter in kwargs.items() } def make_arg_filter(self, arg_name, arg_filter): if callable(arg_filter): arg_filter = ColumnFilter(arg_name, arg_filter) arg_filter.maybe_set_arg_name(arg_name) return arg_filter def filter_query(self, query, view): """Filter a query using the configured filters and the request args. :param query: The query to filter. :type query: :py:class:`sqlalchemy.orm.query.Query` :param view: The view with the model we wish to filter for. :type view: :py:class:`ModelView` :return: The filtered query :rtype: :py:class:`sqlalchemy.orm.query.Query` """ args = flask.request.args for arg_name, arg_filter in self._arg_filters.items(): try: arg_value = args[arg_name] except KeyError: arg_value = None try: query = arg_filter.filter_query(query, view, arg_value) except ApiError as e: raise e.update({"source": {"parameter": arg_name}}) return query def __or__(self, other): """Combine two `Filtering` instances. `Filtering` supports view inheritance by implementing the `|` operator. For example, `Filtering(foo=..., bar=...) | Filtering(baz=...)` will create a new `Filtering` instance with filters for each `foo`, `bar` and `baz`. Filters on the right-hand side take precedence where each `Filtering` instance has the same key. """ if not isinstance(other, Filtering): return NotImplemented return self.__class__(**{**self._arg_filters, **other._arg_filters})
class Filtering: '''Container for the arg filters on a :py:class:`ModelView`. :param dict kwargs: A mapping from filter field names to filters. ''' def __init__(self, **kwargs): pass def make_arg_filter(self, arg_name, arg_filter): pass def filter_query(self, query, view): '''Filter a query using the configured filters and the request args. :param query: The query to filter. :type query: :py:class:`sqlalchemy.orm.query.Query` :param view: The view with the model we wish to filter for. :type view: :py:class:`ModelView` :return: The filtered query :rtype: :py:class:`sqlalchemy.orm.query.Query` ''' pass def __or__(self, other): '''Combine two `Filtering` instances. `Filtering` supports view inheritance by implementing the `|` operator. For example, `Filtering(foo=..., bar=...) | Filtering(baz=...)` will create a new `Filtering` instance with filters for each `foo`, `bar` and `baz`. Filters on the right-hand side take precedence where each `Filtering` instance has the same key. ''' pass
5
3
12
2
7
4
2
0.67
0
3
2
0
4
1
4
4
58
13
27
10
22
18
24
9
19
4
0
2
9
974
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/filtering.py
flask_resty.filtering.ModelFilter
class ModelFilter(FieldFilterBase): """An arbitrary filter against the model. :param field: A marshmallow field for deserializing filter values. :type field: :py:class:`marshmallow.fields.Field` :param filter: A callable that returns the filter expression given the model and the filter value. :param dict kwargs: Passed to :py:class:`FieldFilterBase`. """ def __init__(self, field, filter, **kwargs): super().__init__(**kwargs) self._field = field self._filter = filter def get_field(self, view): return self._field def get_filter_clause(self, view, value): return self._filter(view.model, value)
class ModelFilter(FieldFilterBase): '''An arbitrary filter against the model. :param field: A marshmallow field for deserializing filter values. :type field: :py:class:`marshmallow.fields.Field` :param filter: A callable that returns the filter expression given the model and the filter value. :param dict kwargs: Passed to :py:class:`FieldFilterBase`. ''' def __init__(self, field, filter, **kwargs): pass def get_field(self, view): pass def get_filter_clause(self, view, value): pass
4
1
3
0
3
0
1
0.78
1
1
0
0
3
2
3
15
21
5
9
6
5
7
9
6
5
1
2
0
3
975
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/jwt.py
flask_resty.jwt.JwkSetAuthentication
class JwkSetAuthentication(JwtAuthentication): def __init__(self, jwk_set=None, **kwargs): super().__init__(**kwargs) self._jwk_set = jwk_set @property def _pyjwt(self): return JwkSetPyJwt(self.jwk_set) @property def jwk_set(self): return ( self._jwk_set or flask.current_app.config[self.get_config_key("jwk_set")] )
class JwkSetAuthentication(JwtAuthentication): def __init__(self, jwk_set=None, **kwargs): pass @property def _pyjwt(self): pass @property def jwk_set(self): pass
6
0
4
0
3
0
1
0
1
2
1
0
3
1
3
16
16
3
13
7
7
0
8
5
4
1
4
0
3
976
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/jwt.py
flask_resty.jwt.JwkSetPyJwt
class JwkSetPyJwt(PyJWT): def __init__(self, jwk_set, *args, **kwargs): super().__init__(*args, **kwargs) self.jwk_set = jwk_set def decode(self, jwt, **kwargs): unverified_header = jwt_lib.get_unverified_header(jwt) jwk = self.get_jwk_for_jwt(unverified_header) # It's safe to use alg from the header here, as we verify that against # the algorithm whitelist. alg = jwk["alg"] if "alg" in jwk else unverified_header["alg"] # jwt.decode will also check this, but this is more defensive. if alg not in kwargs["algorithms"]: raise InvalidAlgorithmError( "The specified alg value is not allowed" ) return super().decode( jwt, key=self.get_key_from_jwk(jwk, alg), **kwargs ) def get_jwk_for_jwt(self, unverified_header): try: token_kid = unverified_header["kid"] except KeyError as e: raise InvalidTokenError( "Key ID header parameter is missing" ) from e for jwk in self.jwk_set["keys"]: if jwk["kid"] == token_kid: return jwk raise InvalidTokenError("no key found") def get_key_from_jwk(self, jwk, alg): if "x5c" in jwk: return load_der_x509_certificate( base64.b64decode(jwk["x5c"][0]), default_backend() ).public_key() algorithm = PyJWS()._algorithms[alg] # Awkward: return algorithm.from_jwk(json.dumps(jwk))
class JwkSetPyJwt(PyJWT): def __init__(self, jwk_set, *args, **kwargs): pass def decode(self, jwt, **kwargs): pass def get_jwk_for_jwt(self, unverified_header): pass def get_key_from_jwk(self, jwk, alg): pass
5
0
11
2
8
1
3
0.12
1
2
0
0
4
1
4
4
49
12
33
13
28
4
25
12
20
4
1
2
10
977
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/jwt.py
flask_resty.jwt.JwtAuthentication
class JwtAuthentication(HeaderAuthentication): CONFIG_KEY_TEMPLATE = "RESTY_JWT_DECODE_{}" def __init__(self, **kwargs): super().__init__() self._decode_args = { key: kwargs[key] for key in JWT_DECODE_ARG_KEYS if key in kwargs } def get_credentials_from_token(self, token): try: payload = self.decode_token(token) except InvalidTokenError as e: raise ApiError(401, {"code": "invalid_token"}) from e return payload def decode_token(self, token): return self._pyjwt.decode(token, **self.get_jwt_decode_args()) @property def _pyjwt(self): return jwt_lib def get_jwt_decode_args(self): config = flask.current_app.config args = { key: config[self.get_config_key(key)] for key in JWT_DECODE_ARG_KEYS if self.get_config_key(key) in config } args.update(self._decode_args) return args def get_config_key(self, key): return self.CONFIG_KEY_TEMPLATE.format(key.upper())
class JwtAuthentication(HeaderAuthentication): def __init__(self, **kwargs): pass def get_credentials_from_token(self, token): pass def decode_token(self, token): pass @property def _pyjwt(self): pass def get_jwt_decode_args(self): pass def get_config_key(self, key): pass
8
0
5
1
4
0
1
0
1
2
1
1
6
1
6
13
38
9
29
14
21
0
22
12
15
2
3
1
7
978
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/pagination.py
flask_resty.pagination.CursorInfo
class CursorInfo: reversed: bool cursor: str | None cursor_arg: str | None limit: str | None limit_arg: str | None
class CursorInfo: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
8
2
6
1
5
0
6
1
5
0
0
0
0
979
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/pagination.py
flask_resty.pagination.CursorPaginationBase
class CursorPaginationBase(LimitPagination): """The base class for pagination schemes that use cursors. Unlike with offsets that identify items by relative position, cursors identify position by content. This allows continuous pagination without concerns about page shear on dynamic collections. This makes cursor-based pagination especially effective for lists with infinite scroll dynamics, as offset-based pagination can miss or duplicate items due to inserts or deletes. It's also more efficient against the database, as the cursor condition can be cheaply evaluated as a filter against an index. :param bool validate: If unset, bypass validation on cursor values. This is useful if the deserializer field imposes validation that will fail for on cursor values for items actually present. """ #: The name of the query parameter to inspect for the cursor value. cursor_arg = "cursor" limit_arg = "limit" #: the name of the query parameter to inspect for explicit forward pagination after_arg = "after" first_arg = "first" #: the name of the query parameter to inspect for explicit backward pagination before_arg = "before" last_arg = "last" def __init__(self, *args, validate_values=True, **kwargs): super().__init__(*args, **kwargs) self._validate_values = validate_values def try_get_arg(self, arg): value = flask.request.args.get(arg) if value is not None: return (value, arg) return (None, None) # There are a number of different cases that this covers in order to be backwards compatible with def get_cursor_info(self) -> CursorInfo: cursor = None cursor_arg = None limit = None limit_arg = None # Unambiguous cases where a cursor is provided. if self.after_arg in flask.request.args: reversed = False cursor, cursor_arg = self.try_get_arg(self.after_arg) limit, limit_arg = self.try_get_arg(self.first_arg) elif self.before_arg in flask.request.args: reversed = True cursor, cursor_arg = self.try_get_arg(self.before_arg) limit, limit_arg = self.try_get_arg(self.last_arg) # Ambiguous cases where limits are provided but not cursors # Relay sometimes sends both first and after, default to "first" # in keeping with the cursor precedence elif self.first_arg in flask.request.args: reversed = False limit, limit_arg = self.try_get_arg(self.first_arg) elif self.last_arg in flask.request.args: reversed = True limit, limit_arg = self.try_get_arg(self.last_arg) # legacy "cursor_arg" config cases always map to after/first else: reversed = False cursor, cursor_arg = self.try_get_arg(self.cursor_arg) limit, limit_arg = self.try_get_arg(self.limit_arg) return CursorInfo(reversed, cursor, cursor_arg, limit, limit_arg) def get_limit(self): cursor_info = self.get_cursor_info() try: return self.parse_limit(cursor_info.limit) except ApiError as e: raise e.update({"source": {"parameter": cursor_info.limit_arg}}) @property def reversed(self): return self.get_cursor_info().reversed def adjust_sort_ordering( self, view: ModelView, field_orderings ) -> FieldOrderings: """Ensure the query is sorted correctly and get the field orderings. The implementation of cursor-based pagination in Flask-RESTy requires that the query be sorted in a fully deterministic manner. The timestamp columns usually used in sorting do not quite qualify, as two different rows can have the same timestamp. This method adds the ID fields to the sorting criterion, then returns the field orderings for use in the other methods, as in `get_field_orderings` below. :param view: The view with the model we wish to paginate. :type view: :py:class:`ModelView` :return: The field orderings necessary to do cursor pagination deterministically :rtype: FieldOrderings """ # ignore the passed in sort so that it's consistent # with further calls in get_page return self.get_field_orderings(view) def get_field_orderings(self, view: ModelView): sorting: FieldSortingBase = view.sorting assert ( sorting is not None ), "sorting must be defined when using cursor pagination" sorting_field_orderings = sorting.get_request_field_orderings(view) sorting_ordering_fields = frozenset( field_name for field_name, _ in sorting_field_orderings ) sorting_ordering_fields = frozenset( field_name for field_name, _ in sorting_field_orderings ) # For convenience, use the ascending setting on the last explicit # ordering when possible, such that reversing the sort will reverse # the IDs as well. if sorting_field_orderings: last_field_asc = sorting_field_orderings[-1][1] else: last_field_asc = True missing_field_orderings = tuple( (id_field, last_field_asc) for id_field in view.id_fields if id_field not in sorting_ordering_fields ) field_ordering = sorting_field_orderings + missing_field_orderings if self.reversed: field_ordering = tuple( (field, not order) for field, order in field_ordering ) return field_ordering def get_request_cursor(self, view, field_orderings): """Get the cursor value specified in the request. Given the view and the field_orderings as above, this method will read the encoded cursor from the query, then return the cursor as a tuple of the field values in the cursor. This parsed cursor can then be used in `get_filter`. :param view: The view with the model we wish to paginate. :type view: :py:class:`ModelView` :param field_orderings: A sequence of field_ordering tuples :type field_orderings: seq :return: A cursor value :rtype: str :raises: :py:class:`ApiError` if an invalid cursor is provided in `cursor_arg`. """ cursor_info = self.get_cursor_info() if cursor_info.cursor is None: return None try: return self.parse_cursor(view, cursor_info.cursor, field_orderings) except ApiError as e: raise e.update({"source": {"parameter": cursor_info.cursor_arg}}) def parse_cursor( self, view: ModelView, cursor: str, field_orderings: FieldOrderings, ) -> Cursor: cursor = self.decode_cursor(cursor) if len(cursor) != len(field_orderings): raise ApiError(400, {"code": "invalid_cursor.length"}) deserializer = view.deserializer column_fields = ( deserializer.fields[field_name] for field_name, _ in field_orderings ) try: cursor = tuple( self.deserialize_value(field, value) for field, value in zip(column_fields, cursor) ) except ValidationError as e: raise ApiError.from_validation_error( 400, e, self.format_validation_error ) from e return cursor def decode_cursor(self, cursor: str) -> tuple[str, ...]: try: cursor = cursor.split(".") cursor = tuple(self.decode_value(value) for value in cursor) except (TypeError, ValueError) as e: raise ApiError(400, {"code": "invalid_cursor.encoding"}) from e return cursor def decode_value(self, value: str): value = value.encode("ascii") value += (3 - ((len(value) + 3) % 4)) * b"=" # Add back padding. value = base64.urlsafe_b64decode(value).decode() return None if value == _NULL else value def deserialize_value(self, field, value): if value is None: return None return ( field.deserialize(value) if self._validate_values # Cursors don't need to be fully valid values; they just need to be # the correct type for sorting, so it can make sense to bypass # validation. else field._deserialize(value, None, None) ) def format_validation_error(self, message, path): return {"code": "invalid_cursor", "detail": message} def get_filter( self, view, field_orderings: FieldOrderings, cursor: Cursor ): """Build the filter clause corresponding to a cursor. Given the field orderings and the cursor as above, this will construct a filter clause that can be used to filter a query to return only items after the specified cursor, per the specified field orderings. Use this to apply the equivalent of the offset specified by the cursor. :param view: The view with the model we wish to paginate. :type view: :py:class:`ModelView` :param field_orderings: A sequence of field_ordering tuples derived from the view's Sorting with explicit id ordering :type field_orderings: seq :param cursor: A set of values corresponding to the fields in `field_orderings` :type cursor: seq :return: A filter clause """ sorting: FieldSortingBase = view.sorting column_cursors = tuple( (sorting.get_column(view, field_name), asc, value) for (field_name, asc), value in zip(field_orderings, cursor) ) return sa.or_( self.get_filter_clause(column_cursors[: i + 1]) for i in range(len(column_cursors)) ) @staticmethod def get_previous_clause(column_cursors): if not column_cursors: return None clauses = [ column.isnot_distinct_from(value) for column, _, value in column_cursors ] return sa.and_(*clauses) @staticmethod def _handle_nullable(column, value, is_nullable): if is_nullable: return sa.or_(column.is_(None), (column > value)) else: return column > value def _prepare_current_clause(self, column, asc, value): is_nullable = getattr(column.expression, "nullable", True) # SQL Alchemy won't let you > or < a boolean, so we convert # to an integer, the DB's seem to handle this just fine if isinstance(value, bool): column = sa.cast(column, sa.Integer) value = int(value) if asc: if value is None: return None elif value is not None: current_clause = self._handle_nullable( column, value, is_nullable ) else: current_clause = column > value else: if value is None: current_clause = column.isnot(None) else: current_clause = column < value return current_clause def get_filter_clause(self, column_cursors): previous_clauses = self.get_previous_clause(column_cursors[:-1]) column, asc, value = column_cursors[-1] current_clause = self._prepare_current_clause(column, asc, value) if previous_clauses is None: return current_clause return sa.and_(previous_clauses, current_clause) def make_cursors(self, items, view, field_orderings): """Build a cursor for each of many items. This method creates a cursor for each item in `items`. It produces the same cursors as :py:meth:`make_cursor`, but is slightly more efficient in cases where cursors for multiple items are required. :param seq items: A sequence of instances of :py:attr:`ApiView.model` :param view: The view we wish to paginate. :type view: :py:class:`ModelView` :param seq field_orderings: A sequence of (field, asc?). :return: A sequence of :py:class:`marshmallow.Field`. :rtype: seq """ column_fields = self.get_column_fields(view, field_orderings) return tuple(self.render_cursor(item, column_fields) for item in items) def make_cursor(self, item, view, field_orderings): """Build a cursor for a given item. Given an item and the field orderings as above, this builds a cursor for the item. This cursor encodes the value for each field on the item per the specified field orderings. This cursor should be returned in page or item metadata to allow pagination continuing after the cursor for the item. :param obj item: An instance :py:attr:`ApiView.model` :param view: The view we wish to paginate. :type view: :py:class:`ModelView` :param seq field_orderings: A sequence of (field, asc?). :return: A sequence of :py:class:`marshmallow.Field`. :rtype: seq """ column_fields = self.get_column_fields(view, field_orderings) return self.render_cursor(item, column_fields) def get_column_fields(self, view, field_orderings): serializer = view.serializer return tuple( serializer.fields[field_name] for field_name, _ in field_orderings ) def render_cursor(self, item, column_fields): cursor = tuple( field._serialize(getattr(item, field.name), field.name, item) for field in column_fields ) return self.encode_cursor(cursor) def encode_cursor(self, cursor): return ".".join(self.encode_value(value) for value in cursor) def encode_value(self, value): if value is None: value = _NULL value = str(value) value = value.encode() value = base64.urlsafe_b64encode(value) value = value.rstrip(b"=") # Strip padding. return value.decode("ascii")
class CursorPaginationBase(LimitPagination): '''The base class for pagination schemes that use cursors. Unlike with offsets that identify items by relative position, cursors identify position by content. This allows continuous pagination without concerns about page shear on dynamic collections. This makes cursor-based pagination especially effective for lists with infinite scroll dynamics, as offset-based pagination can miss or duplicate items due to inserts or deletes. It's also more efficient against the database, as the cursor condition can be cheaply evaluated as a filter against an index. :param bool validate: If unset, bypass validation on cursor values. This is useful if the deserializer field imposes validation that will fail for on cursor values for items actually present. ''' def __init__(self, *args, validate_values=True, **kwargs): pass def try_get_arg(self, arg): pass def get_cursor_info(self) -> CursorInfo: pass def get_limit(self): pass @property def reversed(self): pass def adjust_sort_ordering( self, view: ModelView, field_orderings ) -> FieldOrderings: '''Ensure the query is sorted correctly and get the field orderings. The implementation of cursor-based pagination in Flask-RESTy requires that the query be sorted in a fully deterministic manner. The timestamp columns usually used in sorting do not quite qualify, as two different rows can have the same timestamp. This method adds the ID fields to the sorting criterion, then returns the field orderings for use in the other methods, as in `get_field_orderings` below. :param view: The view with the model we wish to paginate. :type view: :py:class:`ModelView` :return: The field orderings necessary to do cursor pagination deterministically :rtype: FieldOrderings ''' pass def get_field_orderings(self, view: ModelView): pass def get_request_cursor(self, view, field_orderings): '''Get the cursor value specified in the request. Given the view and the field_orderings as above, this method will read the encoded cursor from the query, then return the cursor as a tuple of the field values in the cursor. This parsed cursor can then be used in `get_filter`. :param view: The view with the model we wish to paginate. :type view: :py:class:`ModelView` :param field_orderings: A sequence of field_ordering tuples :type field_orderings: seq :return: A cursor value :rtype: str :raises: :py:class:`ApiError` if an invalid cursor is provided in `cursor_arg`. ''' pass def parse_cursor( self, view: ModelView, cursor: str, field_orderings: FieldOrderings, ) -> Cursor: pass def decode_cursor(self, cursor: str) -> tuple[str, ...]: pass def decode_value(self, value: str): pass def deserialize_value(self, field, value): pass def format_validation_error(self, message, path): pass def get_filter( self, view, field_orderings: FieldOrderings, cursor: Cursor ): '''Build the filter clause corresponding to a cursor. Given the field orderings and the cursor as above, this will construct a filter clause that can be used to filter a query to return only items after the specified cursor, per the specified field orderings. Use this to apply the equivalent of the offset specified by the cursor. :param view: The view with the model we wish to paginate. :type view: :py:class:`ModelView` :param field_orderings: A sequence of field_ordering tuples derived from the view's Sorting with explicit id ordering :type field_orderings: seq :param cursor: A set of values corresponding to the fields in `field_orderings` :type cursor: seq :return: A filter clause ''' pass @staticmethod def get_previous_clause(column_cursors): pass @staticmethod def _handle_nullable(column, value, is_nullable): pass def _prepare_current_clause(self, column, asc, value): pass def get_filter_clause(self, column_cursors): pass def make_cursors(self, items, view, field_orderings): '''Build a cursor for each of many items. This method creates a cursor for each item in `items`. It produces the same cursors as :py:meth:`make_cursor`, but is slightly more efficient in cases where cursors for multiple items are required. :param seq items: A sequence of instances of :py:attr:`ApiView.model` :param view: The view we wish to paginate. :type view: :py:class:`ModelView` :param seq field_orderings: A sequence of (field, asc?). :return: A sequence of :py:class:`marshmallow.Field`. :rtype: seq ''' pass def make_cursors(self, items, view, field_orderings): '''Build a cursor for a given item. Given an item and the field orderings as above, this builds a cursor for the item. This cursor encodes the value for each field on the item per the specified field orderings. This cursor should be returned in page or item metadata to allow pagination continuing after the cursor for the item. :param obj item: An instance :py:attr:`ApiView.model` :param view: The view we wish to paginate. :type view: :py:class:`ModelView` :param seq field_orderings: A sequence of (field, asc?). :return: A sequence of :py:class:`marshmallow.Field`. :rtype: seq ''' pass def get_column_fields(self, view, field_orderings): pass def render_cursor(self, item, column_fields): pass def encode_cursor(self, cursor): pass def encode_value(self, value): pass
28
6
14
2
9
3
2
0.46
1
14
4
1
22
1
24
32
386
76
214
80
177
98
152
60
127
6
3
2
49
980
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/pagination.py
flask_resty.pagination.LimitOffsetPagination
class LimitOffsetPagination(LimitPagination): """A pagination scheme that takes a user-specified limit and offset. This pagination scheme takes a user-specified limit and offset. It will retrieve up to the specified number of items, beginning at the specified offset. """ #: The name of the query parameter to inspect for the OFFSET value. offset_arg = "offset" def get_page(self, query, view): offset = self.get_offset() query = query.offset(offset) return super().get_page(query, view) def get_offset(self): offset = flask.request.args.get(self.offset_arg) try: return self.parse_offset(offset) except ApiError as e: raise e.update({"source": {"parameter": self.offset_arg}}) def parse_offset(self, offset): if offset is None: return 0 try: offset = int(offset) except ValueError as e: raise ApiError(400, {"code": "invalid_offset"}) from e if offset < 0: raise ApiError(400, {"code": "invalid_offset"}) return offset
class LimitOffsetPagination(LimitPagination): '''A pagination scheme that takes a user-specified limit and offset. This pagination scheme takes a user-specified limit and offset. It will retrieve up to the specified number of items, beginning at the specified offset. ''' def get_page(self, query, view): pass def get_offset(self): pass def parse_offset(self, offset): pass
4
1
7
1
7
0
2
0.27
1
4
1
1
3
0
3
11
35
7
22
9
18
6
22
7
18
4
3
1
7
981
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/pagination.py
flask_resty.pagination.LimitPagination
class LimitPagination(LimitPaginationBase): """A pagination scheme that takes a user-specified limit. This is not especially useful and is included only for completeness. This pagination scheme uses the :py:attr:`limit_arg` query parameter to limit the number of items returned by the query. If no such limit is explicitly specified, this uses `default_limit`. If `max_limit` is specified, then the user-specified limit may not exceed `max_limit`. :param int default_limit: The default maximum number of items to retrieve, if the user does not specify an explicit value. :param int max_limit: The maximum number of items the user is allowed to request. """ #: The name of the query parameter to inspect for the LIMIT value. limit_arg = "limit" def __init__(self, default_limit=None, max_limit=None): self._default_limit = if_none(default_limit, max_limit) self._max_limit = max_limit if self._max_limit is not None: assert ( self._default_limit <= self._max_limit ), "default limit exceeds max limit" def get_limit(self): limit = flask.request.args.get(self.limit_arg) try: return self.parse_limit(limit) except ApiError as e: raise e.update({"source": {"parameter": self.limit_arg}}) def parse_limit(self, limit): if limit is None: return self._default_limit try: limit = int(limit) except ValueError as e: raise ApiError(400, {"code": "invalid_limit"}) from e if limit < 0: raise ApiError(400, {"code": "invalid_limit"}) if self._max_limit is not None: limit = min(limit, self._max_limit) return limit
class LimitPagination(LimitPaginationBase): '''A pagination scheme that takes a user-specified limit. This is not especially useful and is included only for completeness. This pagination scheme uses the :py:attr:`limit_arg` query parameter to limit the number of items returned by the query. If no such limit is explicitly specified, this uses `default_limit`. If `max_limit` is specified, then the user-specified limit may not exceed `max_limit`. :param int default_limit: The default maximum number of items to retrieve, if the user does not specify an explicit value. :param int max_limit: The maximum number of items the user is allowed to request. ''' def __init__(self, default_limit=None, max_limit=None): pass def get_limit(self): pass def parse_limit(self, limit): pass
4
1
10
1
8
0
3
0.48
1
3
1
2
3
2
3
8
52
12
27
10
23
13
25
8
21
5
2
1
9
982
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/pagination.py
flask_resty.pagination.MaxLimitPagination
class MaxLimitPagination(LimitPaginationBase): """Return up to a fixed maximum number of items. This is not especially useful and is included only for completeness. :param int max_limit: The maximum number of items to retrieve. """ def __init__(self, max_limit): self._max_limit = max_limit def get_limit(self): return self._max_limit
class MaxLimitPagination(LimitPaginationBase): '''Return up to a fixed maximum number of items. This is not especially useful and is included only for completeness. :param int max_limit: The maximum number of items to retrieve. ''' def __init__(self, max_limit): pass def get_limit(self): pass
3
1
2
0
2
0
1
0.8
1
0
0
0
2
1
2
7
13
4
5
4
2
4
5
4
2
1
2
0
2
983
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/pagination.py
flask_resty.pagination.PagePagination
class PagePagination(LimitOffsetPagination): """A pagination scheme that fetches a particular fixed-size page. This works similar to `LimitOffsetPagination`. The limit used will always be the fixed page size. The offset will be page * page_size. :param int page_size: The fixed number of items per page. """ #: The name of the query parameter to inspect for the page value. page_arg = "page" def __init__(self, page_size): super().__init__() self._page_size = page_size def get_offset(self): return self.get_request_page() * self._page_size def get_request_page(self): page = flask.request.args.get(self.page_arg) try: return self.parse_page(page) except ApiError as e: raise e.update({"source": {"parameter": self.page_arg}}) def parse_page(self, page): if page is None: return 0 try: page = int(page) except ValueError as e: raise ApiError(400, {"code": "invalid_page"}) from e if page < 0: raise ApiError(400, {"code": "invalid_page"}) return page def get_limit(self): return self._page_size
class PagePagination(LimitOffsetPagination): '''A pagination scheme that fetches a particular fixed-size page. This works similar to `LimitOffsetPagination`. The limit used will always be the fixed page size. The offset will be page * page_size. :param int page_size: The fixed number of items per page. ''' def __init__(self, page_size): pass def get_offset(self): pass def get_request_page(self): pass def parse_page(self, page): pass def get_limit(self): pass
6
1
5
0
5
0
2
0.24
1
4
1
0
5
1
5
16
41
10
25
11
19
6
25
9
19
4
4
1
9
984
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/pagination.py
flask_resty.pagination.RelayCursorPagination
class RelayCursorPagination(CursorPaginationBase): """A pagination scheme that works with the Relay specification. This pagination scheme assigns a cursor to each retrieved item. The page metadata will contain an array of cursors, one per item. The item metadata will include the cursor for the fetched item. For Relay Cursor Connections Specification, see https://facebook.github.io/relay/graphql/connections.htm. """ def __init__( self, *args, page_info_arg=None, default_include_page_info=False, **kwargs, ): super().__init__(*args, **kwargs) self._default_include_page_info = default_include_page_info self.page_info_arg = page_info_arg def get_page_info(self, query, view, field_orderings, cursor, items): include_page_info = ( self.deserialize_value( fields.Boolean(), flask.request.args.get( self.page_info_arg, self._default_include_page_info ), ) if self.page_info_arg else self._default_include_page_info ) if not include_page_info: return {} total = query.count() index = 0 if cursor: filter_clause = self.get_filter( view, tuple((field, not order) for field, order in field_orderings), cursor, ) index = query.filter(filter_clause).count() + 1 # in the reversed case, both the `order by` and sort are inverted. # so in practice this gives us a reverse index, e.g. distance from # the end of the list. We normalize it back by subtracting from the total if self.reversed: before_index = total - index index = max(before_index - len(items), 0) return {"index": index, "total": total} def get_page(self, query, view): field_orderings = self.get_field_orderings(view) cursor_in = self.get_request_cursor(view, field_orderings) page_query = query if cursor_in is not None: page_query = page_query.filter( self.get_filter(view, field_orderings, cursor_in) ) items = super().get_page(page_query, view) if self.reversed: items.reverse() # Relay expects a cursor for each item. cursors_out = self.make_cursors(items, view, field_orderings) page_info = self.get_page_info( query, view, field_orderings, cursor_in, items ) meta.update_response_meta({"cursors": cursors_out, **page_info}) return items def get_item_meta(self, item, view): cursor = self.make_cursor(item, view, self.get_field_orderings(view)) return {"cursor": cursor}
class RelayCursorPagination(CursorPaginationBase): '''A pagination scheme that works with the Relay specification. This pagination scheme assigns a cursor to each retrieved item. The page metadata will contain an array of cursors, one per item. The item metadata will include the cursor for the fetched item. For Relay Cursor Connections Specification, see https://facebook.github.io/relay/graphql/connections.htm. ''' def __init__( self, *args, page_info_arg=None, default_include_page_info=False, **kwargs, ): pass def get_page_info(self, query, view, field_orderings, cursor, items): pass def get_page_info(self, query, view, field_orderings, cursor, items): pass def get_item_meta(self, item, view): pass
5
1
19
4
14
1
3
0.19
1
2
0
0
4
2
4
36
88
20
57
25
46
11
34
19
29
5
4
1
10
985
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/related.py
flask_resty.related.Related
class Related: """A component for resolving deserialized data fields to model instances. The `Related` component is responsible for resolving related model instances by ID and for constructing nested model instances. It supports multiple related types of functionality. For a view with:: related = Related( foo=RelatedId(FooView, "foo_id"), bar=BarView, baz=Related(models.Baz, qux=RelatedId(QuxView, "qux_id"), ) Given deserialized input data like:: { "foo_id": "3", "bar": {"id": "4"}, "baz": {name: "Bob", "qux_id": "5"}, "other_field": "value", } This component will resolve these data into something like:: { "foo": <Foo(id=3)>, "bar": <Bar(id=4)>, "baz": <Baz(name="Bob", qux=<Qux(id=5)>>, "other_field": "value", } In this case, the Foo, Bar, and Qux instances are fetched from the database, while the Baz instance is freshly constructed. If any of the Foo, Bar, or Qux instances do not exist, then the component will fail the request with a 422. Formally, in this specification: - A `RelatedId` item will retrieve the existing object in the database with the ID from the specified scalar ID field using the specified view. - A view class will retrieve the existing object in the database using the object stub containing the ID fields from the data field of the same name, using the specified view. This is generally used with the `RelatedItem` field class, and unlike `RelatedId`, supports composite IDs. - Another `Related` item will apply the same resolution to a nested dictionary. Additionally, if the `Related` item is given a callable as its positional argument, it will construct a new instance given that callable, which can often be a model class. `Related` depends on the deserializer schema to function accordingly, and delegates validation beyond the database fetch to the schema. `Related` also automatically supports cases where the fields are list fields or are configured with ``many=True``. In those cases, `Related` will iterate through the sequence and resolve each item in turn, using the rules as above. :param item_class: The SQLAlchemy mapper corresponding to the related item. :param dict kwargs: A mapping from related fields to a callable resolver. """ def __init__(self, item_class=None, **kwargs): self._item_class = item_class self._resolvers = kwargs def resolve_related(self, data): """Resolve the related values in the request data. This method will replace values in `data` with resolved model instances as described above. This operates in place and will mutate `data`. :param data object: The deserialized request data. :return: The deserialized data with related fields resolved. :rtype: object """ for field_name, resolver in self._resolvers.items(): if isinstance(resolver, RelatedId): data_field_name = resolver.field_name else: data_field_name = field_name if data_field_name not in data: # If this field were required, the deserializer would already # have raised an exception. continue # Remove the data field (in case it's different) so we can keep # just the output field. value = data.pop(data_field_name) if value is None: # Explicitly clear the related item if the value was None. data[field_name] = None continue try: resolved = self.resolve_field(value, resolver) except ApiError as e: pointer = f"/data/{data_field_name}" raise e.update({"source": {"pointer": pointer}}) data[field_name] = resolved if self._item_class: return self._item_class(**data) return data def resolve_field(self, value, resolver): """Resolve a single field value. :param value: The value corresponding to the field we are resolving. :param resolver: A callable capable of resolving the given `value`. :type resolver: :py:class:`Related` | :py:class:`RelatedId` | func """ # marshmallow always uses lists here. many = isinstance(value, list) if many and not value: # As a tiny optimization, there's no need to resolve an empty list. return value if isinstance(resolver, Related): resolve_item = resolver.resolve_related elif isinstance(resolver, RelatedId): view = resolver.create_view() resolve_item = functools.partial(resolver.resolve_related_id, view) else: resolve_item = resolver().resolve_related_item if many: return [resolve_item(item) for item in value] return resolve_item(value) def __or__(self, other): """Combine two `Related` instances. `Related` supports view inheritance by implementing the `|` operator. For example, `Related(foo=..., bar=...) | Related(baz=...)` will create a new `Related` instance with resolvers for each `foo`, `bar` and `baz`. Resolvers on the right-hand side take precedence where each `Related` instance has the same key. """ if not isinstance(other, Related): return NotImplemented return self.__class__( other._item_class or self._item_class, **{**self._resolvers, **other._resolvers}, )
class Related: '''A component for resolving deserialized data fields to model instances. The `Related` component is responsible for resolving related model instances by ID and for constructing nested model instances. It supports multiple related types of functionality. For a view with:: related = Related( foo=RelatedId(FooView, "foo_id"), bar=BarView, baz=Related(models.Baz, qux=RelatedId(QuxView, "qux_id"), ) Given deserialized input data like:: { "foo_id": "3", "bar": {"id": "4"}, "baz": {name: "Bob", "qux_id": "5"}, "other_field": "value", } This component will resolve these data into something like:: { "foo": <Foo(id=3)>, "bar": <Bar(id=4)>, "baz": <Baz(name="Bob", qux=<Qux(id=5)>>, "other_field": "value", } In this case, the Foo, Bar, and Qux instances are fetched from the database, while the Baz instance is freshly constructed. If any of the Foo, Bar, or Qux instances do not exist, then the component will fail the request with a 422. Formally, in this specification: - A `RelatedId` item will retrieve the existing object in the database with the ID from the specified scalar ID field using the specified view. - A view class will retrieve the existing object in the database using the object stub containing the ID fields from the data field of the same name, using the specified view. This is generally used with the `RelatedItem` field class, and unlike `RelatedId`, supports composite IDs. - Another `Related` item will apply the same resolution to a nested dictionary. Additionally, if the `Related` item is given a callable as its positional argument, it will construct a new instance given that callable, which can often be a model class. `Related` depends on the deserializer schema to function accordingly, and delegates validation beyond the database fetch to the schema. `Related` also automatically supports cases where the fields are list fields or are configured with ``many=True``. In those cases, `Related` will iterate through the sequence and resolve each item in turn, using the rules as above. :param item_class: The SQLAlchemy mapper corresponding to the related item. :param dict kwargs: A mapping from related fields to a callable resolver. ''' def __init__(self, item_class=None, **kwargs): pass def resolve_related(self, data): '''Resolve the related values in the request data. This method will replace values in `data` with resolved model instances as described above. This operates in place and will mutate `data`. :param data object: The deserialized request data. :return: The deserialized data with related fields resolved. :rtype: object ''' pass def resolve_field(self, value, resolver): '''Resolve a single field value. :param value: The value corresponding to the field we are resolving. :param resolver: A callable capable of resolving the given `value`. :type resolver: :py:class:`Related` | :py:class:`RelatedId` | func ''' pass def __or__(self, other): '''Combine two `Related` instances. `Related` supports view inheritance by implementing the `|` operator. For example, `Related(foo=..., bar=...) | Related(baz=...)` will create a new `Related` instance with resolvers for each `foo`, `bar` and `baz`. Resolvers on the right-hand side take precedence where each `Related` instance has the same key. ''' pass
5
4
22
4
11
7
4
1.63
0
4
2
0
4
2
4
4
151
30
46
16
41
75
40
15
35
7
0
2
15
986
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/related.py
flask_resty.related.RelatedId
class RelatedId: """Resolve a related item by a scalar ID. :param view_class: The :py:class:`ModelView` corresponding to the related model. :param str field_name: The field name on request data. """ def __init__(self, view_class, field_name): self._view_class = view_class self.field_name = field_name def create_view(self): # Separating this out saves instantiating the view multiple times for # list fields. return self._view_class() def resolve_related_id(self, view, id): return view.resolve_related_id(id)
class RelatedId: '''Resolve a related item by a scalar ID. :param view_class: The :py:class:`ModelView` corresponding to the related model. :param str field_name: The field name on request data. ''' def __init__(self, view_class, field_name): pass def create_view(self): pass def resolve_related_id(self, view, id): pass
4
1
3
0
2
1
1
0.88
0
0
0
0
3
2
3
3
19
4
8
6
4
7
8
6
4
1
0
0
3
987
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/sorting.py
flask_resty.sorting.FixedSorting
class FixedSorting(FieldSortingBase): """A sorting component that applies a fixed sort order. For example, to sort queries by `name` ascending and `date` descending, specify the following in your view:: sorting = FixedSorting('name,-date') :param str fields: The formatted fields. """ def __init__(self, fields): self._field_orderings = self.get_field_orderings(fields) def get_request_field_orderings(self, view): return self._field_orderings
class FixedSorting(FieldSortingBase): '''A sorting component that applies a fixed sort order. For example, to sort queries by `name` ascending and `date` descending, specify the following in your view:: sorting = FixedSorting('name,-date') :param str fields: The formatted fields. ''' def __init__(self, fields): pass def get_request_field_orderings(self, view): pass
3
1
2
0
2
0
1
1.2
1
0
0
0
2
1
2
11
16
5
5
4
2
6
5
4
2
1
2
0
2
988
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/sorting.py
flask_resty.sorting.Sorting
class Sorting(FieldSortingBase): """A sorting component that allows the user to specify sort fields. For example, to allow users to sort by `title` and/or `content_length`, specify the following in your view:: sorting = Sorting( 'title', content_length=sql.func.length(Post.content) ) One or both of `title` or `content_length` can be formatted in the `sort_arg` request parameter to determine the sort order. For example, users can sort requests by `name` ascending and `date` descending by making a ``GET`` request to:: /api/comments/?sort=title,-content_length :param str field_names: The fields available for sorting. Names should match a column on your View's ``model``. :param str default: If provided, specifies a default sort order when the request does not specify an explicit sort order. :param dict kwargs: Provide custom sort behavior by mapping a sort argument name to a model order_by expression. """ #: The request parameter from which the formatted sorting fields will be #: retrieved. sort_arg = "sort" def __init__(self, *field_names, default=None, **kwargs): keys = frozenset(kwargs.keys()) names = frozenset(field_names) duplicates = keys.intersection(names) if duplicates: raise ValueError( f"Sort field(s) cannot be passed as both positional and keyword arguments: {duplicates}" ) self._field_names = names.union(keys) self._field_sorters = { field_name: field_sort for field_name, field_sort in kwargs.items() } self._default_sort = default def get_criterion(self, view, field_ordering): field_name, asc = field_ordering if field_name not in self._field_sorters: return super().get_criterion(view, field_ordering) sort = self._field_sorters[field_name] expr = sort(view.model, field_name) if callable(sort) else sort return expr if asc else sa.desc(expr) def get_request_field_orderings(self, view): sort = flask.request.args.get(self.sort_arg, self._default_sort) if sort is None: return () field_orderings = self.get_field_orderings(sort) for field_name, _ in field_orderings: if field_name not in self._field_names: raise ApiError( 400, { "code": "invalid_sort", "source": {"parameter": self.sort_arg}, }, ) return field_orderings
class Sorting(FieldSortingBase): '''A sorting component that allows the user to specify sort fields. For example, to allow users to sort by `title` and/or `content_length`, specify the following in your view:: sorting = Sorting( 'title', content_length=sql.func.length(Post.content) ) One or both of `title` or `content_length` can be formatted in the `sort_arg` request parameter to determine the sort order. For example, users can sort requests by `name` ascending and `date` descending by making a ``GET`` request to:: /api/comments/?sort=title,-content_length :param str field_names: The fields available for sorting. Names should match a column on your View's ``model``. :param str default: If provided, specifies a default sort order when the request does not specify an explicit sort order. :param dict kwargs: Provide custom sort behavior by mapping a sort argument name to a model order_by expression. ''' def __init__(self, *field_names, default=None, **kwargs): pass def get_criterion(self, view, field_ordering): pass def get_request_field_orderings(self, view): pass
4
1
15
3
12
0
3
0.57
1
4
1
0
3
3
3
12
76
18
37
17
33
21
27
17
23
4
2
2
10
989
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/testing.py
flask_resty.testing.ApiClient
class ApiClient(FlaskClient): """A `flask.testing.FlaskClient` with a few conveniences: * Prefixes paths * Sets ``Content-Type`` to "application/json" * Envelopes ``data`` within a "data" key in the request payload """ def open(self, path, *args, **kwargs): full_path = "{}{}".format( self.application.extensions["resty"].api.prefix, path ) if "data" in kwargs: kwargs.setdefault("content_type", "application/json") if kwargs["content_type"] == "application/json": kwargs["data"] = json.dumps({"data": kwargs["data"]}) return super().open(full_path, *args, **kwargs)
class ApiClient(FlaskClient): '''A `flask.testing.FlaskClient` with a few conveniences: * Prefixes paths * Sets ``Content-Type`` to "application/json" * Envelopes ``data`` within a "data" key in the request payload ''' def open(self, path, *args, **kwargs): pass
2
1
11
2
9
0
3
0.5
1
1
0
0
1
0
1
1
19
4
10
3
8
5
8
3
6
3
1
2
3
990
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/testing.py
flask_resty.testing.Predicate
class Predicate: """A helper object to do predicate assertion""" def __init__(self, predicate): self.predicate = predicate def __eq__(self, other): return self.predicate(other) def __ne__(self, other): return not self.predicate(other)
class Predicate: '''A helper object to do predicate assertion''' def __init__(self, predicate): pass def __eq__(self, other): pass def __ne__(self, other): pass
4
1
2
0
2
0
1
0.14
0
0
0
0
3
1
3
3
11
3
7
5
3
1
7
5
3
1
0
0
3
991
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/utils.py
flask_resty.utils.SettableProperty
class SettableProperty: def __init__(self, get_default): self.get_default = get_default self.internal_field_name = "_" + get_default.__name__ self.__doc__ = get_default.__doc__ def __get__(self, instance, owner): if instance is None: return self if hasattr(instance, self.internal_field_name): return getattr(instance, self.internal_field_name) else: return self.get_default(instance) def __set__(self, instance, value): setattr(instance, self.internal_field_name, value) def __delete__(self, instance): try: delattr(instance, self.internal_field_name) except AttributeError: pass
class SettableProperty: def __init__(self, get_default): pass def __get__(self, instance, owner): pass def __set__(self, instance, value): pass def __delete__(self, instance): pass
5
0
5
0
5
0
2
0
0
1
0
0
4
3
4
4
22
3
19
8
14
0
18
8
13
3
0
1
7
992
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/utils.py
flask_resty.utils._Undefined
class _Undefined: def __bool__(self): return False def __copy__(self): return self def __deepcopy__(self, _): return self def __repr__(self): # pragma: no cover return "<UNDEFINED>"
class _Undefined: def __bool__(self): pass def __copy__(self): pass def __deepcopy__(self, _): pass def __repr__(self): pass
5
0
2
0
2
0
1
0.11
0
0
0
0
4
0
4
4
12
3
9
5
4
1
9
5
4
1
0
0
4
993
4Catalyzer/flask-resty
4Catalyzer_flask-resty/flask_resty/view.py
flask_resty.view.ApiView
class ApiView(MethodView): """Base class for views that expose API endpoints. `ApiView` extends :py:class:`flask.views.MethodView` exposes functionality to deserialize request bodies and serialize response bodies according to standard API semantics. """ #: The :py:class:`marshmallow.Schema` for serialization and #: deserialization. schema = None #: The identifying fields for the model. id_fields = ("id",) #: The :py:class:`marshmallow.Schema` for deserializing the query params in #: the :py:data:`flask.Request.args`. args_schema = None #: The authentication component. See :py:class:`AuthenticationBase`. authentication = NoOpAuthentication() #: The authorization component. See :py:class:`AuthorizationBase`. authorization = NoOpAuthorization() def dispatch_request(self, *args, **kwargs): """Handle an incoming request. By default, this checks request-level authentication and authorization before calling the upstream request handler. """ self.authentication.authenticate_request() self.authorization.authorize_request() return super().dispatch_request(*args, **kwargs) def serialize(self, item, **kwargs): """Dump an item using the :py:attr:`serializer`. This doesn't technically serialize the item; it instead uses marshmallow to dump the item into a native Python data type. The actual serialization is done in `make_response`. Any provided `**kwargs` will be passed to :py:meth:`marshmallow.Schema.dump`. :param object item: The object to serialize :return: The serialized object :rtype: dict """ return self.serializer.dump(item, **kwargs) @settable_property def serializer(self): """The :py:class:`marshmallow.Schema` for serialization. By default, this is :py:attr:`ApiView.schema`. This can be overridden to use a different schema for serialization. """ return self.schema def make_items_response(self, items, *args): """Build a response for a sequence of multiple items. This serializes the items, then builds an response with the list of serialized items as its data. This is useful when returning a list of items. The response will have the items available as the ``items`` attribute. :param list items: The objects to serialize into the response body. :return: The HTTP response :rtype: :py:class:`flask.Response` """ data_out = self.serialize(items, many=True) return self.make_response(data_out, *args, items=items) def make_item_response(self, item, *args): """Build a response for a single item. This serializes the item, then builds an response with the serialized item as its data. If the response status code is 201, then it will also include a ``Location`` header with the canonical URL of the item, if available. The response will have the item available as the ``item`` attribute. :param object item: The object to serialize into the response body. :return: The HTTP response :rtype: :py:class:`flask.Response` """ data_out = self.serialize(item) self.set_item_response_meta(item) response = self.make_response(data_out, *args, item=item) if response.status_code == 201: location = self.get_location(item) if location is not None: response.headers["Location"] = location return response def set_item_response_meta(self, item): """Hook for setting additional metadata for an item. This should call `meta.update_response_meta` to set any metadata values to add to the response. :param object item: The object for which to generate metadata. :return: """ pass def make_response(self, data, *args, **kwargs): """Build a response for arbitrary dumped data. This builds the response body given the data and any metadata from the request context. It then serializes the response. :return: The HTTP response :rtype: :py:class:`flask.Response` """ body = self.render_response_body(data, meta.get_response_meta()) return self.make_raw_response(body, *args, **kwargs) def render_response_body(self, data, response_meta): """Render the response data and metadata into a body. This is the final step of building the response payload before serialization. By default, this builds a dictionary with a ``data`` item for the response data and a ``meta`` item for the response metadata, if any. """ body = {"data": data} if response_meta is not None: body["meta"] = response_meta return flask.jsonify(body) def make_raw_response(self, *args, **kwargs): """Convenience method for creating a :py:class:`flask.Response`. Any supplied keyword arguments are defined as attributes on the response object itself. :return: The HTTP response :rtype: :py:class:`flask.Response` """ response = flask.make_response(*args) for key, value in kwargs.items(): setattr(response, key, value) return response def make_empty_response(self, **kwargs): """Build an empty response. This response has a status code of 204 and an empty body. :return: The HTTP response :rtype: :py:class:`flask.Response` """ return self.make_raw_response("", 204, **kwargs) def make_created_response(self, item): """Build a response for a newly created item. This response will be for the item data and will have a status code of 201. It will include a ``Location`` header with the canonical URL of the created item, if available. :param object item: The created item. :return: The HTTP response :rtype: :py:class:`flask.Response` """ return self.make_item_response(item, 201) def make_deleted_response(self, item): """Build a response for a deleted item. By default, this will be an empty response. The empty response will have the ``item`` attribute as with an item response. :param object item: The deleted item. :return: The HTTP response :rtype: :py:class:`flask.Response` """ return self.make_empty_response(item=item) def get_location(self, item): """Get the canonical URL for an item. Override this to return ``None`` if no such URL is available. :param object item: The item. :return: The canonical URL for `item`. :rtype: str """ id_dict = { id_field: getattr(item, id_field) for id_field in self.id_fields } return flask.url_for(flask.request.endpoint, _method="GET", **id_dict) def get_request_data(self, **kwargs): """Deserialize and load data from the body of the current request. By default, this will look for the value under the ``data`` key in a JSON request body. :return: The deserialized request data :rtype: dict """ data_raw = self.parse_request_data() return self.deserialize(data_raw, **kwargs) def parse_request_data(self): """Deserialize the data for the current request. This will deserialize the request data from the request body into a native Python object that can be loaded by marshmallow. :return: The deserialized request data. """ try: data_raw = flask.request.get_json(silent=True)["data"] except TypeError as e: raise ApiError(400, {"code": "invalid_body"}) from e except KeyError as e: raise ApiError(400, {"code": "invalid_data.missing"}) from e return data_raw def deserialize(self, data_raw, *, expected_id=None, **kwargs): """Load data using the :py:attr:`deserializer`. This doesn't technically deserialize the data; it instead uses marshmallow to load and validate the data. The actual deserialization happens in `parse_request_data`. Any provided `**kwargs` will be passed to :py:meth:`marshmallow.Schema.load`. :param data_raw: The request data to load. :param expected_id: The expected ID in the request data. See `validate_request_id`. :return: The deserialized data :rtype: dict """ try: data = self.deserializer.load(data_raw, **kwargs) except ValidationError as e: raise ApiError.from_validation_error( 422, e, self.format_validation_error ) from e self.validate_request_id(data, expected_id) return data @settable_property def deserializer(self): """The :py:class:`marshmallow.Schema` for serialization. By default, this is :py:attr:`ApiView.schema`. This can be overridden to use a different schema for deserialization. """ return self.schema def format_validation_error(self, message, path): """Convert marshmallow validation error data to a serializable form. This converts marshmallow validation error data to a standard serializable representation. By default, it converts errors into a dictionary of the form:: { "code": "invalid_data", "detail": "<error message>", "source": { "pointer": "/data/<field name>" } } :param str message: The marshmallow validation error message. :param tuple path: The path to the invalid field. :return: The formatted validation error. :rtype: dict """ pointer = "/data/{}".format( "/".join(str(field_key) for field_key in path) ) return { "code": "invalid_data", "detail": message, "source": {"pointer": pointer}, } def validate_request_id(self, data, expected_id): """Check that the request data has the expected ID. This is generally used to assert that update operations include the correct item ID and that create operations do not include an ID. This works in one of three modes:: - If `expected_id` is ``None``, do no checking - If `expected_id` is ``False``, check that no ID is provided - Otherwise, check that `data` has the expected ID :param data: The request data. :param expected_id: The ID or ID tuple, or False, or None. :raises ApiError: If the necessary IDs are not present and correct """ if expected_id is None: return if expected_id is False: for id_field in self.id_fields: if id_field in data: raise ApiError(403, {"code": "invalid_id.forbidden"}) return try: id = self.get_data_id(data) except KeyError as e: raise ApiError(422, {"code": "invalid_id.missing"}) from e if id != expected_id: raise ApiError(409, {"code": "invalid_id.mismatch"}) def get_data_id(self, data): """Get the ID as a scalar or tuple from request data. The ID will be a scalar if :py:attr:`id_fields` contains a single field or a tuple if it contains multiple. :return: The ID scalar or tuple. """ if len(self.id_fields) == 1: return data[self.id_fields[0]] return tuple(data[id_field] for id_field in self.id_fields) @request_cached_property def request_args(self): """The query arguments for the current request. This uses :py:attr:`args_schema` to load the current query args. This value is cached per request, and will be computed the first time it is called for any request. :return: The query arguments. :rtype: dict """ args = flask.request.args data_raw = {} for field_name, field in self.args_schema.fields.items(): alternate_field_name = field.data_key if alternate_field_name and alternate_field_name in args: field_name = alternate_field_name elif field_name not in args: # getlist will return an empty list instead of raising a # KeyError for args that aren't present. continue if isinstance(field, fields.List) and not isinstance( field, DelimitedList ): value = args.getlist(field_name) else: value = args.get(field_name) data_raw[field_name] = value return self.deserialize_args(data_raw) def deserialize_args(self, data_raw, **kwargs): """Load parsed query arg data using :py:attr:`args_schema`. As with `deserialize`, contra the name, this handles loading with a schema rather than deserialization per se. :param dict data_raw: The raw query data. :param dict kwargs: Additional keyword arguments for `marshmallow.Schema.load`. :return: The deserialized data :rtype: object """ try: data = self.args_schema.load(data_raw, **kwargs) except ValidationError as e: raise ApiError( 422, *( self.format_parameter_validation_error(message, parameter) for parameter, messages in e.messages.items() for message in messages ), ) from e return data def format_parameter_validation_error(self, message, parameter): """Convert a parameter validation error to a serializable form. This closely follows `format_validation_error`, but produces error dictionaries of the form:: { "code": "invalid_parameter", "detail": "<error message>", "source": { "parameter": "<parameter name>" } } :param str message: The validation error message. :param str parameter: The query parameter name. :return: The formatted parameter validation error :rtype: dict """ return { "code": "invalid_parameter", "detail": message, "source": {"parameter": parameter}, } def get_id_dict(self, id): """Convert an ID from `get_data_id` to dictionary form. This converts an ID from `get_data_id` into a dictionary where each ID value is keyed by the corresponding ID field name. :param id: An ID from `get_id_dict` :type: str or tuple :return: A mapping from ID field names to ID field values :rtype: dict """ if len(self.id_fields) == 1: id = (id,) return dict(zip(self.id_fields, id))
class ApiView(MethodView): '''Base class for views that expose API endpoints. `ApiView` extends :py:class:`flask.views.MethodView` exposes functionality to deserialize request bodies and serialize response bodies according to standard API semantics. ''' def dispatch_request(self, *args, **kwargs): '''Handle an incoming request. By default, this checks request-level authentication and authorization before calling the upstream request handler. ''' pass def serialize(self, item, **kwargs): '''Dump an item using the :py:attr:`serializer`. This doesn't technically serialize the item; it instead uses marshmallow to dump the item into a native Python data type. The actual serialization is done in `make_response`. Any provided `**kwargs` will be passed to :py:meth:`marshmallow.Schema.dump`. :param object item: The object to serialize :return: The serialized object :rtype: dict ''' pass @settable_property def serializer(self): '''The :py:class:`marshmallow.Schema` for serialization. By default, this is :py:attr:`ApiView.schema`. This can be overridden to use a different schema for serialization. ''' pass def make_items_response(self, items, *args): '''Build a response for a sequence of multiple items. This serializes the items, then builds an response with the list of serialized items as its data. This is useful when returning a list of items. The response will have the items available as the ``items`` attribute. :param list items: The objects to serialize into the response body. :return: The HTTP response :rtype: :py:class:`flask.Response` ''' pass def make_item_response(self, item, *args): '''Build a response for a single item. This serializes the item, then builds an response with the serialized item as its data. If the response status code is 201, then it will also include a ``Location`` header with the canonical URL of the item, if available. The response will have the item available as the ``item`` attribute. :param object item: The object to serialize into the response body. :return: The HTTP response :rtype: :py:class:`flask.Response` ''' pass def set_item_response_meta(self, item): '''Hook for setting additional metadata for an item. This should call `meta.update_response_meta` to set any metadata values to add to the response. :param object item: The object for which to generate metadata. :return: ''' pass def make_response(self, data, *args, **kwargs): '''Build a response for arbitrary dumped data. This builds the response body given the data and any metadata from the request context. It then serializes the response. :return: The HTTP response :rtype: :py:class:`flask.Response` ''' pass def render_response_body(self, data, response_meta): '''Render the response data and metadata into a body. This is the final step of building the response payload before serialization. By default, this builds a dictionary with a ``data`` item for the response data and a ``meta`` item for the response metadata, if any. ''' pass def make_raw_response(self, *args, **kwargs): '''Convenience method for creating a :py:class:`flask.Response`. Any supplied keyword arguments are defined as attributes on the response object itself. :return: The HTTP response :rtype: :py:class:`flask.Response` ''' pass def make_empty_response(self, **kwargs): '''Build an empty response. This response has a status code of 204 and an empty body. :return: The HTTP response :rtype: :py:class:`flask.Response` ''' pass def make_created_response(self, item): '''Build a response for a newly created item. This response will be for the item data and will have a status code of 201. It will include a ``Location`` header with the canonical URL of the created item, if available. :param object item: The created item. :return: The HTTP response :rtype: :py:class:`flask.Response` ''' pass def make_deleted_response(self, item): '''Build a response for a deleted item. By default, this will be an empty response. The empty response will have the ``item`` attribute as with an item response. :param object item: The deleted item. :return: The HTTP response :rtype: :py:class:`flask.Response` ''' pass def get_location(self, item): '''Get the canonical URL for an item. Override this to return ``None`` if no such URL is available. :param object item: The item. :return: The canonical URL for `item`. :rtype: str ''' pass def get_request_data(self, **kwargs): '''Deserialize and load data from the body of the current request. By default, this will look for the value under the ``data`` key in a JSON request body. :return: The deserialized request data :rtype: dict ''' pass def parse_request_data(self): '''Deserialize the data for the current request. This will deserialize the request data from the request body into a native Python object that can be loaded by marshmallow. :return: The deserialized request data. ''' pass def deserialize(self, data_raw, *, expected_id=None, **kwargs): '''Load data using the :py:attr:`deserializer`. This doesn't technically deserialize the data; it instead uses marshmallow to load and validate the data. The actual deserialization happens in `parse_request_data`. Any provided `**kwargs` will be passed to :py:meth:`marshmallow.Schema.load`. :param data_raw: The request data to load. :param expected_id: The expected ID in the request data. See `validate_request_id`. :return: The deserialized data :rtype: dict ''' pass @settable_property def deserializer(self): '''The :py:class:`marshmallow.Schema` for serialization. By default, this is :py:attr:`ApiView.schema`. This can be overridden to use a different schema for deserialization. ''' pass def format_validation_error(self, message, path): '''Convert marshmallow validation error data to a serializable form. This converts marshmallow validation error data to a standard serializable representation. By default, it converts errors into a dictionary of the form:: { "code": "invalid_data", "detail": "<error message>", "source": { "pointer": "/data/<field name>" } } :param str message: The marshmallow validation error message. :param tuple path: The path to the invalid field. :return: The formatted validation error. :rtype: dict ''' pass def validate_request_id(self, data, expected_id): '''Check that the request data has the expected ID. This is generally used to assert that update operations include the correct item ID and that create operations do not include an ID. This works in one of three modes:: - If `expected_id` is ``None``, do no checking - If `expected_id` is ``False``, check that no ID is provided - Otherwise, check that `data` has the expected ID :param data: The request data. :param expected_id: The ID or ID tuple, or False, or None. :raises ApiError: If the necessary IDs are not present and correct ''' pass def get_data_id(self, data): '''Get the ID as a scalar or tuple from request data. The ID will be a scalar if :py:attr:`id_fields` contains a single field or a tuple if it contains multiple. :return: The ID scalar or tuple. ''' pass @request_cached_property def request_args(self): '''The query arguments for the current request. This uses :py:attr:`args_schema` to load the current query args. This value is cached per request, and will be computed the first time it is called for any request. :return: The query arguments. :rtype: dict ''' pass def deserialize_args(self, data_raw, **kwargs): '''Load parsed query arg data using :py:attr:`args_schema`. As with `deserialize`, contra the name, this handles loading with a schema rather than deserialization per se. :param dict data_raw: The raw query data. :param dict kwargs: Additional keyword arguments for `marshmallow.Schema.load`. :return: The deserialized data :rtype: object ''' pass def format_parameter_validation_error(self, message, parameter): '''Convert a parameter validation error to a serializable form. This closely follows `format_validation_error`, but produces error dictionaries of the form:: { "code": "invalid_parameter", "detail": "<error message>", "source": { "parameter": "<parameter name>" } } :param str message: The validation error message. :param str parameter: The query parameter name. :return: The formatted parameter validation error :rtype: dict ''' pass def get_id_dict(self, id): '''Convert an ID from `get_data_id` to dictionary form. This converts an ID from `get_data_id` into a dictionary where each ID value is keyed by the corresponding ID field name. :param id: An ID from `get_id_dict` :type: str or tuple :return: A mapping from ID field names to ID field values :rtype: dict ''' pass
28
25
16
3
6
8
2
1.38
1
9
2
9
24
0
24
24
440
98
144
58
116
198
116
50
91
7
1
3
44
994
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.views.WidgetListView
class WidgetListView(WidgetViewBase): def post(self): return self.create()
class WidgetListView(WidgetViewBase): def post(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
62
3
0
3
2
1
0
3
2
1
1
5
0
1
995
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_args.py
tests.test_args.schemas.NameDelimitedListSchema
class NameDelimitedListSchema(Schema): names = DelimitedList(fields.String(), data_key="name", required=True)
class NameDelimitedListSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
996
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_view_errors.py
tests.test_view_errors.views.WidgetView
class WidgetView(WidgetViewBase): def get(self, id): return self.retrieve(id) def patch(self, id): return self.update(id, partial=True)
class WidgetView(WidgetViewBase): def get(self, id): pass def patch(self, id): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
63
6
1
5
3
2
0
5
3
2
1
5
0
2
997
4Catalyzer/flask-resty
4Catalyzer_flask-resty/example/views.py
example.views.BookViewBase
class BookViewBase(GenericModelView): model = models.Book schema = schemas.BookSchema() authentication = NoOpAuthentication() authorization = NoOpAuthorization() pagination = PagePagination(page_size=10) sorting = Sorting("published_at", default="-published_at") filtering = Filtering(author_id=ColumnFilter(operator.eq, required=True))
class BookViewBase(GenericModelView): pass
1
0
0
0
0
0
0
0
1
0
0
2
0
0
0
61
10
2
8
8
7
0
8
8
7
0
4
0
0
998
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_fields.py
tests.test_fields.related_schema_class.RelatedSchema
class RelatedSchema(Schema): id = fields.Integer(as_string=True) name = fields.String(required=True)
class RelatedSchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
2
2
0
3
2
2
0
1
0
0
999
4Catalyzer/flask-resty
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/4Catalyzer_flask-resty/tests/test_fields.py
tests.test_fields.many_schema.ManySchema
class ManySchema(Schema): children = RelatedItem(related_schema_class, many=True, required=True)
class ManySchema(Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0