Saravanan666/pypi-org huggingface dataset:
Package: channelpack
The ChannelPack class provides a callable container of data. The channelpack
package also provides some factory functions to get such a pack from data
files.Channelpack is a Python project (a small library) assuming Numpy being
available and that numpy arrays are the preferred data sequences.ExampleProduce some data and make a pack:>>> import channelpack as cp
>>> data = {0: range(5), 1: ('A', 'B', 'C', 'D', 'E')}
>>> names = {0: 'seq', 1: 'abc'}
>>> pack = cp.ChannelPack(data=data, names=names)
>>> pack
ChannelPack(
data={0: array([0, 1, 2, 3, 4]),
      1: array(['A', 'B', 'C', 'D', 'E'], dtype='<U1')},
names={0: 'seq',
       1: 'abc'})
>>> pack(0)
array([0, 1, 2, 3, 4])
>>> pack(0) is pack('seq')
TrueSet the pack mask and use it to slice or filter out parts:>>> pack.mask = (pack('seq') < 2) | (pack('abc') == 'D')
>>> pack('seq', part=0)
array([0, 1])
>>> pack('seq', part=1)
array([3])
>>> pack('abc', nof='filter')
array(['A', 'B', 'D'], dtype='<U1')
>>> pack('abc', nof='nan')
array(['A', 'B', None, 'D', None], dtype=object)
>>> pack('seq', nof='nan')
array([ 0.,  1., nan,  3., nan])Read data from file:>>> import io
>>> datstring = \
... u"""date: 20-05-01 17:39
... room: east lab hall, floor 2, room 8
... operator: Goran Operatorsson
...
... time, speed, onoff, distance
... 0, 23, on, 0.3
... 1, 21, off, 0.28
... """
>>> sio = io.StringIO(datstring)
>>> pack = cp.textpack(sio, delimiter=',', skiprows=5, hasnames=True)
>>> pack
ChannelPack(
data={0: array([0., 1.]),
      1: array([23., 21.]),
      2: array([' on', ' off'], dtype='<U4'),
      3: array([0.3 , 0.28])},
names={0: 'time',
       1: 'speed',
       2: 'onoff',
       3: 'distance'})Lazy read numeric data:>>> datstring = \
... u"""date: 20-05-01 17:39
... room: east lab hall, floor 2, room 8
... operator: Goran Operatorsson
...
... time, speed, distance
... 0, 23, 0.3
... 1, 21, 0.28
... """
>>> sio = io.StringIO(datstring)
>>> pack = cp.lazy_textpack(sio)
>>> pack
ChannelPack(
data={0: array([0., 1.]),
      1: array([23., 21.]),
      2: array([0.3 , 0.28])},
names={0: 'time',
       1: 'speed',
       2: 'distance'})Channel?The naming (channelpack) sort of origins from work with measurements and data
