httpbase.resources

Base Class

class httpbase.resources.ResourceMetaclass[source]

Metaclass for Resource objects. When a class object is constructed at run time this will add any declared to a dictionary and set that dictionary as the value for _declared_fields. It will also go up the inheritance chain and add any fields from parent Resources as well.

This is done so that class instances can make copies of the fields that are assigned to it so that instances of the Resource class don’t all share the same fields/values.

mro() → list

return a type’s method resolution order

class httpbase.resources.Resource(**kwargs)[source]

A class the represents a resource in an HTTP API. Subclasses of this class are composed of Fields which dictate how the value within that field will serialized. Resources can contain other resources.

To deal with the nested nature of these resources this class has some special accessor methods to make traversing down deeply nested structures a bit more convenient. They are similar to the get() on dictionaries and work the same way when fetching a value on the parent resource. However they aso support a dotted syntax for traversing further down in to nested objects. For example if you had a post resource that had an author and the author had a profile that had an email you could access it like so:

class PostResource(Resource):
    author = ResourceField()


class AuthorResource(Resource):
    profile = ResourceField()


class ProfileResource(Resource):
    email = StrField()

post = PostResource(
    author=AuthorResource(profile=ProfileResource(email="foo@example.com"))
)
# to get the value of the StrField ``email``
post.get_value("author.profile.email")

# to update the value
post.update("author.profile.email","new.email@example.com")
exception SerializationError

This error is used to indicate that an exception occurred during serialization of the fields on a resource.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

_traverse_fields(path: str) → httpbase.fields.Field[source]

Method for traversing fields given a dotted path.

Parameters:path – A dot separated path down the Resource object.
Returns:Field
dict(use_labels: bool = True) → Dict[str, Union[str, int, float, NoneType, typing.Mapping[str, _ForwardRef('JSON')], typing.List[_ForwardRef('JSON')]]][source]

Get a json serializable dictionary

Returns a dictionary suitable for use with json.dumps(). Accepts a keyword argument, use_labels, that determines if the attribute name or the label attribute of the field should be used as the key in the resulting dictionary.

This method will capture most expected exceptions raised during the serialization process and attach them to the instance, similar to forms in Django. This method is called by json(), if there are any errors on the instance JSON serialization will fail. If you are going to use this method directly ensure to check for errors prior to using it.

Example:

class PostResource(Resource):
    author_name = StrField(label="authorName")
    title = StrField(label="postTitle")
    body = StrField()
    date = DateField()

post = PostResource(
    author_name="Author", title="Post Title", body="...", date=datetime.now()
)
post.dict()
{'authorName': 'Author',
 'body': '...',
 'date': '2018-02-17 22:08:1518934108',
 'postTitle': 'Post Title'}

post.dict(use_labels=False)
{'author_name': 'Author',
 'body': '...',
 'date': '2018-02-17 22:08:1518934108',
 'title': 'Post Title'}
Keyword Arguments:
 use_labels – If set to False the resulting dictionary will use the attribute names of the fields as keys in the dictionary. If set to True the label attribute of the class will be used. This helpful if you want to write the serialized Resource to a file to loaded again later. That will allow use to use the Resource(**dict) syntax.
errors

A dictionary containing any errors encountered during serialization. Should be checked prior to suing the output of dict(). If this dictionary contains any errors json() will raise a SerializationError

fields

Returns a dictionary where the keys are the attribute name for a field and the value is the Field object

Example:

class PostResource(Resource):
    author_name = StrField()
    title = StrField()
    body = StrField()
    date = DateField()

post = Post(author_name="Author", title="Post Title", body="...", date=datetime.now())
print(post.fields())
{'author_name': <StrField: Author>,
 'body': <StrField: ...>,
 'date': <DateField: 2018-02-17 21:53:44.522987>,
 'title': <StrField: Post Title>}
Returns:dict[str, Field]
get_field(path: str) → httpbase.fields.Field[source]

Given a dot separated path to a field will return the field at the end of the path.

Example:

post = PostResource(
    author=AuthorResource(profile=ProfileResource(email="foo@example.com"))
)
# This would return the field of the ``email`` attribute on the ``ProfileResource``
print(post.get_field("author.profile.email"))
<StrField: foo@example.com>
Parameters:path – A dot separated path to a field.
Returns:Field
get_label(path: str) → str[source]

Get the label for a given path.

Example:

post = PostResource(
    author=AuthorResource(profile=ProfileResource(email="foo@example.com"))
)
# This would return the label of the ``email`` field on the ``ProfileResource``
post.get_label("author.profile.email")
print(post.get_label("author.profile.email")
"email"
Parameters:path – A dot separated path.
get_value(path: str)[source]

Given a dotted path return the value at the end of that path.

Example:

post = PostResource(
    author=AuthorResource(profile=ProfileResource(email="foo@example.com"))
)
# This would return the value of the ``email`` field on the ``ProfileResource``
print(post.get_value("author.profile.email"))
"foo@example.com"
Parameters:path – A dot separated path
json(use_labels: bool = True) → str[source]

Get the JSON for an instance.

Parameters:use_labels – Boolean to determine whether or not the attr name or the label of the Field should be used.
Raises:SerializationError – Raises a SerializationError if there are fields that aren’t JSON serializable.
labels(path: str = '') → Iterator[str][source]

Yields all the labels for the given resource. If a dotted path is given it will return the labels for the resource at the end of that path.

Example:

class PostResource(Resource):
    author = ResourceField()
    title = StrField()
    body = StrField()
    date = DateField()

class AuthorResource(Resource):
    name = StrField(label="authorName")
    post_count = IntField(label="postCount")
    avatar = StrField()

author = AuthorResource(name="author", post_count=10, avatar="...")
post = PostResource(
    author=author,
    title="Post Title",
    body="...",
    date=datetime.now(),
)
# This would yield the labels of the ``PostResource``
print(list(post.labels()))
['author', 'title', 'body', 'date']
print(list(post.labels("author")))
['authorName', 'postCount', 'avatar']
Parameters:path – A dot separated path
Yields:str
update(path: str, value)[source]

Update the value at given path.

Example:

post = PostResource(
    author=AuthorResource(profile=ProfileResource(email="foo@example.com"))
)
# This would update the value of the ``email`` field on the ``ProfileResource``
post.update("author.profile.email", "new.email@example.com")
print(post.get_value("author.profile.email")
"new.email@example.com"
Parameters:
  • path – A dot separated path
  • value – A new value