Skip to main content

Hyper Media Channels Rest Framework

A Hyper Media style serializer for DjangoChannelsRestFramework.

https://travis-ci.org/hishnash/hypermediachannels.svg?branch=master

API USAGE

This is a collection of serialisers and serialiser fields that creats a hypermidea style like PK

Setting up your consumers

All of your consumers should be mapped through a AsyncJsonWebsocketDemultiplexer.

from channelsmultiplexer import AsyncJsonWebsocketDemultiplexer
from djangochannelsrestframework.generics import GenericAsyncAPIConsumer
from hypermediachannels.serializers import HyperChannelsApiModelSerializer

class UserSerializer(HyperChannelsApiModelSerializer):
  class Meta:
      model = User
      fields = (
          '@id',
          'username'
      )

class UserConsumer(GenericAsyncAPIConsumer):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class MainDemultiplexer(AsyncJsonWebsocketDemultiplexer):
    applications = {
        'users': UserConsumer,
    }

Then when configuring your Channels Application add the MainDemultiplexer as your main consumer. This way all Websocket connections on that URL will run through the Demultiplexer. See DjangoChannelsRestFramework for more deaitls on how to write consumers.

HyperChannelsApiModelSerializer

This can be used inplace of the DRF ModelSerializer. It will (if you include @id in the fields list) add a self reference to the model being displayed)

eg User model Serialiser might respond like this if its fields are ('@id', 'username', 'profile')

{
   @id: {
     stream: 'user',
     payload: {
       action: 'retrieve',
       pk: 1023
      }
   },
   username: 'bob@example.com',
   profile: {
     stream: 'profile',
     payload: {
       action: 'retrieve',
       pk: 23
     }
   }
}

This will under the hood use HyperlinkedIdentityField to create the @id and profile fields and they will (by default) return these retrieve objects.

Why do we do this.

this means that if we then need to lookup that profile for this user we can just send the msg:

{
  stream: 'profile',
  payload: {
    action: 'retrieve',
    pk: 23
  }
}

Down the websocket and we will get that item, the frontend code does not need to track all of these lockup logic, (consider that some models might have lookup that is not based on pk for example).

If you need to define a different set of lookup params. You can use the kwarg_mappings, stream_name and action_name kwargs to override this.

eg:

class UserSerializer(HyperChannelsApiModelSerializer):
    class Meta:
        model = get_user_model()
        fields = (
            '@id', 'username', 'profile'
        )

        extra_kwargs = {
            'profile': {
                'action_name': 'user_profile',
                'kwarg_mappings': {
                    'user_pk': 'self.pk',
                    'team_pk': 'team.pk'
                }
            },
        }

the kwarg_mappings will set the value in the response user_pk by extracting the pk value on from the User instance.

(pre-appending self to the kwarg_mappings value means it will do the lookup based on the instance parsed to the parent Serializer rather than the instance for this field. In this case a user profile).

so the above would return:

{
   @id: {
     stream: 'user',
     payload: {
       action: 'retrieve',
       pk: 1023
      }
   },
   username: 'bob@example.com',
   profile: {
     stream: 'user_profile',
     payload: {
       action: 'retrieve',
       user_pk: 1023,
       team_pk: 234234
     }
   }
}

You can use . to access nested values eg. profile.team.name.

Alternatively you can create fields as you would in DRF.
class UserSerializer(HyperChannelsApiModelSerializer):
    team = HyperChannelsApiRelationField(
        source='profile.team',
        kwarg_mappings={
            'member_username': 'self.username'
        }
    )

    class Meta:
        model = get_user_model()
        fields = (
            '@id', 'username', 'team'
        )

this will return:

{
   @id: {
     stream: 'user',
     payload: {
       action: 'retrieve',
       pk: 1023
      }
   },
   username: 'bob@example.com',
   team: {
     stream: 'team',
     payload: {
       action: 'retrieve',
       member_username: 'bob@example.com'
     }
   }
}

If you reference a Many field the HyperChannelsApiModelSerializer will do some magic so that:

class UserSerializer(HyperChannelsApiModelSerializer):
    friends = HyperChannelsApiRelationField(
        source='profile.friends'
    )

    class Meta:
        model = get_user_model()
        fields = (
            '@id', 'username', 'friends'
        )



        extra_kwargs = {
            'friends': {
                'kwarg_mappings': {
                    'user_pk': 'self.user.pk',
                }
            },
        }

Adding extra_kwargs for any Many field can be important so that you can controle the lookup params used.

NOTE all Many fields (forwards and backwards) will extract values from the parent instance regardless of if you use self. in the kwarg_mappings value.)

this will return:

{
   @id: {
     stream: 'user',
     payload: {
       action: 'retrieve',
       pk: 1023
      }
   },
   username: 'bob@example.com',
   friends: {
        stream: 'user_profile', payload: {action: 'list', user_pk: 1023}
    }
}

Remember you can also override the @id lookup/action and stream if needed, eg:

extra_kwargs = {
    '@id': {
        'action_name': 'subscribe_status',
        'kwarg_mappings': {
            'username': 'username'
        }
    },
}

Returning Many items.

Expect to get:

[
    {
     stream: 'user',
     payload: {
       action: 'retrieve',
       pk: 1023
      }
    },
    {
     stream: 'user',
     payload: {
       action: 'retrieve',
       pk: 234
      }
   },
    {
     stream: 'user',
     payload: {
       action: 'retrieve',
       pk: 103223
      }
   },
]

Rather than getting a fully expanded value for each instance you will rather just get a list of hyper media paths you can use to lookup the instance you need.

If you need to override the stream action or lookup do this:

class UserSerializer(HyperChannelsApiModelSerializer):

    class Meta:
        model = User
        fields = (
            '@id',
            'username'
        )

        many_stream_name = 'active_users'

        many_kwarg_mappings = {
            'username': 'username'
        }

        many_action_name = 'subscribe'

Metadata

Release files for hypermediachannels 0.0.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hypermediachannels 0.0.5
File Size Uploaded Provenance Actions
hypermediachannels-0.0.5.tar.gz 8.1 kB Without provenance Details for hypermediachannels-0.0.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for hypermediachannels 0.0.5
File Interpreter ABI Platform Actions
hypermediachannels-0.0.5-py2.py3-none-any.whl Python 2, Python 3 none any Details for hypermediachannels-0.0.5-py2.py3-none-any.whl

Total release size: 14.9 kB

Release files / hypermediachannels-0.0.5.tar.gz

Download URL hypermediachannels-0.0.5.tar.gz
Size 8.1 kB
Tags Source
SHA-256 checksum
How to use checksums
c9dd26c206a4c194d07f88825cb777adce5186747f25acef8f41dc9cc1281e9f
BLAKE2b-256 checksum
How to use checksums
4a4f9e8281d41b836a445bf281478f75c3c2e4e60d0fe0983e158c922d86045c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/40.1.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.3

Release files / hypermediachannels-0.0.5-py2.py3-none-any.whl

Download URL hypermediachannels-0.0.5-py2.py3-none-any.whl
Size 6.9 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
00947fd56d0b5c12673b96fab97d37ec677d330f3ec8f70b5f1416c78cd26779
BLAKE2b-256 checksum
How to use checksums
257ae5a42447d598e8df9beaafd0aa770b9b55eba602c32797898de732322263
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/40.1.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.3

Security for hypermediachannels 0.0.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page