acquisition. Using tools for that, the recorded arrays of data are often called
“channels”, because it was acquired through some IO channel.Install$ pip install channelpackDocumentation and repositoryThere is some documentation atRead the Docsand the code repository is onGitHub.
Package: channelpy
A basic implementation ofGoinspired channels.Use these channels to communicate across Python threads, processes, or
hosts, independent of network location.  Channels are first class
objects that can be passed themselves through the channels.The current implementation usesRabbitMQas a broker, but it can be
swapped by other queues or even a peer-to-peer transport mechanism
such asZeroMQ.  Seethe implementation details.PrerequisiteStart a RabbitMQ instance by executing the following command in the
root directory of this repository:docker-composeup-dQuickstartCreate a channel with:>>>fromchannelpyimportChannel>>>ch=Channel()Put and get objects to and from the channel:>>>ch.put('foo')>>>ch.get()'foo'>>>ch.get(timeout=1)# raises ChannelTimeoutException since channel is emptyPass channels into channels:>>>ch1=Channel()>>>ch1.put(5)>>>ch2=Channel()>>>ch2.put(ch1)>>>x=ch2.get()>>>x.get()5Channels can be instantiated by name:>>>ch=Channel()>>>ch.name'daa0a490f9254c69883335c9f925d74f'>>>another=Channel(name=ch.name)>>>another.put('foo')>>>ch.get()'foo'Or create them with a specific name:>>>ch=Channel(name='my_channel')Multiple consumers and producers can be attached to a
channel. Messages are delivered in round-robin fashion to
consumers. However, aclose_allcan be delivered to all the
consumers to signal a full termination of the channel.>>>ch=Channel()>>>deff(c):...whileTrue:...print(c.get())...>>>threading.Thread(target=f,args=(ch,)).start()>>>threading.Thread(target=f,args=(ch,)).start()>>>ch.put(4)# one of the threads will print 4>>>ch.close_all()# ChannelClosedException is raised in all threadsThe broker to use can be configured at instantiation time or by
using the config file~/.channelpy.yml.  For example:connection:RabbitConnectionuri:amqp://192.168.35.10:5672TestsRun the tests with:$BROKER='amqp://localhost:5672'py.test-vImplementation DetailsTo be written.
Package: channels-auth-token-middlewares
Django Channels auth token middlewaresProvides Django REST frameworktoken authenticationmiddleware,Simple JWTmiddleware and easily extendable middlewares to work with auth tokens placed in request headers, cookie and query string.RequirementsPython>=3.6Channels>=3Install$ pip install channels-auth-token-middlewaresAdd app name toINSTALLED_APPSINSTALLED_APPS=[# base django apps (django.contrib.auth is required)# other apps this one depends on (like rest_framework if it's necessary)'channels_auth_token_middlewares',# custom apps]TutorialExploreDocsExploreTestsRequirementsDocker>=19docker-compose>=1.25UsageRun$ docker-compose -f docker-compose.tests.yml upClean$ docker-compose -f docker-compose.tests.yml down
Package: channels-demultiplexer
(De)multiplexer for Django Channels 3 (and 2)FunctionalityChannels Demultiplexer provides a standard way to multiplex different data streams over a single websocket.It expects JSON-formatted WebSocket frames with two keys, stream and payload (both configurable). It matches the stream against a mapping to find a consumer and subsequently forwards the message. Consumers do not require any modifications in order to be plugged in to a (de)multiplexer, so you can hook them directly in therouting.pyfile as well as in a (de)multiplexer.QuickstartInstall usingpip:$pipinstallchannels-demultiplexerAddchannels_demultiplexerto yourINSTALLED_APPSINSTALLED_APPS=[# channels_demultiplexer can be in any position in the INSTALLED_APPS list."channels_demultiplexer",]Create a demultiplexer indemultiplexer.py:fromchannels_demultiplexer.demultiplexerimportWebsocketDemultiplexerfrom.consumersimportEchoConsumer,AnotherConsumerclassDemultiplexer(WebsocketDemultiplexer):# Wire your async JSON consumers here: {stream_name: consumer}consumer_classes={"echo":EchoConsumer,"other":AnotherConsumer,}Add the demultiplexer to your Channels routing configuration:fromchannels.routingimportProtocolTypeRouter,URLRouterfromdjango.conf.urlsimporturlfromdjango.core.asgiimportget_asgi_applicationfrom.demultiplexerimportDemultiplexerapplication=ProtocolTypeRouter({"http":get_asgi_application(),"websocket":URLRouter([url(r"^/$",Demultiplexer.as_asgi()),])})DocumentationFor more information on installation and configuration see the documentation at:https://channels-demultiplexer.readthedocs.io/Compatibilitychannelschannels_demultiplexerv3.xlatestv2.xv1.0.1IssuesIf you have questions or have trouble using the app please file a bug report at:https://github.com/csdenboer/channels-demultiplexer/issuesContributionsIt is best to separate proposed changes and PRs into small, distinct patches
by type so that they can be merged faster into upstream and released quicker:features,bugfixes,code style improvements, anddocumentation improvements.All contributions are required to pass the quality gates configured
with the CI. This includes running tests and linters successfully
on the currently officially supported Python and Django versions.The test automation is run automatically by Travis CI, but you can
run it locally with thetoxcommand before pushing commits.
Package: channels-discord
Channels-DiscordDjango Channels Discordis a bridge between Discord (currently using thepycordPython library, but this may be a stopgap while we wait for the dust to settle after discord.py'simplosion) and Django'schannels).  It contains both a new interface server for connecting to Discord and Channels consumers -- everything you need to turn your Django app into an Discord chatbot, chat monitoring/moderating service, or whatever else you might use a real-time Discord client to do.This project is more of a stub right now, and will be more further fleshed out as new features are wired up from discord.py.RequirementsMost of the requirements can be found in setup.py, but the most important note is that this requires library requiresDjango Channels 3+-- Channels 1.x and 2.x are not supported.InstallationInstall the package from github:pipinstallchannels-discordBasic UsageAdd the library toINSTALLED_APPS:INSTALLED_APPS = (
    ...
    'channels_discord',
)Create a ConsumerCreate a new consumer by inheriting fromDiscordConsumer:fromchannels_discordimportDiscordConsumerclassMyDiscordConsumer(DiscordConsumer):defready(self):"""Optional hook for actions on connection to Discord"""print('You are now connected to discord!')defmy_custom_message(self):"""Use built-in functions to send basic discord actions"""self.send_action('dm',user_id='SOME_DISCORD_USER_ID',text='your message')self.send_action('send_to_channel',channel_id='SOME_DISCORD_CHANNEL_ID',text='your message')Add your consumer(s) to your routerYou can use thediscordtype in channelsProtocolTypeRouterto connect your new consumer to the interface server, and ensure yourdiscordmessages are delivered to the right place:fromchannels.routingimportProtocolTypeRouterfrommyapp.consumersimportMyDiscordConsumerapplication=ProtocolTypeRouter({'discord':MyDiscordConsumer,})Start the interface serverThe interface server can be started by simply running this in the command line:channels-discordThe server requires that thetokenandapplicationproperties be set:token: Either a bot auth token or a user access token from user OAuth access. For information on how to acquire these tokens, please see Discord'sdeveloper documentation.application: An import string pointing to the location of your app's ASGI application. Hence, if your app was namedmyapp, contained an ASGI filed calledasgi.py, and your ASGI application is namedmy_application, you could start the server by running:channels-discord -t 'MY_LONG_BOT_TOKEN' -a 'myapp.asgi:my_application'You can also set these values using the env variablesCHANNELS_DISCORD_APPLICATIONandDISCORD_BOT_TOKEN.
Package: channels-easy
Channels EasyA thin wrapper around channel consumers to make thingsEASYNote: This library currently support only text data which is JSON serializable.What problem does this library solve?This library simplifies two tasks for nowParse incoming text data as JSON and vice versa.Generate event on the basis of type passed from client side.Table of ContentsInstallationExampleAPI UsageContributeInstallationTo get the latest stable release from PyPipipinstallchannels-easyAschannels-easyis a thin wrapper aroundchannelsso channels must be in yourINSTALLED_APPSinsettings.py.INSTALLED_APPS=(...,'channels',)ExampleAll the naming convention used to implement this library is inspired fromsocket.ioto make server implementation simple.Get full example projecthere.Server side# consumers.pyfromchannels_easy.genericimportAsyncWebsocketConsumerclassNewConsumer(AsyncWebsocketConsumer):asyncdefconnect(self):# join room on connectawaitself.join("room1")awaitself.accept()asyncdefdisconnect(self,close_code):# Leave room on disconnectawaitself.leave("room1")asyncdefon_message(self,data):print("message from client",data)# output:# message from client {'text': 'hello'}awaitself.emit("message",{"message":"hello from server"},"room1")Client side// client.jsconstsocket=newWebSocket("ws://localhost:8000/ws/test/");socket.onmessage=function({data}){constparsed_data=JSON.parse(data);console.log(parsed_data);// output:// {//     data: {message: 'hello from server'}//     type: "message"// }};socket.onopen=()=>{console.log("websocket connected...");// send message from client after connected// send with type `message` to receive from subscribed// `on_message` event on server sidesocket.send(JSON.stringify({type:"message",data:{text:"hello",},}));};API UsageSubscribing to eventsWe can simply subscribe to a message type asdefon_<type>(self,data):...passso if client send data as{"type":"message","data":"Hello!"}We can subscribe to message event asdefon_message(self,data):...passEmitting MessageWe can emit message to client using same schema that we used abovedefon_message(self,data):...# some code here...self.emit("message",# type{"text":"hello"},# message dict | str | int | list["room1"],# room list or string)Check all APIshere.ContributeIf you want to contribute to this project, please perform the following steps# Fork this repository# Clone your forkpoetryinstall

gitcheckout-bfeature_branchmaster# Implement your feature and testsgitadd.&&gitcommit
gitpush-uoriginfeature_branch# Send us a pull request for your feature branchIn order to run the tests, simply executepoetry run pytest. This will run test created insidetestdirectory.
Package: channels-endpoints
Django channels endpointsThis package provides endpoints as functions for djangochannelspackage.Installationpipinstallchannels-endpointsUsageIn your django app create dce.py file:fromchannels_endpoints.mainimportendpoint,Responsefromdjango.contrib.auth.modelsimportUserfromdjango.coreimportserializersfrom.permissionsimportUsersPermissionsfromasgiref.syncimportsync_to_asyncusers_logger=logging.getLogger('users')@endpoint(logger=users_logger,permissions=[UsersPermissions],timeout=42)asyncdefget_users(request):print(request.data)def_get():returnserializers.serialize('python',User.objects.all(),fields=('username','id'))awaitrequest.consumer.send(text_data=Response(None,f'hello',consumers=['SomeConsumer']))returnResponse(request,awaitsync_to_async(_get)())Python client:fromchannels_endpoints.clientimportDce,DceException,consumer@consumerasyncdefSomeConsumer(response):print(f'SomeConsumer:{response["data"]}')dce=Dce('http://127.0.0.1:8000/ws/')try:data=awaitdce.request('myapp.get_users',{'some':'data'})exceptDceExceptionase:print(e.__repr__())dce.close()Javascript client:import{dce,consumer}from"channels_endpoints"consumer('SomeConsumer',(response)=>{console.log('SomeConsumer: ',response.data)})dce('myapp.get_users',{some:"data"}).then(response=>{console.log('users:',response)})see js client packagehttps://www.npmjs.com/package/channels_endpointsExamplesFor complete usage examples seeexample chat
Package: channels-irc
A bridge between IRC and Django’schannels.Installationrunpip install channels_ircto install the library and set up the command line interfaceDocumentationFull docs available atdjango-channels-irc.readthedocs.io.RequirementsDjango Channels 3+UsageFollow these steps to set upDjango Channels IRCin your projectAdd to INSTALLED_APPSAdd the library toINSTALLED_APPS:INSTALLED_APPS = (
    ...
    'channels_irc',
)Create a ConsumerDjango Channels IRCcontains two consumers for interacting with the
IRC interface server:IrcConsumerandAsyncIrcConsumer:from channels_irc import IrcConsumer

class MyIrcConsumer(IrcConsumer):
    def welcome(self, channel):
        """
        Optional hook for actions on connection to IRC Server
        """
        print('Connected to IRC with nickname'.format(nickname)

    def disconnect(self, server, port):
        """
        Optionl hook for actions on disconnect from IRC Server
        """
        print('Disconnect from server {}:{}'.format(server, port)

    def my_custom_message(self):
        """
        Use built-in functions to send basic IRC messages
        """
        self.send_message('my-channel', 'here is what I wanted to say')

    def my_custom_command(self):
        """
        You can also use built-in functions to send basic IRC commands
        """
        self.send_command('join', channel='some-other-channel')Add your consumer(s) to your routerYou can use theirctype in channelsProtocolTypeRouterto connect
your new consumer to the interface server, and ensure
yourircmessages are delivered to the right place:from channels.routing import ProtocolTypeRouter
from myapp.consumers import MyIrcConsumer

application = ProtocolTypeRouter({
    'irc': MyIrcConsumer.as_asgi(),
})Start the interface serverThe interface server can be started by simply running this in the command line:channels-ircThe server requires that theserver,nickname, andapplicationproperties be
set. Theapplicationshould be an import string pointing to the location of
your app’s ASGI application. Hence, if your app was namedmyapp, contained an
ASGI file calledasgi.py, and your ASGI application is namedmy_application,
you could start the server by running:channels-irc -s 'irc.freenode.net' -n 'my_irc_nickname' -a 'myapp.asgi:my_application'You can also set these values using the env variablesCHANNELS_IRC_SERVER,CHANNELS_IRC_NICKNAME, andCHANNELS_IRC_LAYER.
Package: channelsmultiplexer
DjangoChannelsdoes not yet include a Multiplexing Consumer. This project aims to add such a multiplexer.Version CompatibilityChannels VersionChannels Multiplexer Versionv20.0.2v3>=0.0.3InstallpipinstallchannelsmultiplexerUsageto create a De-MultiplexerclassEchoDemultiplexerAsyncJson(AsyncJsonWebsocketDemultiplexer):applications={"echostream":EchoTestConsumer(),"altechostream":AltEchoTestConsumer(),"closeafterfirst":EchoCloseAfterFirstTestConsumer(),"neveraccept":NeverAcceptTestConsumer()}or you can use theAsyncJsonWebsocketDemultiplexertype directly and pass the multiplexed upstream consumers as kwargs.application=ProtocolTypeRouter({"websocket":URLRouter([url(r"^ws/$",AsyncJsonWebsocketDemultiplexer(echostream=EchoTestConsumer(),altechostream=AltEchoTestConsumer(),closeafterfirst=EchoCloseAfterFirstTestConsumer(),neveraccept=NeverAcceptTestConsumer())),]),"telegram":ChattyBotConsumer.as_asgi(),})This acts just as any other channels consumer, however it will route incoming (JSON) messages to the upstream Consumers.It does this by reading the value of thestreamattribute in the message body. It will then pass the value of thepayloadattribute upstream.{"stream":"echostream","payload":{"hello":"world"}}Messages being sent downstream from the Multiplexed consumers will be embedded within a similar style msg.
Package: channels-multiprocessing
RationalKeep thinks simple and stupid.Adding a redis service makes thinks more complicatedThis is a try to use plain python utilities to provide channels layer functionality without configurationideawe leverage multiprocessing for providing a channel layer. As multiprocessing doesn't play always nice with async
we use a per layer a Thread to serialize the internal requests.
Per default the default mp_context is used for creating the manager for multiprocessing synchronization
It may be set manually to "spawn" in case of an non python asgi server with multiple process workersUsageCHANNEL_LAYERS={"default":{"BACKEND":"channels_multiprocessing.MultiprocessingChannelLayer"}}with explicit contextCHANNEL_LAYERS={"default":{"BACKEND":"channels_multiprocessing.MultiprocessingChannelLayer","CONFIG":{"mp_context":"spawn",},}}Note: all options of BaseLayer are supported (e.g. capacity)Statetests passedTODOdocumentationinvestigate aioprocessing
Package: channels-redux
Channels-ReduxChannels-Redux is a package that notifies subscribers about changes in the databaseIt should be paired with thenpm package of the same name.
The pypi packagedjango-react-viewsis also useful for hydrating initial stateExposed ModulesNotifyConsumerThis is an AsyncWebsocketConsumer that allows clients to subscribe to different models and objects and sends frames
when subscribed objects are updated, created or deleted. Unless you plan on extending it's functionality you don't
need to do anything with this.NotifyRouterNotifyRouter is a channels.routing.URLRouter that defines a default URL that routes connections to NotifyConsumerNotifierMixinExtending this mixin marks a model as being a 'Notifier' this means that it will send frames to subscribed clients
when changes happen on the server side.This also defines a property that returns the name of the api url for the model. By default it assumes the namespace
of your api is 'api' this can be overridden by definingAPI_APP_NAMESPACEin your settings.HyperlinkedModelSerializerA drop-in replacement for DRF's HyperlinkedModelSerializer that fixes some issues with URL fields and relationships
in a namespaced apiRestRouterA drop-in replacement for DRF's DefaultRouter that should be used to assign the expected default base names for
your api urls.Quick StartAdd to installed appsINSTALLED_APPS=[...'channels_redux',]Models that you want clients to receive notifications about should extend the NotifierMixinSetup your models with Django Rest Framework with the following exceptions:Instead of the DRF's HyperlinkedModelSerializer you should use
channels_redux.rest.HyperlinkedModelSerializer. At minimum your serializers should include theurland thepkfields.User RestRouter instead of DefaultRouter for your api routesrouter=RestRouter()router.register(r'appname/modelname',viewsets.ModelNameViewSet)Setup django-channels. Follow their docs for this with the following exceptions:In routing.py use the NotifyRouterapplication=ProtocolTypeRouter({"websocket":AuthMiddlewareStack(NotifyRouter()),})channels-reduxrequireschannel layers, so be sure to set those up.Use django-react-views to provide the initial data to your frontendOn the frontend use channels-redux js to setup your redux state and WebsocketHandler before rendering any react components// In the root component that your page loads.import{WebSocketHandler,store}from'channels-redux';constwebSocketHandler=newWebSocketHandler(store);webSocketHandler.subscribeAll();
Package: channels-sendmail
Simple package to wrap Django’s built-insend_mailfunction with
channels, sending the mail with whichever backend you are using
asynchronously.InstallRequires Django 1.8+ and Channels.pipinstallchannels-sendmailUsageAdd to your routingchannel_routing=[# ...include('sendmail.routing.channel_routing'),]Use where you have useddjango.core.mail.send_mailin the past:fromsendmailimportsend_mailsend_mail(...)# Normal arguments to send_mailConfigurationCHANNELS_SENDMAIL_CHANNEL_NAMEwhich defaults to
“django.core.mail.send_mail”
Package: channels-slack-notifications
If you want to asyncronously send low priority messages to a
Slack channel usingDjango Channelsthis is the 3rd party library for you.Partially inspired by django-slackhttps://github.com/lamby/django-slack. Adding support for channels and simplying the interface.RequirementsDjango 1.8+channelsrequestsQuick StartAdd toINSTALLED_APPSand set your slack token:INSTALLED_APPS = (
  # ...
  'channels_slack_notifications',
  # ...
)

CHANNELS_SLACK_TOKEN = 'yourtokenhere'You can generate a tokens here:https://api.slack.com/web#authenticationAdd to yourrouting.py:from channels.routing import include
from channels_slack_notifications.routing import slack_routing

channels_routing = [
    include(slack_routing),
]Send your first notification:from channels import Channel

message = dict(
    text = 'this is a test',
)
Channel('slack-notifications').send(message)This uses a bunch of defaults which you can override per setting, or just in the message dict.You can use this management command to test your settings:python manage.py test_slack_notificationSettingsCHANNELS_SL ACK_TOKEN~~~~~~~~~~~~~~~~~~~~~~~~Default:NoneYour Slack authentication token.You can generate a tokens here:https://api.slack.com/web#authenticationCHANNELS_SLACK_CHANNELDefault:#generalUse this setting to set a default channel of the room the message should appear
in.You can override on a per-message level by specifyingchannelin your message dict.CHANNELS_SLACK_USERNAMEDefault:botUse this setting to set a default name the message will appear be sent from.You can override on a per-message level by specifyingusernamein your message dict.CHANNELS_SLACK_ICON_EMOJIDefault::robot:Use this setting to set a default icon emoji.You can override on a per-message level by specifyingicon_emojiin your message dict.CHANNELS_SLACK_BACKENDDefault:'channels_slack_notifications.backends.console'A string pointing to the eventual backend class that will actually send the
message to the Slack API.Use'channels_slack_notifications.backends.default'in product which uses the requests library.