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
800
475Cumulus/TBone
475Cumulus_TBone/tests/resources/resources.py
tests.resources.resources.PersonResource
class PersonResource(Resource): ''' Used during resource tests. Implements a poor-man's RESTful API over an in-memory fixture loaded during creation ''' limit = 10 pk_type = int pk = 'id' async def list(self, *args, **kwargs): offset = kwargs.get('offset', 0) limit = kwargs.get('limit', self.limit) return { 'meta': { 'total_count': len(self.request.app.db), 'limit': self.limit, 'offset': 0 }, 'objects': self.request.app.db[offset:limit] } async def detail(self, *args, **kwargs): pk = kwargs.get('pk') if pk: obj = next(filter(lambda x: x['id'] == self.pk_type(pk), self.request.app.db), None) if obj: return obj raise NotFound('Object matching the given {} with value {} was not found'.format(self.pk, self.pk_type(pk))) async def create(self, *args, **kwargs): new_obj = self.request.body new_obj['id'] = len(self.request.app.db) + 1 self.request.app.db.append(new_obj) return new_obj async def update(self, *args, **kwargs): raise MethodNotImplemented() async def delete(self, *args, **kwargs): raise MethodNotImplemented()
class PersonResource(Resource): ''' Used during resource tests. Implements a poor-man's RESTful API over an in-memory fixture loaded during creation ''' async def list(self, *args, **kwargs): pass async def detail(self, *args, **kwargs): pass async def create(self, *args, **kwargs): pass async def update(self, *args, **kwargs): pass async def delete(self, *args, **kwargs): pass
6
1
5
0
5
0
1
0.13
1
3
2
1
5
0
5
57
40
5
31
14
25
4
24
14
18
3
4
2
7
801
475Cumulus/TBone
475Cumulus_TBone/tests/resources/resources.py
tests.resources.resources.BookResource
class BookResource(MongoResource): class Meta: object_class = Book @classmethod def nested_routes(cls, base_url, formatter=None): if formatter is None or callable(formatter) is False: formatter = cls.route_param return [ Route( path=base_url + '%s/reviews/add/' % formatter('pk'), handler=cls.add_review, methods='POST', name='add_review') ] async def add_review(self, request, **kwargs): try: if 'pk' not in request.args: raise Exception('Object pk not provided') # add a new review to the document using a custom Model method which pushes the new review to the document book = Book({Book.primary_key: request.args['pk']}) update_result = await book.add_review(request.app.db, request.body) if update_result.matched_count != 1 or update_result.modified_count != 1: raise Exception('Database update failed. Unexpected update results') except Exception as ex: return {'error': ex}
class BookResource(MongoResource): class Meta: @classmethod def nested_routes(cls, base_url, formatter=None): pass async def add_review(self, request, **kwargs): pass
5
0
11
0
10
1
3
0.04
1
2
1
0
1
0
2
69
27
2
24
9
19
1
17
7
13
4
6
2
6
802
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.Review
class Review(Model): user = StringField(required=True) ratings = DictField(IntegerField) text = StringField() @serialize async def total_rating(self): return sum(self.ratings.values(), 0.0) / len(self.ratings.values())
class Review(Model): @serialize async def total_rating(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
31
8
1
7
6
4
0
6
5
4
1
4
0
1
803
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/mongo.py
tbone.data.fields.mongo.DBRefField
class DBRefField(CompositeField): ''' A field wrapper around MongoDB reference fields ''' _data_type = RefDict _python_type = DBRef ERRORS = { 'missing_id': 'Referenced model does not have the _id attribute', 'invalid_id': 'Referenced model has an empty or invalid _id' } def __init__(self, model_class, **kwargs): super(DBRefField, self).__init__(**kwargs) if isinstance(model_class, (ModelMeta, MongoCollectionMixin)): self.model_class = model_class else: raise TypeError("DBRefField: Expected a model of the type '{}'.".format(model_class.__name__)) def _import(self, value): if value is None: return None if isinstance(value, self.model_class): if not hasattr(value, '_id'): raise ValueError(self._errors['missing_id']) if value._id is None or value._id.is_valid(str(value._id)) is False: raise ValueError(self._errors['invalid_id']) return self._python_type(self.model_class.get_collection_name(), value._id) elif isinstance(value, self._python_type): return value elif isinstance(value, dict): return self._python_type(value['ref'], ObjectId(value['id'])) raise ValueError(self._errors['to_python']) def _export(self, value): if value is None: return None if isinstance(value, self.model_class): if not hasattr(value, '_id'): raise ValueError(self._errors['missing_id']) if value._id is None or value._id.is_valid(str(value._id)) is False: raise ValueError(self._errors['invalid_id']) return self._data_type({ 'ref': value.get_collection_name(), 'id': value._id }) elif isinstance(value, self._python_type): return self._data_type({ 'ref': value.collection, 'id': str(value.id) }) raise ValueError(self._errors['to_data'])
class DBRefField(CompositeField): ''' A field wrapper around MongoDB reference fields ''' def __init__(self, model_class, **kwargs): pass def _import(self, value): pass def _export(self, value): pass
4
1
14
1
13
0
5
0.07
1
7
2
0
3
1
3
35
54
6
45
8
41
3
32
8
28
7
5
2
15
804
475Cumulus/TBone
475Cumulus_TBone/examples/snippets/aiohttp_resource_hookup.py
aiohttp_resource_hookup.TestResource
class TestResource(AioHttpResource, Resource): async def list(self, **kwargs): return { 'meta': {}, 'objects': [ {'text': 'hello world'} ] }
class TestResource(AioHttpResource, Resource): async def list(self, **kwargs): pass
2
0
7
0
7
0
1
0
2
0
0
0
1
0
1
58
8
0
8
2
6
0
3
2
1
1
4
0
1
805
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.Number
class Number(BaseModel): number = IntegerField()
class Number(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
51
2
0
2
2
1
0
2
2
1
0
5
0
0
806
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.CreditCardNumberField
class CreditCardNumberField(StringField): pass
class CreditCardNumberField(StringField): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
0
2
0
2
1
1
1
2
1
1
0
1
0
0
807
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.CreditCard
class CreditCard(Model): number = CreditCardNumberField() type = StringField()
class CreditCard(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
3
0
3
3
2
0
3
3
2
0
4
0
0
808
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.Child
class Child(Model): gender = StringField(choices=['M', 'F']) first_name = StringField(required=True) last_name = StringField(required=True) DOB = DateField()
class Child(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
5
0
5
5
4
0
5
5
4
0
4
0
0
809
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.Book
class Book(Model, MongoCollectionMixin): isbn = StringField(primary_key=True) title = StringField(required=True) author = ListField(StringField) format = StringField(choices=['Paperback', 'Hardcover', 'Digital', 'Audiobook'], default='Paperback') publication_date = DateTimeField() # MongoDB cannot persist dates only and accepts only datetime reviews = ListField(ModelField(Review), default=[]) # internal attributes number_of_impressions = IntegerField(default=0, projection=None) number_of_views = IntegerField(default=0, projection=None) class Meta: name = 'books' namespace = 'catalog' indices = [{ 'name': '_isbn', 'fields': [('isbn', ASCENDING)], 'unique': True }, { 'name': '_fts', 'fields': [ ('title', TEXT), ('author', TEXT) ] }] async def add_review(self, db, review_data): ''' Adds a review to the list of reviews, without fetching and updating the entire document ''' db = db or self.db # create review model instance new_rev = Review(review_data) data = new_rev.export_data(native=True) # use model's pk as query query = {self.primary_key: self.pk} # push review result = await db[self.get_collection_name()].update_one( filter=query, update={'$push': {'reviews': data}}, ) return result async def inc_number_of_impressions(self, db): ''' Increment the number of views by 1 ''' db = db or self.db # use model's pk as query query = {self.primary_key: self.pk} # push review result = await db[self.get_collection_name()].update_one( filter=query, update={'$inc': {'number_of_impressions': 1}}, ) return result async def inc_number_of_views(self, db): ''' Increment the number of views by 1 ''' db = db or self.db # use model's pk as query query = {self.primary_key: self.pk} # push review result = await db[self.get_collection_name()].update_one( filter=query, update={'$inc': {'number_of_views': 1}}, ) return result
class Book(Model, MongoCollectionMixin): class Meta: async def add_review(self, db, review_data): ''' Adds a review to the list of reviews, without fetching and updating the entire document ''' pass async def inc_number_of_impressions(self, db): ''' Increment the number of views by 1 ''' pass async def inc_number_of_views(self, db): ''' Increment the number of views by 1 ''' pass
5
3
12
0
9
3
1
0.24
2
1
1
0
3
0
3
53
64
4
49
23
44
12
30
23
25
1
4
0
3
810
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.BaseModel
class BaseModel(Model, MongoCollectionMixin): ''' Base model which adds a mongodb default _id field and an serialize method for object creation timestamp''' _id = ObjectIdField(primary_key=True) class Meta: concrete = False @serialize async def created(self): return self._id.generation_time.isoformat()
class BaseModel(Model, MongoCollectionMixin): ''' Base model which adds a mongodb default _id field and an serialize method for object creation timestamp''' class Meta: @serialize async def created(self): pass
4
1
2
0
2
0
1
0.14
2
0
0
8
1
0
1
51
10
2
7
6
3
1
6
5
3
1
4
0
1
811
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.Address
class Address(Model): city = StringField(required=True) street_name = StringField(required=True) street_number = IntegerField() zipcode = StringField() state = StringField() country = StringField(required=True)
class Address(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
7
0
7
7
6
0
7
7
6
0
4
0
0
812
475Cumulus/TBone
475Cumulus_TBone/tbone/utils.py
tbone.utils.ExtendedJSONEncoder
class ExtendedJSONEncoder(json.JSONEncoder): ''' Extends the default JSON encoder to support additional data types: datetime.datetime datetime.date datetime.time decimal.Decimal uuid.UUID ''' def default(self, data): if isinstance(data, (datetime.datetime, datetime.date, datetime.time)): return data.isoformat() elif isinstance(data, decimal.Decimal) or isinstance(data, uuid.UUID): return str(data) else: return super(ExtendedJSONEncoder, self).default(data)
class ExtendedJSONEncoder(json.JSONEncoder): ''' Extends the default JSON encoder to support additional data types: datetime.datetime datetime.date datetime.time decimal.Decimal uuid.UUID ''' def default(self, data): pass
2
1
7
0
7
0
3
1
1
7
0
0
1
0
1
5
16
0
8
2
6
8
6
2
4
3
2
1
3
813
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.Person
class Person(BaseModel): first_name = StringField(required=True) last_name = StringField(required=True) @serialize async def full_name(self): # redundant but good for testing return '{} {}'.format(self.first_name, self.last_name)
class Person(BaseModel): @serialize async def full_name(self): pass
3
0
2
0
2
1
1
0.17
1
0
0
0
1
0
1
52
7
1
6
5
3
1
5
4
3
1
5
0
1
814
475Cumulus/TBone
475Cumulus_TBone/tests/db/models.py
tests.db.models.Profile
class Profile(Model): title = StringField() first_name = StringField(required=True) last_name = StringField(required=True) suffix = StringField(projection=False) avatar = StringField() DOB = DateField()
class Profile(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
7
0
7
7
6
0
7
7
6
0
4
0
0
815
475Cumulus/TBone
475Cumulus_TBone/tbone/testing/resources.py
tbone.testing.resources.DummyResource
class DummyResource(object): ''' Dummy resource mixin to emulate the behavior of an async http library. Used for testing without Sanic or Aiohttp ''' @classmethod def build_http_response(cls, payload, status=200): return Response( payload=payload, headers={'Content-Type': 'application/json'}, status=status ) async def request_body(self): ''' Returns the body of the current request. The resource expects a text-formatted body ''' if isinstance(self.request.body, dict): return json.dumps(self.request.body) return self.request.body def request_args(self): ''' Returns the url arguments of the current request''' return self.request.args @classmethod def route_methods(cls): ''' Returns the relevant representation of allowed HTTP methods for a given route. ''' return '*'
class DummyResource(object): ''' Dummy resource mixin to emulate the behavior of an async http library. Used for testing without Sanic or Aiohttp ''' @classmethod def build_http_response(cls, payload, status=200): pass async def request_body(self): ''' Returns the body of the current request. The resource expects a text-formatted body ''' pass def request_args(self): ''' Returns the url arguments of the current request''' pass @classmethod def route_methods(cls): ''' Returns the relevant representation of allowed HTTP methods for a given route. ''' pass
7
4
6
0
4
2
1
0.71
1
1
0
0
2
0
4
4
32
3
17
7
10
12
11
5
6
2
1
1
5
816
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/base.py
tbone.data.fields.base.Ternary
class Ternary(object): ''' A class for managing a ternary object with 3 possible states ''' def __init__(self, value=None): if any(value is v for v in (True, False, None)): self.value = value else: raise ValueError('Ternary value must be True, False, or None') def __eq__(self, other): return (self.value is other.value if isinstance(other, Ternary) else self.value is other) def __ne__(self, other): return not self == other def __bool__(self): raise TypeError('Ternary object may not be used as a Boolean') def __str__(self): return str(self.value) def __repr__(self): return "Ternary(%s)" % self.value
class Ternary(object): ''' A class for managing a ternary object with 3 possible states ''' def __init__(self, value=None): pass def __eq__(self, other): pass def __ne__(self, other): pass def __bool__(self): pass def __str__(self): pass def __repr__(self): pass
7
1
3
0
3
0
1
0.06
1
3
0
0
6
1
6
6
24
6
17
8
10
1
15
8
8
2
1
1
8
817
475Cumulus/TBone
475Cumulus_TBone/examples/blog/backend/models.py
backend.models.Comment
class Comment(Model): timestamp = DateTimeField(default=datetime.now) text = StringField(required=True) user = StringField(required=True)
class Comment(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
4
0
4
4
3
0
4
4
3
0
4
0
0
818
475Cumulus/TBone
475Cumulus_TBone/examples/blog/backend/models.py
backend.models.Entry
class Entry(Model, MongoCollectionMixin): _id = ObjectIdField(primary_key=True) title = StringField(required=True) content = StringField(required=True) tags = ListField(StringField) comments = ListField(ModelField(Comment))
class Entry(Model, MongoCollectionMixin): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
50
7
1
6
6
5
0
6
6
5
0
4
0
0
819
475Cumulus/TBone
475Cumulus_TBone/examples/movies/backend/models.py
backend.models.Reviews
class Reviews(Model): title = StringField(required=True) text = StringField(required=True) rating = FloatField(required=True) user = ObjectIdField()
class Reviews(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
5
0
5
5
4
0
5
5
4
0
4
0
0
820
475Cumulus/TBone
475Cumulus_TBone/examples/weather/main.py
main.CityInfo
class CityInfo(Model): city = StringField(required=True) state = StringField() @export async def current_weather(self): async with aiohttp.ClientSession() as session: async with session.get(QUERY_URL.format(key=API_KEY, city=self.city, state=self.state)) as resp: if resp.status == 200: # http OK data = await resp.json() return data['list'][0]['main']['temp'] return None
class CityInfo(Model): @export async def current_weather(self): pass
3
0
7
0
7
1
2
0.09
1
1
0
0
1
0
1
31
12
1
11
8
8
1
10
5
8
2
4
3
2
821
475Cumulus/TBone
475Cumulus_TBone/examples/chatrooms/backend/models.py
models.BaseModel
class BaseModel(Model, MongoCollectionMixin): _id = ObjectIdField(primary_key=True) class Meta: concrete = False @serialize async def created(self): return self._id.generation_time.isoformat()
class BaseModel(Model, MongoCollectionMixin): class Meta: @serialize async def created(self): pass
4
0
2
0
2
0
1
0
2
0
0
3
1
0
1
51
9
2
7
6
3
0
6
5
3
1
4
0
1
822
475Cumulus/TBone
475Cumulus_TBone/examples/chatrooms/backend/models.py
models.Room
class Room(BaseModel): name = StringField(primary_key=True) title = StringField() default = BooleanField(default=False) # new users will be added to this channel as they join in active = BooleanField(default=True) access = IntegerField(default=ACCESS_PUBLIC, choices=[ACCESS_PUBLIC, ACCESS_PROTECTED, ACCESS_PRIVATE]) owner = DBRefField(User, required=True) members = ListField(DBRefField(User), default=[]) class Meta: name = 'rooms' indices = [ { 'name': '_name', 'fields': [('name', ASCENDING)], 'unique': True } ] async def add_member(self, db, user): ''' Adds a new user to the list of room members, if memeber doesn't exist already ''' # use model's pk as query query = {self.primary_key: self.pk} # push review result = await db[self.get_collection_name()].update_one( filter=query, update={'$addToSet': {'members': DBRefField(User).to_python(user)}}, ) return result async def remove_member(self, db, user): pass
class Room(BaseModel): class Meta: async def add_member(self, db, user): ''' Adds a new user to the list of room members, if memeber doesn't exist already ''' pass async def remove_member(self, db, user): pass
4
1
7
1
5
2
1
0.15
1
2
2
0
2
0
2
53
34
5
26
15
22
4
17
15
13
1
5
0
2
823
475Cumulus/TBone
475Cumulus_TBone/examples/chatrooms/backend/resources.py
resources.EntryResource
class EntryResource(WeblibResource, MongoResource): class Meta: object_class = Entry authentication = UserAuthentication() sort = [('_id', -1)] # revert order by creation, we want to display by order of entry decending hypermedia = False async def create(self, **kwargs): ''' Override the create method to add the user's id to the request data ''' return await super(EntryResource, self).create(user=self.request['user'])
class EntryResource(WeblibResource, MongoResource): class Meta: async def create(self, **kwargs): ''' Override the create method to add the user's id to the request data ''' pass
3
1
3
0
2
1
1
0.25
2
1
0
0
1
0
1
73
10
1
8
7
5
2
8
7
5
1
6
0
1
824
475Cumulus/TBone
475Cumulus_TBone/examples/chatrooms/backend/resources.py
resources.RoomResource
class RoomResource(WeblibResource, MongoResource): class Meta: object_class = Room authentication = UserAuthentication() async def create(self, **kwargs): self.data['owner'] = self.request['user'] return await super(RoomResource, self).create(**kwargs) @classmethod def nested_routes(cls, base_url, formatter: callable = None) -> list: if formatter is None or callable(formatter) is False: formatter = cls.route_param return [ Route( path=base_url + '%s/entry/' % (formatter('pk')), handler=cls.dispatch_entries_list, methods=cls.route_methods(), name='dispatch_entries_list') ] # @classmethod async def dispatch_entries_list(cls, request, **kwargs): entry_resource = EntryResource(request=request) room_id = request.match_info.get('pk') return await entry_resource.dispatch(room=room_id) @classmethod def connect_signal_receivers(cls): ''' Override the base call to include additional nested resources ''' super(RoomResource, cls).connect_signal_receivers() EntryResource.connect_signal_receivers()
class RoomResource(WeblibResource, MongoResource): class Meta: async def create(self, **kwargs): pass @classmethod def nested_routes(cls, base_url, formatter: callable = None) -> list: pass async def dispatch_entries_list(cls, request, **kwargs): pass @classmethod def connect_signal_receivers(cls): ''' Override the base call to include additional nested resources ''' pass
8
1
5
0
5
0
1
0.08
2
3
1
0
2
0
4
76
32
4
26
12
18
2
18
10
12
2
6
1
5
825
475Cumulus/TBone
475Cumulus_TBone/examples/chatrooms/backend/resources.py
resources.UserAuthentication
class UserAuthentication(NoAuthentication): async def is_authenticated(self, request): if 'user' in request: return True if 'Authorization' in request.headers: bearer, username = request.headers['Authorization'].split(' ') user = await User.find_one(request.app.db, {'username': username}) if user: request['user'] = user return True return False
class UserAuthentication(NoAuthentication): async def is_authenticated(self, request): pass
2
0
11
1
10
0
4
0
1
1
1
0
1
0
1
2
12
1
11
4
9
0
11
4
9
4
2
2
4
826
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/composite.py
tbone.data.fields.composite.DictField
class DictField(CompositeField): _data_type = dict _python_type = dict def __init__(self, field, **kwargs): super(DictField, self).__init__(**kwargs) # the provided field can be a field class or field instance if isinstance(field, FieldMeta): # a field type was passed self.field = field() elif isinstance(field, BaseField): # an instance of field was passed self.field = field else: raise TypeError("'{}' is not a field or type of field".format( field.__class__.__qualname__)) def _export(self, associative): if associative is None: return None if not isinstance(associative, dict): raise ValueError('Data is not of type dict') data = {} for key, value in associative.items(): data[key] = self.field.to_data(value) return data def _import(self, associative): if associative is None: return None if not isinstance(associative, dict): raise ValueError('Data is not of type dict') data = {} for key, value in associative.items(): data[key] = self.field.to_python(value) return data async def serialize(self, associative: dict, native=False) -> dict: if associative is None: return None if not isinstance(associative, dict): raise ValueError('Data is not of type dict') tasks = {} for key, value in associative.items(): tasks[key] = self.field.serialize(value) async def mark(key, future): return key, await future return { key: result for key, result in await asyncio.gather( *(mark(key, future) for key, future in tasks.items()) ) }
class DictField(CompositeField): def __init__(self, field, **kwargs): pass def _export(self, associative): pass def _import(self, associative): pass async def serialize(self, associative: dict, native=False) -> dict: pass async def mark(key, future): pass
6
0
11
2
9
1
3
0.07
1
4
0
0
4
1
4
36
59
12
46
15
40
3
38
15
32
4
5
1
16
827
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/composite.py
tbone.data.fields.composite.ListField
class ListField(CompositeField): _data_type = list _python_type = list def __init__(self, field, min_size=None, max_size=None, **kwargs): super(ListField, self).__init__(**kwargs) self.min_size = min_size self.max_size = max_size # the provided field can be a field class or field instance if isinstance(field, FieldMeta): # a field type was passed self.field = field() elif isinstance(field, BaseField): # an instance of field was passed self.field = field elif isinstance(field, ModelMeta): # we're being nice raise TypeError('To define a list of models, use ListField(ModelField(...))') else: raise TypeError("'{}' is not a field or type of field".format( field.__class__.__qualname__)) def _import(self, value_list): if value_list is None: return None if not isinstance(value_list, list): raise ValueError('Data is not of type list') data = [] for value in value_list: data.append(self.field.to_python(value)) return data def _export(self, value_list): if value_list is None: return None if not isinstance(value_list, list): raise ValueError('Data is not of type list') data = [] for value in value_list: data.append(self.field.to_data(value)) return data async def serialize(self, value_list: list, native=False) -> list: if value_list is None: return None if not isinstance(value_list, list): raise ValueError('Data is not of type list') futures = [] for value in value_list: futures.append(self.field.serialize(value)) return await asyncio.gather(*futures)
class ListField(CompositeField): def __init__(self, field, min_size=None, max_size=None, **kwargs): pass def _import(self, value_list): pass def _export(self, value_list): pass async def serialize(self, value_list: list, native=False) -> list: pass
5
0
11
1
10
1
4
0.09
1
5
1
0
4
3
4
36
50
6
43
16
38
4
39
16
34
4
5
1
16
828
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/composite.py
tbone.data.fields.composite.ModelField
class ModelField(CompositeField): ''' A field that can hold an instance of the specified model ''' _data_type = dict def __init__(self, model_class, **kwargs): super(ModelField, self).__init__(**kwargs) if isinstance(model_class, ModelMeta): self._model_class = model_class else: raise TypeError( "ModelField: Expected a model of the type '{}'.".format(model_class.__name__)) def __repr__(self): return '<%s instance of type %s>' % (self.__class__.__qualname__, self._python_type.__name__) @property def _python_type(self): return self._model_class @property def fields(self): return self.model_class.fields def to_python(self, value): # create a model instance from data instance = super(ModelField, self).to_python(value) if instance is None: return None return instance.export_data(native=True) def _import(self, value): if isinstance(value, self._python_type): return value elif isinstance(value, dict): return self._python_type(value) elif value is None: # no data was passed return None else: raise ValueError('Cannot convert type {} to {}'.format( type(value), self._python_type.__name__)) def _export(self, value): if isinstance(value, self._python_type): return value.export_data(native=False) elif isinstance(value, dict): return self._python_type(value).export_data(native=False) elif value is None: # no data was passed return None else: raise ValueError('Cannot convert type {} to {}'.format( type(value), self._python_type.__name__)) async def serialize(self, value, native=False): # create a model instance from data instance = super(ModelField, self).to_python(value) if instance is None: return None # return the model's serialization dd = await instance.serialize(native) return dd
class ModelField(CompositeField): ''' A field that can hold an instance of the specified model ''' def __init__(self, model_class, **kwargs): pass def __repr__(self): pass @property def _python_type(self): pass @property def fields(self): pass def to_python(self, value): pass def _import(self, value): pass def _export(self, value): pass async def serialize(self, value, native=False): pass
11
1
6
0
6
1
2
0.17
1
5
1
0
8
1
8
40
62
8
48
16
37
8
36
14
27
4
5
1
17
829
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/composite.py
tbone.data.fields.composite.PolyModelField
class PolyModelField(CompositeField): ''' A field that can hold an instance of the one of the specified models ''' _data_type = dict def __init__(self, model_classes, **kwargs): super(PolyModelField, self).__init__(**kwargs) if isinstance(model_classes, ModelMeta): self._model_classes = (model_classes,) elif isinstance(model_classes, Iterable): self._model_classes = {model.__name__: model for model in model_classes} else: raise TypeError("PolyModelField: Expected a model of the type '{}'.".format( self._model_classes.keys())) @property def _python_type(self): return tuple(self._model_classes.values()) def _export(self, value): # TODO: use if isinstance(value, self._python_type) to allow inheritance if value is None: return None elif value.__class__ in self._python_type: return{ 'type': type(value).__name__, 'data': value.export_data(native=False) } else: raise ValueError('Cannot convert type {} to on of the types in {}'.format( type(value), self._python_type)) def _import(self, value): if isinstance(value, self._python_type): return value elif isinstance(value, dict): model_class = self._model_classes[value['type']] return model_class(value['data']) elif value is None: # no data was passed return None else: raise ValueError('Cannot convert type {} to {}'.format( type(value), self._python_type.__name__))
class PolyModelField(CompositeField): ''' A field that can hold an instance of the one of the specified models ''' def __init__(self, model_classes, **kwargs): pass @property def _python_type(self): pass def _export(self, value): pass def _import(self, value): pass
6
1
9
0
8
1
3
0.14
1
6
1
0
4
1
4
36
44
4
36
9
30
5
22
8
17
4
5
1
11
830
475Cumulus/TBone
475Cumulus_TBone/examples/chatrooms/backend/resources.py
resources.UserResource
class UserResource(WeblibResource, MongoResource): class Meta: object_class = User async def create(self, **kwargs): if 'avatar' not in self.data: self.data['avatar'] = 'https://randomuser.me/api/portraits/lego/{}.jpg'.format(randint(0, 8)) return await super(UserResource, self).create(**kwargs)
class UserResource(WeblibResource, MongoResource): class Meta: async def create(self, **kwargs): pass
3
0
4
0
4
0
2
0
2
1
0
0
1
0
1
73
8
1
7
4
4
0
7
4
4
2
6
1
2
831
475Cumulus/TBone
475Cumulus_TBone/examples/snippets/sanic_resource_hookup.py
sanic_resource_hookup.TestResource
class TestResource(SanicResource, Resource): async def list(self, **kwargs): return { 'meta': {}, 'objects': [ {'text': 'hello world'} ] }
class TestResource(SanicResource, Resource): async def list(self, **kwargs): pass
2
0
7
0
7
0
1
0
2
0
0
0
1
0
1
58
8
0
8
2
6
0
3
2
1
1
4
0
1
832
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/base.py
tbone.data.fields.base.BaseField
class BaseField(object, metaclass=FieldMeta): ''' Base class for all fields in TBone models. Added to subclasses of ``Model`` to define the model's schema. :param required: Invalidates the field of no data is provided. Default: None :param default: Provides a default value when none is provided. Can be a callable Default: None :param choices: Used to limit a field's choices of value. Requires a list of acceptable values. If not ``None`` validates the value against a the provided list. :param validators: An optional list of validator functions. Requires a list of calllables. Used for validation functions which are not implemented as internal ``Field`` methods :param projection: Determines if the field is serialized by the model using the model's ``serialize`` methods. Useful when specific control over the model serialization is required. Acceptable values are ``True``, ``False`` and ``None``. Using ``True`` implies the field will always be serialized Using ``False`` implies the field will be serialized only if the value is not ``None`` Using ``None`` implies the field will never be serialized :param export_if_none: Determines if the field will be included in model ``export_data`` methods. The ``MongoCollectionMixin`` uses this field attribute to determine if the field should be saved to the database when its null Default: True :param readonly: Determines if the field can be overriden using the ``deserialize`` method. Has no effect on direct data manipulation :param primary_key: Declares the field as the model's primary key. Only one field can be declared like so. This declaration has no impact on the datastore, and is used by the ``Resource`` class as the model's identifier. If the model is also mixed with a persistency class, it would make sense that the field which is defined as the primary key may also be indexed as unique ''' _data_type = None _python_type = None ERRORS = { 'required': '{} {} is a required field', 'required_extra': ' in model {}', 'to_data': 'Cannot coerce data to primitive form', 'to_python': 'Cannot corece data to python type', 'choices': 'Value must be one of [{0}] in field {1}', } def __init__(self, required=False, default=None, choices=None, validators=None, projection=True, export_if_none=True, readonly=False, primary_key=False, **kwargs): super(BaseField, self).__init__() self._required = required self._default = default self._choices = choices self._projection = Ternary(projection) self._export_if_none = export_if_none self._readonly = readonly self._primary_key = primary_key self._bound = False # Whether the Field is bound to a Model self._is_composite = False if required and default is not None: raise AttributeError('Required and default cannot co-exist') # accumulate all validators to a single list self.validators = [getattr(self, name) for name in self._validators] if isinstance(validators, list): for validator in validators: if callable(validator): self.validators.append(validator) @property def is_composite(self): return self._is_composite @property def name(self): if hasattr(self, '_name'): return self._name return 'Unknown' @property def container_model(self): if hasattr(self, '_container_model_class'): return self._container_model_class return None def _export(self, value): ''' Coerce the input data to primitive form Override in sub classes to add specialized behavior ''' if value is None: return None return self._data_type(value) def _import(self, value): ''' Imports field data and coerce to the field's python type. Overrride in sub classes to add specialized behavior ''' if value is None: return None return self._python_type(value) def _check_required(self, value): ''' Internal method to check if assigned value is None while it is required. Exception is thrown if ``True`` ''' if value is None and self._required: err_msg = self._errors['required'].format(self.__class__.__name__, self.name) if self.container_model: err_msg += self._errors['required_extra'].format(self.container_model.__name__) raise ValueError(err_msg) def to_data(self, value): ''' Coerce python data type to simple form for serialization. If default value was defined returns the default value if None was passed. Throw exception is value is ``None`` is ``required`` is set to ``True`` ''' try: if value is None and self._default is not None: return self._export(self.default) self._check_required(value) value = self._export(value) return value except ValueError as ex: raise ValueError(ex, self._errors['to_data']) def to_python(self, value): ''' Coerce data from primitive form to native Python types. Returns the default type (if exists) ''' try: if value is None and self._default is not None: return self.default self._check_required(value) if not isinstance(value, self._python_type): value = self._import(value) return value except ValueError as ex: raise ValueError(ex, self._errors['to_python']) async def serialize(self, value, native=False): ''' Calls the field's ``to_python`` method. Override in derived classes of fields which involve models, such as ``ModelField`` ''' if native: return self.to_python(value) return self.to_data(value) def __call__(self, value): return self.to_python(value) def __repr__(self): if self._bound: return '<%s instance in model %s>' % (self.__class__.__qualname__, self.container_model.__name__) return '<%s instance>' % self.__class__.__qualname__ @property def default(self): default = self._default if callable(default): default = default() return default def add_to_class(self, cls, name): ''' Hook that replaces the `Field` attribute on a class with a named ``FieldDescriptor``. Called by the metaclass during construction of the ``Model``. ''' self._name = name self._container_model_class = cls setattr(cls, name, FieldDescriptor(self)) self._bound = True def validate(self, value): ''' Run all validate functions pertaining to this field and raise exceptions. ''' for validator in self.validators: validator(value) @validator def choices(self, value): if self._choices: if value not in self._choices and value is not None: raise ValueError( self._errors['choices'].format( ', '.join([str(x) for x in self._choices]), getattr(self, 'name', None) ) )
class BaseField(object, metaclass=FieldMeta): ''' Base class for all fields in TBone models. Added to subclasses of ``Model`` to define the model's schema. :param required: Invalidates the field of no data is provided. Default: None :param default: Provides a default value when none is provided. Can be a callable Default: None :param choices: Used to limit a field's choices of value. Requires a list of acceptable values. If not ``None`` validates the value against a the provided list. :param validators: An optional list of validator functions. Requires a list of calllables. Used for validation functions which are not implemented as internal ``Field`` methods :param projection: Determines if the field is serialized by the model using the model's ``serialize`` methods. Useful when specific control over the model serialization is required. Acceptable values are ``True``, ``False`` and ``None``. Using ``True`` implies the field will always be serialized Using ``False`` implies the field will be serialized only if the value is not ``None`` Using ``None`` implies the field will never be serialized :param export_if_none: Determines if the field will be included in model ``export_data`` methods. The ``MongoCollectionMixin`` uses this field attribute to determine if the field should be saved to the database when its null Default: True :param readonly: Determines if the field can be overriden using the ``deserialize`` method. Has no effect on direct data manipulation :param primary_key: Declares the field as the model's primary key. Only one field can be declared like so. This declaration has no impact on the datastore, and is used by the ``Resource`` class as the model's identifier. If the model is also mixed with a persistency class, it would make sense that the field which is defined as the primary key may also be indexed as unique ''' def __init__(self, required=False, default=None, choices=None, validators=None, projection=True, export_if_none=True, readonly=False, primary_key=False, **kwargs): pass @property def is_composite(self): pass @property def name(self): pass @property def container_model(self): pass def _export(self, value): ''' Coerce the input data to primitive form Override in sub classes to add specialized behavior ''' pass def _import(self, value): ''' Imports field data and coerce to the field's python type. Overrride in sub classes to add specialized behavior ''' pass def _check_required(self, value): ''' Internal method to check if assigned value is None while it is required. Exception is thrown if ``True`` ''' pass def to_data(self, value): ''' Coerce python data type to simple form for serialization. If default value was defined returns the default value if None was passed. Throw exception is value is ``None`` is ``required`` is set to ``True`` ''' pass def to_python(self, value): ''' Coerce data from primitive form to native Python types. Returns the default type (if exists) ''' pass async def serialize(self, value, native=False): ''' Calls the field's ``to_python`` method. Override in derived classes of fields which involve models, such as ``ModelField`` ''' pass def __call__(self, value): pass def __repr__(self): pass @property def default(self): pass def add_to_class(self, cls, name): ''' Hook that replaces the `Field` attribute on a class with a named ``FieldDescriptor``. Called by the metaclass during construction of the ``Model``. ''' pass def validate(self, value): ''' Run all validate functions pertaining to this field and raise exceptions. ''' pass @validator def choices(self, value): pass
22
9
8
0
6
2
2
0.65
2
7
2
6
16
12
16
31
209
30
109
45
85
71
92
36
75
5
3
3
37
833
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/base.py
tbone.data.fields.base.FieldDescriptor
class FieldDescriptor(object): ''' ``FieldDescriptor`` for exposing fields to allow access to the underlying data ''' def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is not None: if self.field.name == 'participants': import pdb; pdb.set_trace() return instance._data.get(self.field.name, None) or self.field.default return self.field def __set__(self, instance, value): instance._data[self.field.name] = value def __delete__(self, instance): del instance._data[self.name]
class FieldDescriptor(object): ''' ``FieldDescriptor`` for exposing fields to allow access to the underlying data ''' def __init__(self, field): pass def __get__(self, instance, owner): pass def __set__(self, instance, value): pass def __delete__(self, instance): pass
5
1
3
0
3
0
2
0.23
1
0
0
0
4
1
4
4
20
4
13
7
8
3
14
7
8
3
1
2
6
834
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/composite.py
tbone.data.fields.composite.CompositeField
class CompositeField(BaseField): ''' Base class for fields which accept another field as parameter ''' def __init__(self, **kwargs): super(CompositeField, self).__init__(**kwargs) self._is_composite = True
class CompositeField(BaseField): ''' Base class for fields which accept another field as parameter ''' def __init__(self, **kwargs): pass
2
1
3
0
3
0
1
0.75
1
1
0
5
1
1
1
32
8
1
4
3
2
3
4
3
2
1
4
0
1
835
475Cumulus/TBone
475Cumulus_TBone/tbone/testing/clients.py
tbone.testing.clients.WebsocketResourceTestClient
class WebsocketResourceTestClient(ResourceTestClient): protocol = Resource.Protocol.websocket
class WebsocketResourceTestClient(ResourceTestClient): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
2
0
2
2
1
0
2
2
1
0
2
0
0
836
475Cumulus/TBone
475Cumulus_TBone/tbone/dispatch/carriers/sanic_websocket.py
tbone.dispatch.carriers.sanic_websocket.SanicWebSocketCarrier
class SanicWebSocketCarrier(object): def __init__(self, websocket): self._socket = websocket async def deliver(self, data): try: if isinstance(data, dict): payload = json.dumps(data, cls=ExtendedJSONEncoder) elif isinstance(data, bytes): payload = data.decode('utf-8') else: payload = data await self._socket.send(payload) return True except Exception as ex: logger.exception(ex) return False
class SanicWebSocketCarrier(object): def __init__(self, websocket): pass async def deliver(self, data): pass
3
0
8
0
8
0
3
0
1
4
1
0
2
1
2
2
18
2
16
6
13
0
14
5
11
4
1
2
5
837
475Cumulus/TBone
475Cumulus_TBone/tbone/testing/__init__.py
tbone.testing.Request
class Request(dict): __slots__ = ( 'app', 'headers', 'method', 'body', 'args', 'url', 'user' ) def __init__(self, app, url, method, headers, args, body): self.app = app self.method = method self.args = args self.headers = headers self.body = body self.args = args
class Request(dict): def __init__(self, app, url, method, headers, args, body): pass
2
0
7
0
7
0
1
0
1
0
0
0
1
5
1
28
12
1
11
8
9
0
9
8
7
1
2
0
1
838
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_fields.py
tests.data.test_fields.test_default.M
class M(Model): number = IntegerField(default=5)
class M(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
2
0
2
2
1
0
2
2
1
0
4
0
0
839
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_poly_model_field.Product
class Product(Model): sku = StringField(required=True) media = PolyModelField([Book, Film], required=True)
class Product(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
3
0
3
3
2
0
3
3
2
0
4
0
0
840
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_poly_model_field.Film
class Film(Model): title = StringField() director = StringField() actors = ListField(StringField)
class Film(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
4
0
4
4
3
0
4
4
3
0
4
0
0
841
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_poly_model_field.Book
class Book(Model): title = StringField() author = StringField() number_of_pages = IntegerField()
class Book(Model): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
30
4
0
4
4
3
0
4
4
3
0
4
0
0
842
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_poly_model_field.AnotherBook
class AnotherBook(Book): pass
class AnotherBook(Book): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
2
0
2
1
1
0
2
1
1
0
5
0
0
843
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_nested_model_serialization.Trip
class Trip(Model): participants = ListField(ModelField(Person), default=[]) destination = StringField(required=True) date = DateTimeField(required=True)
class Trip(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
4
0
4
4
3
0
4
4
3
0
4
0
0
844
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_nested_model_serialization.Person
class Person(Model): '''Model for holding a person's name with serialization for full name only ''' first_name = StringField(required=True, projection=None) last_name = StringField(required=True, projection=None) @serialize async def full_name(self): return '{} {}'.format(self.first_name, self.last_name)
class Person(Model): '''Model for holding a person's name with serialization for full name only ''' @serialize async def full_name(self): pass
3
1
2
0
2
0
1
0.17
1
0
0
0
1
0
1
31
8
1
6
5
3
1
5
4
3
1
4
0
1
845
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_nested_model_serialization.Journey
class Journey(Model): participants = DictField(ModelField(Person), default={}) destination = StringField(required=True) date = DateTimeField(required=True)
class Journey(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
4
0
4
4
3
0
4
4
3
0
4
0
0
846
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_model_field_complete.Person
class Person(Model): first_name = StringField(required=True) last_name = StringField(required=True)
class Person(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
3
0
3
3
2
0
3
3
2
0
4
0
0
847
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_model_field_complete.Book
class Book(Model): title = StringField(required=True) isbn = StringField() author = ModelField(Person) language = StringField(choices=['en', 'de', 'fr']) publication_date = DateField()
class Book(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
6
0
6
6
5
0
6
6
5
0
4
0
0
848
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_model_field.Comment
class Comment(Model): text = StringField() ts = DateTimeField(default=datetime.datetime.utcnow)
class Comment(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
3
0
3
3
2
0
3
3
2
0
4
0
0
849
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_list_of_models.Comment
class Comment(Model): text = StringField()
class Comment(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
2
0
2
2
1
0
2
2
1
0
4
0
0
850
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_composite_fields.py
tests.data.test_composite_fields.test_list_field.M
class M(Model): numbers = ListField(StringField, required=True)
class M(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
2
0
2
2
1
0
2
2
1
0
4
0
0
851
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tbone/resources/resources.py
tbone.resources.resources.ResourceMeta
class ResourceMeta(type): @classmethod def __prepare__(mcl, name, bases): ''' Adds the signal decorator so member methods can be decorated as signal receivers ''' def receiver(signal): def _receiver(func): func._signal_receiver_ = signal @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return _receiver d = dict() d['receiver'] = receiver return d def __new__(mcl, name, bases, attrs): attrs.pop('receiver', None) cls = super(ResourceMeta, mcl).__new__(mcl, name, bases, attrs) # create default resource options options = ResourceOptions() # copy over resource options defined in base classes, if any for base in reversed(bases): if not hasattr(base, '_meta'): continue options.__dict__.update(base._meta.__dict__) # copy resource options defined in this resource, if any if hasattr(cls, 'Meta'): for attr in dir(cls.Meta): if not attr.startswith('_'): setattr(options, attr, getattr(cls.Meta, attr)) # create the combined resource options class cls._meta = ResourceOptions(options) return cls
class ResourceMeta(type): @classmethod def __prepare__(mcl, name, bases): ''' Adds the signal decorator so member methods can be decorated as signal receivers ''' pass def receiver(signal): pass def _receiver(func): pass @wraps(func) def wrapper(*args, **kwargs): pass def __new__(mcl, name, bases, attrs): pass
8
1
11
2
8
1
2
0.18
1
4
1
1
1
0
2
15
39
6
28
13
20
5
26
11
20
6
2
3
10
852
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tbone/resources/resources.py
tbone.resources.resources.Resource.Protocol
class Protocol(Enum): http = 10 websocket = 20 amqp = 30
class Protocol(Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
4
0
4
4
3
0
4
4
3
0
4
0
0
853
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tbone/resources/mongo.py
tbone.resources.mongo.MongoResource.Meta
class Meta: channel_class = MongoChannel
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
854
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tbone/resources/mongo.py
tbone.resources.mongo.MongoResource
class MongoResource(ModelResource): ''' A specialized ``Resource`` subclass used for creating API endpoints coupled to a MongoDB collection. Provides basic CRUD operations using standard HTTP verbs. ''' class Meta: channel_class = MongoChannel @property def limit(self): return LIMIT @property def offset(self): return OFFSET @classmethod async def emit(cls, db, key, data): pubsub = cls._meta.channel_class(name='pubsub', db=db) await pubsub.publish(key, data) # ---------- receivers ------------ # @classmethod @receiver(post_save) async def post_save(cls, sender, db, instance, created): if instance.pk is None: return async def _emit(event_name): resource = cls() obj = await instance.serialize() if cls._meta.hypermedia is True: resource.add_hypermedia(obj) await resource.emit(db, event_name, obj) if created is True and 'created' in cls._meta.outgoing_detail: await _emit('resource_create') elif created is False and 'updated' in cls._meta.outgoing_detail: await _emit('resource_update') @classmethod @receiver(resource_post_list) async def post_list(cls, sender, db, instances): ''' Hook to capture the results of a list query. Useful when wanting to know when certain documents have come up in a query. Implement in resource subclasses to provide domain-specific behavior ''' serialized_objects = await asyncio.gather(*[obj.serialize() for obj in instances]) await cls.emit(db, 'resource_get_list', serialized_objects) # ------------- resource overrides ---------------- # async def list(self, *args, **kwargs): ''' Corresponds to GET request without a resource identifier, fetching documents from the database ''' limit = int(kwargs.pop('limit', self.limit)) limit = 1000 if limit == 0 else limit # lets not go crazy here offset = int(kwargs.pop('offset', self.offset)) projection = None # perform full text search or standard filtering if self._meta.fts_operator in kwargs.keys(): filters = { '$text': {'$search': kwargs[self._meta.fts_operator]} } projection = {'score': {'$meta': 'textScore'}} sort = [('score', {'$meta': 'textScore'}, )] else: # build filters from query parameters filters = self.build_filters(**kwargs) # add custom query defined in resource meta, if exists if isinstance(self._meta.query, dict): filters.update(self._meta.query) # build sorts from query parameters sort = self.build_sort(**kwargs) if isinstance(self._meta.sort, list): sort.extend(self._meta.sort) cursor = self._meta.object_class.get_cursor( db=self.db, query=filters, projection=projection, sort=sort) cursor.skip(offset) cursor.limit(limit) total_count = await self._meta.object_class.count(db=self.db, filters=filters) object_list = await self._meta.object_class.find(cursor) # serialize results serialized_objects = await asyncio.gather(*[obj.serialize() for obj in object_list]) # signal post list asyncio.ensure_future(resource_post_list.send( sender=self._meta.object_class, db=self.db, instances=object_list) ) return { 'meta': { 'total_count': total_count, 'limit': limit, 'offset': offset }, 'objects': serialized_objects } async def detail(self, **kwargs): ''' Corresponds to GET request with a resource unique identifier, fetching a single document from the database ''' try: pk = self.pk_type(kwargs.get('pk')) obj = await self._meta.object_class.find_one(self.db, {self.pk: pk}) if obj: return await obj.serialize() raise NotFound('Object matching the given {} with value {} was not found'.format( self.pk, str(pk))) except InvalidId: raise NotFound('Invalid ID') async def create(self, **kwargs): ''' Corresponds to POST request without a resource identifier, inserting a document into the database ''' try: # create model obj = self._meta.object_class() # deserialize data from request body self.data.update(kwargs) await obj.deserialize(self.data) # create document in DB await obj.insert(db=self.db) # serialize object for response return await obj.serialize() except Exception as ex: logger.exception(ex) raise BadRequest(ex) async def modify(self, **kwargs): ''' Corresponds to PATCH request with a resource identifier, modifying a single document in the database ''' try: pk = self.pk_type(kwargs['pk']) # modify is a class method on MongoCollectionMixin result = await self._meta.object_class.modify(self.db, key=pk, data=self.data) if result is None: raise NotFound( 'Object matching the given {} was not found'.format(self.pk)) return await result.serialize() except Exception as ex: logger.exception(ex) raise BadRequest(ex) async def update(self, **kwargs): ''' Corresponds to PUT request with a resource identifier, updating a single document in the database ''' try: self.data[self.pk] = self.pk_type(kwargs['pk']) updated_obj = await self._meta.object_class().update(self.db, data=self.data) if updated_obj is None: raise NotFound( 'Object matching the given {} was not found'.format(self.pk)) return await updated_obj.serialize() except Exception as ex: logger.exception(ex) raise BadRequest(ex) async def delete(self, *args, **kwargs): ''' Corresponds to DELETE request with a resource identifier, deleting a single document from the database ''' pk = self.pk_type(kwargs['pk']) result = await self._meta.object_class.delete_entries(db=self.db, query={self.pk: pk}) if result.acknowledged: if result.deleted_count == 0: raise NotFound() else: raise BadRequest('Failed to delete object') def build_filters(self, **kwargs): ''' Break url parameters and turn into filters ''' filters = {} for param, value in kwargs.items(): # break each url parameter to key + operator (if exists) pl = dict(enumerate(param.split('__'))) key = pl[0] operator = pl.get(1, None) if key in self._meta.object_class.fields(): field = self._meta.object_class._fields[key] if field.is_composite: # composite keys require additional handling # currently covering cases for dbref and list if isinstance(field, DBRefField): key, value = self.process_dbref_filter(key, value) elif isinstance(value, list) and operator == 'in': value = [convert_value(v) for v in value] else: value = convert_value(value) # assign operator, if applicable filters[key] = {'${}'.format( operator): value} if operator else value elif key == 'created': # special case where we map `created` key to mongo's _id which also contains a creation timestamp dt = parser.parse(convert_value(value)) dummy_id = ObjectId.from_datetime(dt) filters['_id'] = {'${}'.format( operator): dummy_id} if operator else dummy_id return filters def process_dbref_filter(self, key, value): k = '{}.$id'.format(key) if isinstance(value, MongoCollectionMixin): v = value._id else: v = ObjectId(value) return k, v def build_sort(self, **kwargs): ''' Break url parameters and turn into sort arguments ''' sort = [] order = kwargs.get('order_by', None) if order: if type(order) is list: order = order[0] if order[:1] == '-': sort.append((order[1:], -1)) else: sort.append((order, 1)) return sort
class MongoResource(ModelResource): ''' A specialized ``Resource`` subclass used for creating API endpoints coupled to a MongoDB collection. Provides basic CRUD operations using standard HTTP verbs. ''' class Meta: @property def limit(self): pass @property def offset(self): pass @classmethod async def emit(cls, db, key, data): pass @classmethod @receiver(post_save) async def post_save(cls, sender, db, instance, created): pass async def _emit(event_name): pass @classmethod @receiver(resource_post_list) async def post_list(cls, sender, db, instances): ''' Hook to capture the results of a list query. Useful when wanting to know when certain documents have come up in a query. Implement in resource subclasses to provide domain-specific behavior ''' pass async def list(self, *args, **kwargs): ''' Corresponds to GET request without a resource identifier, fetching documents from the database ''' pass async def detail(self, **kwargs): ''' Corresponds to GET request with a resource unique identifier, fetching a single document from the database ''' pass async def create(self, **kwargs): ''' Corresponds to POST request without a resource identifier, inserting a document into the database ''' pass async def modify(self, **kwargs): ''' Corresponds to PATCH request with a resource identifier, modifying a single document in the database ''' pass async def update(self, **kwargs): ''' Corresponds to PUT request with a resource identifier, updating a single document in the database ''' pass async def delete(self, *args, **kwargs): ''' Corresponds to DELETE request with a resource identifier, deleting a single document from the database ''' pass def build_filters(self, **kwargs): ''' Break url parameters and turn into filters ''' pass def process_dbref_filter(self, key, value): pass def build_sort(self, **kwargs): ''' Break url parameters and turn into sort arguments ''' pass
24
10
13
0
10
3
3
0.31
1
10
4
7
11
1
14
67
219
18
156
59
132
48
128
51
111
9
5
4
44
855
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tbone/data/models.py
tbone.data.models.ModelMeta
class ModelMeta(type): '''Metaclass for Model''' @classmethod def __prepare__(mcl, name, bases): ''' Adds the ``serialize`` decorator so member methods can be decorated for serialization ''' def serialize(func): func._serialize_method_ = True @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper d = dict() d['serialize'] = serialize return d def __new__(mcl, name, bases, attrs): del attrs['serialize'] fields = OrderedDict() serialize_methods = OrderedDict() # get model fields and exports from base classes for base in reversed(bases): if hasattr(base, '_fields'): fields.update(deepcopy(base._fields)) # copy all fields # remove excludes if 'Meta' in attrs and hasattr(attrs['Meta'], 'exclude_fields'): ex = attrs['Meta'].exclude_fields for f in ex: if f in fields: del fields[f] if hasattr(base, '_serialize_methods'): serialize_methods.update(deepcopy(base._serialize_methods)) # remove excludes if 'Meta' in attrs and hasattr(attrs['Meta'], 'exclude_serialize'): ex = attrs['Meta'].exclude_serialize for f in ex: if f in serialize_methods: del serialize_methods[f] # collect all defined fields and export methods for key, value in attrs.items(): if hasattr(value, '_serialize_method_'): serialize_methods[key] = value if isinstance(value, BaseField): fields[key] = value attrs['_fields'] = fields attrs['_serialize_methods'] = serialize_methods # create class cls = super(ModelMeta, mcl).__new__(mcl, name, bases, attrs) # apply field descriptors for name, field in fields.items(): field.add_to_class(cls, name) if field._primary_key: # assign primary key information cls.primary_key = field.name cls.primary_key_type = field._python_type # add model options opts = getattr(cls, 'Meta', None) cls._meta = ModelOptions(opts) return cls
class ModelMeta(type): '''Metaclass for Model''' @classmethod def __prepare__(mcl, name, bases): ''' Adds the ``serialize`` decorator so member methods can be decorated for serialization ''' pass def serialize(func): pass @wraps(func) def wrapper(*args, **kwargs): pass def __new__(mcl, name, bases, attrs): pass
7
2
19
3
13
3
5
0.23
1
6
2
1
1
0
2
15
68
11
47
17
40
11
45
15
40
15
2
5
18
856
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tbone/data/fields/base.py
tbone.data.fields.base.FieldMeta
class FieldMeta(type): ''' Meta class for BaseField. Accumulated error messages and validator methods ''' @classmethod def __prepare__(mcl, name, bases): ''' Adds the validator decorator so member methods can be decorated as validation methods ''' def validator(func): func._validation_method_ = True @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper d = dict() d['validator'] = validator return d def __new__(mcl, name, bases, attrs): del attrs['validator'] errors = {} validators = OrderedDict() # accumulate errors and validators from base classes for base in reversed(bases): if hasattr(base, '_errors'): errors.update(base._errors) if hasattr(base, '_validators'): validators.update(base._validators) if 'ERRORS' in attrs: errors.update(attrs['ERRORS']) # store commined error messages of all field class and its bases attrs['_errors'] = errors # store validators - locate member methods which are decorated as validator functions for key, attr in attrs.items(): if getattr(attr, '_validation_method_', None): validators[key] = attr attrs['_validators'] = validators return super(FieldMeta, mcl).__new__(mcl, name, bases, attrs)
class FieldMeta(type): ''' Meta class for BaseField. Accumulated error messages and validator methods ''' @classmethod def __prepare__(mcl, name, bases): ''' Adds the validator decorator so member methods can be decorated as validation methods ''' pass def validator(func): pass @wraps(func) def wrapper(*args, **kwargs): pass def __new__(mcl, name, bases, attrs): pass
7
2
12
2
9
1
3
0.24
1
4
0
1
1
0
2
15
44
8
29
12
22
7
27
10
22
7
2
2
10
857
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_fields.py
tests.data.test_fields.test_field_meta.SomeField
class SomeField(BaseField): ERRORS = { 'first': 'First Error' }
class SomeField(BaseField): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
2
3
0
2
2
1
0
1
0
0
858
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.UserResource.Meta
class Meta: object_class = User
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
859
475Cumulus/TBone
475Cumulus_TBone/tbone/data/fields/simple.py
tbone.data.fields.simple.DTBaseField
class DTBaseField(BaseField): ''' Base field for all fields related to date and time ''' _data_type = str def to_data(self, value): if value is None: if self._default is not None: value = self.default return None return value.isoformat() def _import(self, value): if value is None: return None elif isinstance(value, self._python_type) or isinstance(value, datetime.datetime): return value elif isinstance(value, str): return dateutil.parser.parse(value) raise ValueError('{0} Unacceptable type for {1} field'.format(value.__class__.__name__, self._python_type.__name__))
class DTBaseField(BaseField): ''' Base field for all fields related to date and time ''' def to_data(self, value): pass def _import(self, value): pass
3
1
7
0
7
0
4
0.06
1
3
0
3
2
0
2
33
19
2
16
4
13
1
14
4
11
4
4
2
7
860
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_models.py
tests.data.test_models.test_field_projection.M
class M(Model): first_name = StringField() last_name = StringField() dob = DateTimeField() number_of_views = IntegerField(default=0, projection=None)
class M(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
5
0
5
5
4
0
5
5
4
0
4
0
0
861
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/resources/test_resources.py
tests.resources.test_resources.test_resource_without_hateoas.NoHPersonResource.Meta
class Meta: hypermedia = False
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
862
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/resources/test_mongo_resources.py
tests.resources.test_mongo_resources.test_mongo_collection_with_resource_defined_query.PremiumAccountResource.Meta
class Meta(AccountResource.Meta): query = {'premium': True}
class Meta(AccountResource.Meta): 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
863
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/resources/resources.py
tests.resources.resources.BookResource.Meta
class Meta: object_class = Book
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
864
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/resources/resources.py
tests.resources.resources.AccountResource.Meta
class Meta: object_class = Account
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
865
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/db/test_models.py
tests.db.test_models.test_model_name_and_namespace.M2
class M2(BaseModel): name = StringField()
class M2(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
51
2
0
2
2
1
0
2
2
1
0
5
0
0
866
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/db/test_models.py
tests.db.test_models.test_model_name_and_namespace.M.Meta
class Meta: namespace = 'kitchen' name = 'hats'
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
867
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/db/test_fields.py
tests.db.test_fields.test_dbref_field_in_list.Book
class Book(BaseModel): title = StringField() authors = ListField(DBRefField(Person))
class Book(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
51
3
0
3
3
2
0
3
3
2
0
5
0
0
868
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/db/test_fields.py
tests.db.test_fields.test_dbref_field_in_dict.Book
class Book(BaseModel): title = StringField() authors = DictField(DBRefField(Person))
class Book(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
51
3
0
3
3
2
0
3
3
2
0
5
0
0
869
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/db/test_fields.py
tests.db.test_fields.test_dbref_field.Book
class Book(BaseModel): title = StringField() author = DBRefField(Person)
class Book(BaseModel): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
51
3
0
3
3
2
0
3
3
2
0
5
0
0
870
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/db/models.py
tests.db.models.Book.Meta
class Meta: name = 'books' namespace = 'catalog' indices = [{ 'name': '_isbn', 'fields': [('isbn', ASCENDING)], 'unique': True }, { 'name': '_fts', 'fields': [ ('title', TEXT), ('author', TEXT) ] }]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
14
0
14
4
13
0
4
4
3
0
0
0
0
871
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/db/models.py
tests.db.models.BaseModel.Meta
class Meta: concrete = False
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
872
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/db/models.py
tests.db.models.Account.Meta
class Meta: name = 'accounts' indices = [ { 'fields': [('email', ASCENDING)], 'unique': True }, { 'fields': [('phone_number', ASCENDING)], 'unique': True, 'partialFilterExpression': {'phone_number': {'$ne': None}} } ]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
12
0
12
3
11
0
3
3
2
0
0
0
0
873
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_models.py
tests.data.test_models.test_model_serialize_decorator.M
class M(Model): first_name = StringField() last_name = StringField() @serialize async def full_name(self): return '{} {}'.format(self.first_name, self.last_name)
class M(Model): @serialize async def full_name(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
31
7
1
6
5
3
0
5
4
3
1
4
0
1
874
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_models.py
tests.data.test_models.test_model_repr.M
class M(Model): pass
class M(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
2
0
2
1
1
0
2
1
1
0
4
0
0
875
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_models.py
tests.data.test_models.test_model_items.M
class M(Model): first_name = StringField() last_name = StringField() dob = DateTimeField()
class M(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
4
0
4
4
3
0
4
4
3
0
4
0
0
876
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_models.py
tests.data.test_models.test_model_import.M
class M(Model): first_name = StringField() last_name = StringField()
class M(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
3
0
3
3
2
0
3
3
2
0
4
0
0
877
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_models.py
tests.data.test_models.test_model_field_exclusion.User
class User(Model): username = StringField() password = StringField() first_name = StringField() last_name = StringField() @serialize async def full_name(self): return '{} {}'.format(self.first_name, self.last_name)
class User(Model): @serialize async def full_name(self): pass
3
0
2
0
2
0
1
0
1
0
0
1
1
0
1
31
9
1
8
7
5
0
7
6
5
1
4
0
1
878
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_models.py
tests.data.test_models.test_model_field_exclusion.PublicUser.Meta
class Meta: exclude_fields = ['password', 'none_existing_field'] exclude_serialize = ['full_name', 'none_existing_serialize_method']
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
879
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_models.py
tests.data.test_models.test_model_creation_and_serialization.M
class M(Model): name = StringField() age = IntegerField() decimal = FloatField() dt = DateTimeField()
class M(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
5
0
5
5
4
0
5
5
4
0
4
0
0
880
475Cumulus/TBone
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/475Cumulus_TBone/tests/data/test_fields.py
tests.data.test_fields.test_field_projection.M
class M(Model): name = StringField(default='Ron Burgundy') number = IntegerField(projection=False) age = IntegerField(projection=None)
class M(Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
30
4
0
4
4
3
0
4
4
3
0
4
0
0
881
475Cumulus/TBone
475Cumulus_TBone/tbone/testing/clients.py
tbone.testing.clients.ResourceTestClient
class ResourceTestClient(object): ''' A test client used to perform basic http requests in a test environment on a Resource. Initialize with an app-like object and the Resource class being tested. Defaults to HTTP communication. ''' def __init__(self, app, resource_class, protocol=Resource.Protocol.http): def mix(r): # mix the resource class with a DummyResource mixin to fake the HTTP library return type(r.__name__, (DummyResource, r), {}) self._app = app self.protocol = protocol self._router = Router(name='api') self._router.register(mix(resource_class), resource_class.__name__) def __del__(self): for endpoint in self._router.endpoints(): self._router.unregister(endpoint) def parse_response_data(self, response): if isinstance(response.payload, dict): return response.payload return json.loads(response.payload) async def process_request(self, method, url, headers, args, body): handler = None # match the given url to urls in the router then activate the relevant resource for route in self._router.urls_regex(self.protocol): match = re.match(route.path, url) if match: handler = route.handler args.update(match.groupdict()) break if handler: # create dummy request object request = Request( app=self._app, method=method, url=url, args=args, headers=headers, body=body ) response = await handler(request) # if the protocol is websockets we convert the HTTP response object so the tests don't have to be written twice if self.protocol == Resource.Protocol.websocket: response = json.loads(response) return Response(headers={}, payload=response['payload'], status=response['status']) return response return Response(headers={}, data=None, status=404) async def get(self, url, headers={}, args={}, body={}): return await self.process_request('GET', url, headers, args, body) async def post(self, url, headers={}, args={}, body={}): return await self.process_request('POST', url, headers, args, body) async def put(self, url, headers={}, args={}, body={}): return await self.process_request('PUT', url, headers, args, body) async def delete(self, url, headers={}, args={}, body={}): return await self.process_request('DELETE', url, headers, args, body) async def patch(self, url, headers={}, args={}, body={}): return await self.process_request('PATCH', url, headers, args, body) async def options(self, url, headers={}, args={}, body={}): return await self.process_request('OPTIONS', url, headers, args, body) async def head(self, url, headers={}, args={}, body={}): return await self.process_request('HEAD', url, headers, args, body)
class ResourceTestClient(object): ''' A test client used to perform basic http requests in a test environment on a Resource. Initialize with an app-like object and the Resource class being tested. Defaults to HTTP communication. ''' def __init__(self, app, resource_class, protocol=Resource.Protocol.http): pass def mix(r): pass def __del__(self): pass def parse_response_data(self, response): pass async def process_request(self, method, url, headers, args, body): pass async def get(self, url, headers={}, args={}, body={}): pass async def post(self, url, headers={}, args={}, body={}): pass async def put(self, url, headers={}, args={}, body={}): pass async def delete(self, url, headers={}, args={}, body={}): pass async def patch(self, url, headers={}, args={}, body={}): pass async def options(self, url, headers={}, args={}, body={}): pass async def head(self, url, headers={}, args={}, body={}): pass
13
1
5
0
4
0
2
0.17
1
6
4
1
11
3
11
11
73
13
52
22
39
9
45
22
32
5
1
2
18
882
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.RoomResource.Meta
class Meta: object_class = Room authentication = UserAuthentication()
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
0
0
0
883
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.User.Meta
class Meta: name = 'users' indices = [ { 'name': '_username', 'fields': [('username', ASCENDING)], 'unique': True } ]
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9
0
9
3
8
0
3
3
2
0
0
0
0
884
475Cumulus/TBone
475Cumulus_TBone/tbone/dispatch/multiplexer.py
tbone.dispatch.multiplexer.WebsocketMultiplexer
class WebsocketMultiplexer(object): ''' Creates a single bridge between a websocket handler and one or more resource routers. ''' def __init__(self, app): self.app = app self.routers = {} self.formatter = JSONFormatter() def add_router(self, name, router): self.routers[name] = router def remove_router(self, name): del self.routers[name] async def dispatch(self, carrier, data): # parse the data try: payload = self.formatter.parse(data) # process payload based on the type ptype = payload.get('type', None) if ptype == 'request': # send request to all resource routers and pickup one result tasks = [router.dispatch(self.app, payload) for router in self.routers.values()] results = await asyncio.gather(*tasks) # get the response from the one relevant router response = next(item for item in results if item is not None) await carrier.deliver(response) elif ptype == 'ping': # reply directly with pong pass elif ptype == 'echo': pass else: pass except Exception as ex: import pdb; pdb.set_trace() print(ex)
class WebsocketMultiplexer(object): ''' Creates a single bridge between a websocket handler and one or more resource routers. ''' def __init__(self, app): pass def add_router(self, name, router): pass def remove_router(self, name): pass async def dispatch(self, carrier, data): pass
5
1
7
0
7
1
2
0.3
1
2
1
0
4
3
4
4
37
4
27
15
22
8
25
14
19
5
1
2
8
885
475Cumulus/TBone
475Cumulus_TBone/tbone/dispatch/signals.py
tbone.dispatch.signals.Signal
class Signal(object): ''' Base class for all signals ''' def __init__(self): self.receivers = {} def connect(self, receiver, sender): ''' Connects a signal to a receiver function :param receiver: The callback function which will be connected to this signal :param sender: Specifies a particular sender to receive signals from. Used to limit the receiver function to signal from particular sender types ''' logger.info('Signal connected: {}'.format(receiver)) ''' connect a receiver to a sender for signaling ''' assert callable(receiver) receiver_id = _make_id(receiver) sender_id = _make_id(sender) r = ref if hasattr(receiver, '__self__') and hasattr(receiver, '__func__'): r = WeakMethod receiver = r(receiver) self.receivers.setdefault((receiver_id, sender_id), receiver) def disconnect(self, receiver, sender): logger.info('Signal disconnected: {}'.format(receiver)) receiver_id = _make_id(receiver) sender_id = _make_id(sender) del self.receivers[(receiver_id, sender_id)] async def send(self, sender, **kwargs): ''' send a signal from the sender to all connected receivers ''' if not self.receivers: return [] responses = [] futures = [] for receiver in self._get_receivers(sender): method = receiver() if callable(method): futures.append(method(sender=sender, **kwargs)) if len(futures) > 0: responses = await asyncio.gather(*futures) return responses def _get_receivers(self, sender): ''' filter only receiver functions which correspond to the provided sender ''' key = _make_id(sender) receivers = [] for (receiver_key, sender_key), receiver in self.receivers.items(): if sender_key == key: receivers.append(receiver) return receivers
class Signal(object): ''' Base class for all signals ''' def __init__(self): pass def connect(self, receiver, sender): ''' Connects a signal to a receiver function :param receiver: The callback function which will be connected to this signal :param sender: Specifies a particular sender to receive signals from. Used to limit the receiver function to signal from particular sender types ''' pass def disconnect(self, receiver, sender): pass async def send(self, sender, **kwargs): ''' send a signal from the sender to all connected receivers ''' pass def _get_receivers(self, sender): ''' filter only receiver functions which correspond to the provided sender ''' pass
6
4
10
1
7
2
2
0.32
1
1
0
0
5
1
5
5
57
8
37
19
31
12
37
19
31
5
1
2
12
886
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/aiohttp.py
tbone.resources.aiohttp.AioHttpResource
class AioHttpResource(object): ''' A mixin class for adapting a ``Resource`` class to work with the AioHttp webserver ''' @classmethod def build_http_response(cls, data, status=200): res = Response(status=status, text=data, content_type='application/json') return res async def request_body(self): ''' Returns the body of the current request. ''' if self.request.has_body: return await self.request.text() return {} @classmethod def route_methods(cls): ''' Returns the relevant representation of allowed HTTP methods for a given route. Implemented on the http library resource sub-class to match the requirements of the HTTP library ''' return '*' @classmethod def route_param(cls, param, type=str): return '{%s}' % param def request_args(self): ''' Returns the arguments passed with the request in a dictionary. Returns both URL resolved arguments and query string arguments. ''' kwargs = {} kwargs.update(self.request.match_info.items()) kwargs.update(self.request.query.items()) return kwargs
class AioHttpResource(object): ''' A mixin class for adapting a ``Resource`` class to work with the AioHttp webserver ''' @classmethod def build_http_response(cls, data, status=200): pass async def request_body(self): ''' Returns the body of the current request. ''' pass @classmethod def route_methods(cls): ''' Returns the relevant representation of allowed HTTP methods for a given route. Implemented on the http library resource sub-class to match the requirements of the HTTP library ''' pass @classmethod def route_param(cls, param, type=str): pass def request_args(self): ''' Returns the arguments passed with the request in a dictionary. Returns both URL resolved arguments and query string arguments. ''' pass
9
4
5
0
3
2
1
0.6
1
1
0
2
2
0
5
5
37
5
20
11
11
12
17
8
11
2
1
1
6
887
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/authentication.py
tbone.resources.authentication.NoAuthentication
class NoAuthentication(object): ''' Base class for all authentication methods. Used as the default for all resouces. This is a no-op authenttication class which always returns ``True`` ''' async def is_authenticated(self, request): ''' This method is executed by the ``Resource`` class before executing the request. If the result of this method is ``False`` the request will not be executed and the response will be 401 un authorized. The basic implementation is no-op and always returns ``True`` ''' return True
class NoAuthentication(object): ''' Base class for all authentication methods. Used as the default for all resouces. This is a no-op authenttication class which always returns ``True`` ''' async def is_authenticated(self, request): ''' This method is executed by the ``Resource`` class before executing the request. If the result of this method is ``False`` the request will not be executed and the response will be 401 un authorized. The basic implementation is no-op and always returns ``True`` ''' pass
2
2
7
0
2
5
1
3.33
1
0
0
2
1
0
1
1
13
0
3
2
1
10
3
2
1
1
1
0
1
888
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/authentication.py
tbone.resources.authentication.ReadOnlyAuthentication
class ReadOnlyAuthentication(NoAuthentication): async def is_authenticated(self, request): if request.method.upper() == 'GET': return True return False
class ReadOnlyAuthentication(NoAuthentication): async def is_authenticated(self, request): pass
2
0
4
0
4
0
2
0
1
0
0
0
1
0
1
2
5
0
5
2
3
0
5
2
3
2
2
1
2
889
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/formatters.py
tbone.resources.formatters.JSONFormatter
class JSONFormatter(Formatter): ''' Implements JSON formatting and parsing ''' def parse(self, body): if isinstance(body, bytes): return json.loads(body.decode('utf-8')) return json.loads(body) def format(self, data): return json.dumps(data, cls=ExtendedJSONEncoder)
class JSONFormatter(Formatter): ''' Implements JSON formatting and parsing ''' def parse(self, body): pass def format(self, data): pass
3
1
3
0
3
0
2
0.14
1
2
1
0
2
0
2
4
9
1
7
3
4
1
7
3
4
2
2
1
3
890
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/http.py
tbone.resources.http.HttpResource
class HttpResource(object): pass
class HttpResource(object): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
891
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/resources.py
tbone.resources.resources.ModelResource
class ModelResource(Resource): ''' A specialized resource class for using data models. Requires further implementation for data persistency ''' def __init__(self, *args, **kwargs): super(ModelResource, self).__init__(*args, **kwargs) # verify object class has a declared primary key if not hasattr(self._meta.object_class, 'primary_key') or not hasattr(self._meta.object_class, 'primary_key_type'): raise Exception('Cannot create a ModelResource to model {} without a primary key'.format(self._meta.object_class.__name__)) self.pk = self._meta.object_class.primary_key self.pk_type = self._meta.object_class.primary_key_type
class ModelResource(Resource): ''' A specialized resource class for using data models. Requires further implementation for data persistency ''' def __init__(self, *args, **kwargs): pass
2
1
7
0
6
1
2
0.57
1
2
0
1
1
2
1
53
12
1
7
4
5
4
7
4
5
2
4
1
2
892
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/resources.py
tbone.resources.resources.ResourceOptions
class ResourceOptions(object): ''' A configuration class for Resources. Provides all the defaults and allows overriding inside the resource's definition using the ``Meta`` class :param name: Declare the resource's name. If ``None`` the class name will be used. Default is ``None`` :param object_class: Declare the class of the underlying data object. Used in ``MongoResource`` to bind the resource class to a ``Model`` :param query: Define a query which the resource will apply to all ``list`` calls. Used in ``MongoResource`` to apply a default query fiter. Useful for cases where the entire collection is never queried. :param sort: Define a sort directive which the resource will apply to GET requests without a unique identifier. Used in ``MongoResource`` to declare default sorting for collection. :param hypermedia: Specify if the a ``Resource`` should format data and include HATEOAS directives, specifically link to itself. Defaults to ``True`` :param fts_operator: Define the FTS (full text search) operator used in url parameters. Used in ``MongoResource`` to perform FTS on a collection. Default is set to `q`. :param incoming_list: Define the methods the resource allows access to without a primary key. These are incoming request methods made to the resource. Defaults to a full access ``['get', 'post', 'put', 'patch', 'delete']`` :param incoming_detail: Same as ``incoming_list`` but for requests which include a primary key :param outgoing_list: Define the resource events which will be emitted without a primary key. These are outgoing resource events which are emitted to subscribers. Defaults to these events ``['created', 'updated', 'deleted']`` :param outgoing_detail: Same as ``outgoing_list`` but for resource events which include a primary key :param formatter: Provides an instance to a formatting class the resource will be using when formatting and parsing data. The default is ``JSONFormatter``. Developers can subclass ``Formatter`` base class and provide implementations to other formats. :param authentication: Provides and instance to the authentication class the resource will be using when authenticating requests. Default is ``NoAuthentication``. Developers must subclass the ``NoAuthentication`` class to provide their own resource authentication, based on the application's authentication choices. :param channel: Defines the Channel class which the resource will emit events into. Defaults to in-memory ''' name = None object_class = None query = None sort = None hypermedia = True channel_class = Channel fts_operator = 'q' incoming_list = ['get', 'post', 'put', 'patch', 'delete'] incoming_detail = ['get', 'post', 'put', 'patch', 'delete'] outgoing_list = ['created', 'updated', 'deleted'] outgoing_detail = ['created', 'updated', 'deleted'] formatter = JSONFormatter() authentication = NoAuthentication() def __init__(self, meta=None): if meta: for attr in dir(meta): if not attr.startswith('_'): setattr(self, attr, getattr(meta, attr))
class ResourceOptions(object): ''' A configuration class for Resources. Provides all the defaults and allows overriding inside the resource's definition using the ``Meta`` class :param name: Declare the resource's name. If ``None`` the class name will be used. Default is ``None`` :param object_class: Declare the class of the underlying data object. Used in ``MongoResource`` to bind the resource class to a ``Model`` :param query: Define a query which the resource will apply to all ``list`` calls. Used in ``MongoResource`` to apply a default query fiter. Useful for cases where the entire collection is never queried. :param sort: Define a sort directive which the resource will apply to GET requests without a unique identifier. Used in ``MongoResource`` to declare default sorting for collection. :param hypermedia: Specify if the a ``Resource`` should format data and include HATEOAS directives, specifically link to itself. Defaults to ``True`` :param fts_operator: Define the FTS (full text search) operator used in url parameters. Used in ``MongoResource`` to perform FTS on a collection. Default is set to `q`. :param incoming_list: Define the methods the resource allows access to without a primary key. These are incoming request methods made to the resource. Defaults to a full access ``['get', 'post', 'put', 'patch', 'delete']`` :param incoming_detail: Same as ``incoming_list`` but for requests which include a primary key :param outgoing_list: Define the resource events which will be emitted without a primary key. These are outgoing resource events which are emitted to subscribers. Defaults to these events ``['created', 'updated', 'deleted']`` :param outgoing_detail: Same as ``outgoing_list`` but for resource events which include a primary key :param formatter: Provides an instance to a formatting class the resource will be using when formatting and parsing data. The default is ``JSONFormatter``. Developers can subclass ``Formatter`` base class and provide implementations to other formats. :param authentication: Provides and instance to the authentication class the resource will be using when authenticating requests. Default is ``NoAuthentication``. Developers must subclass the ``NoAuthentication`` class to provide their own resource authentication, based on the application's authentication choices. :param channel: Defines the Channel class which the resource will emit events into. Defaults to in-memory ''' def __init__(self, meta=None): pass
2
1
5
0
5
0
4
2.11
1
0
0
0
1
0
1
1
73
14
19
16
17
40
19
16
17
4
1
3
4
893
475Cumulus/TBone
475Cumulus_TBone/tbone/dispatch/channels/mongo.py
tbone.dispatch.channels.mongo.MongoChannel
class MongoChannel(Channel): ''' Represents a channel for event pub/sub based on a MongoDB capped collection ''' channel_lock = asyncio.Lock() def __init__(self, **kwargs): self._db = kwargs.get('db', None) self._collection = None def __repr__(self): # pragma no cover return '<MongoChannel {}.{}>'.format( self._db.name, self.name ) async def create_channel(self, capacity=2**15, message_size=1024): # default size is 32kb if self._collection: return with (await MongoChannel.channel_lock): if self.name not in (await self._db.list_collection_names()): self._collection = await self._db.create_collection( self.name, size=capacity * message_size, max=capacity, capped=True, autoIndexId=False ) else: self._collection = self._db[self.name] async def publish(self, key, data=None): # begin by making sure the channel is created await self.create_channel() document = { 'key': key, 'data': data } await self._collection.insert(document, manipulate=False) return document async def consume_events(self): ''' begin listening to messages that were entered after starting''' # begin by making sure the channel is created await self.create_channel() # get cursor method def create_cursor(): now = datetime.datetime.utcnow() dummy_id = ObjectId.from_datetime(now) return self._collection.find({'_id': {'$gte': dummy_id}}, cursor_type=CursorType.TAILABLE_AWAIT) # get cursor and start the loop cursor = create_cursor() while self.active: if cursor.alive: if (await cursor.fetch_next): message = cursor.next_object() event = message['key'] data = message['data'] logger.debug('event: %s - %s', event, data) for sub in self._subscribers[event]: await sub.deliver({'type': 'event', 'payload': {'name': event, 'data': data}}) else: await asyncio.sleep(0.1) cursor = create_cursor()
class MongoChannel(Channel): ''' Represents a channel for event pub/sub based on a MongoDB capped collection ''' def __init__(self, **kwargs): pass def __repr__(self): pass async def create_channel(self, capacity=2**15, message_size=1024): pass async def publish(self, key, data=None): pass async def consume_events(self): ''' begin listening to messages that were entered after starting''' pass def create_cursor(): pass
7
2
10
0
9
1
2
0.2
1
1
0
0
5
3
5
13
67
8
51
19
44
10
37
18
30
5
2
4
12
894
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/routers.py
tbone.resources.routers.Request
class Request(dict): __slots__ = ( 'key', 'app', 'headers', 'method', 'body', 'args', 'url' ) def __init__(self, app, key, url, method='GET', headers={}, args={}, body={}): self.app = app self.key = key self.url = url self.method = method self.args = args self.headers = headers self.body = body self.args = args @property def match_info(self): return self.args
class Request(dict): def __init__(self, app, key, url, method='GET', headers={}, args={}, body={}): pass @property def match_info(self): pass
4
0
6
0
6
0
1
0
1
0
0
0
2
7
2
29
18
2
16
12
12
0
13
11
10
1
2
0
2
895
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/sanic.py
tbone.resources.sanic.SanicResource
class SanicResource(HttpResource): ''' A mixin class for adapting a ``Resource`` class to work with the Sanic webserver ''' @classmethod def build_http_response(cls, data, status=200): return response.text( data, headers={'Content-Type': 'application/json'}, status=status ) async def request_body(self): ''' Returns the body of the current request. ''' return self.request.body def request_args(self): ''' Returns the url arguments of the current request''' return self.request.raw_args @classmethod def route_methods(cls): ''' Returns the relevant representation of allowed HTTP methods for a given route. Implemented on the http library resource sub-class to match the requirements of the HTTP library ''' return ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] @classmethod def route_param(cls, param, type=None): if type: return '<%s:%s>' % (param, type) return '<%s>' % param
class SanicResource(HttpResource): ''' A mixin class for adapting a ``Resource`` class to work with the Sanic webserver ''' @classmethod def build_http_response(cls, data, status=200): pass async def request_body(self): ''' Returns the body of the current request. ''' pass def request_args(self): ''' Returns the url arguments of the current request''' pass @classmethod def route_methods(cls): ''' Returns the relevant representation of allowed HTTP methods for a given route. Implemented on the http library resource sub-class to match the requirements of the HTTP library ''' pass @classmethod def route_param(cls, param, type=None): pass
9
4
4
0
3
1
1
0.45
1
0
0
5
2
0
5
5
33
4
20
9
11
9
13
6
7
2
2
1
6
896
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/verbs.py
tbone.resources.verbs.BadRequest
class BadRequest(HttpError): status = BAD_REQUEST msg = 'Bad request'
class BadRequest(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
897
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/verbs.py
tbone.resources.verbs.Forbidden
class Forbidden(HttpError): status = FORBIDDEN msg = 'Resource not allowed'
class Forbidden(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
898
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/verbs.py
tbone.resources.verbs.HttpError
class HttpError(Exception): status = APPLICATION_ERROR msg = "Application Error" def __init__(self, msg=None): if not msg: msg = self.__class__.msg super(HttpError, self).__init__(msg)
class HttpError(Exception): def __init__(self, msg=None): pass
2
0
4
0
4
0
2
0
1
1
0
6
1
0
1
11
8
1
7
4
5
0
7
4
5
2
3
1
2
899
475Cumulus/TBone
475Cumulus_TBone/tbone/resources/verbs.py
tbone.resources.verbs.MethodNotAllowed
class MethodNotAllowed(HttpError): status = METHOD_NOT_ALLOWED msg = 'The specified HTTP method is not allowed'
class MethodNotAllowed(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