Giter Site home page Giter Site logo

pysher's Introduction

PyPI version

Pysher

pysher is a python module for handling pusher websockets. It is based on @ekulyk's PythonPusherClient. A key difference is the dropped support for pre-3.5 Python versions.

This fork is meant as a continuation of the project, and is currently in maintenance mode.

The author is no longer actively using the library, but PRs including fixes, updates and features are welcome and encouraged.

Installation

Simply run python setup.py install - or install via pip pip install pysher.

This module depends on websocket-client module available from: http://github.com/websocket-client/websocket-client

Example

Example of using this pusher client to consume websockets:

import pysher

# Add a logging handler so we can see the raw communication data
import logging

root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
root.addHandler(ch)

pusher = pysher.Pusher(appkey)


def my_func(*args, **kwargs):
 print("processing Args:", args)
 print("processing Kwargs:", kwargs)


# We can't subscribe until we've connected, so we use a callback handler
# to subscribe when able
def connect_handler(data):
 channel = pusher.subscribe('mychannel')
 channel.bind('myevent', my_func)


pusher.connection.bind('pusher:connection_established', connect_handler)
pusher.connect()

while True:
 # Do other things in the meantime here...
 time.sleep(1)

Sending pusher events to a channel can be done simply using the pusher client supplied by pusher. You can get it here: https://github.com/pusher/pusher-http-python

import pusher
pusher.app_id = app_id
pusher.key = appkey

p = pusher.Pusher()
p['mychannel'].trigger('myevent', 'mydata')

Performance

Pysher relies on websocket-client (websocket-client on pyPI, websocket import in code), which by default does utf5 validation in pure python. This is somewhat cpu hungry for lot's of messages (100's of KB/s or more). To optimize this validation consider installing the wsaccel module from pyPI to let websocket-client use C-compiled utf5 validation methods (websocket does this automatically once wsaccel is present and importable).

Thanks

A big thanks to @ekulyk for developing the PythonPusherClient library, as well as the developers contributing bug-fixes, patches and other PRs to the project <3. You can find them listed next to their contributed change in the Changelog section.

Copyright

MTI License - See LICENSE for details.

Changelog

Version 1.0.8

Fixed

  • #70 Allow remote authentication without need of secret, thanks to @Matisilva

Version 1.0.6

Fixed

  • #55 Allow data fields to be empty for other events, too, thanks to @Rubensei

Version 1.0.5

Fixed

  • #53 Allow data fields to be empty, thanks to @Rubensei

Version 1.0.4

Fixed

  • Reverts a patch introduced in 1.0.3

Version 1.0.2

Fixed

  • #38 Fix missing ẁs arg for websocket app callbacks, thanks to @squgeim

Version 1.0.0

Updated

  • #35 Support websocket-client >0.48 only and fix reconnect error, thanks to @agronholm

This change may break existing setups and is backwards-incompatible!

Version 0.5.0

Added

  • #14 Added support for cluster configuration, thanks to @Yvictor

Fixed

  • #30 Require websocket-client version 0.48 or earlier.
  • #24 Signature generation now works as expected, thanks to @agronholm
  • #31 Name threads of the pysher lib for better debugging, thanks to @caliloo

Version 0.4.2

Fixed:

  • #11 Global Logger settings no longer overridden in Connection logger

Version 0.4.0

Added:

  • #8 Add support for WebSocket over HTTP proxy, thanks to @1tgr

Version 0.3.0

Added:

  • #7 Auto-resubscribe to channels after reconnecting, thanks to @pinealan

Fixed:

  • #4, #5 Updated references to the library name, thanks to @deanmaniatis

Version 0.2.0

Added:

  • #2 Allow for token generated by auth endpoint, thanks to @wardcraigj
  • #3 Allow instantiation with custom host, thanks to @wardcraigj

pysher's People

Contributors

1tgr avatar agronholm avatar benruijl avatar berentn avatar caliloo avatar craigjmidwinter avatar deepbrook avatar dependabot[bot] avatar ekulyk avatar fly-away avatar fuzeman avatar gravengaard avatar icook avatar mrichardson23 avatar onyxfish avatar pinealan avatar rubensei avatar squgeim avatar tomwilkie avatar xmurobi avatar yvictor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

pysher's Issues

How to store the 'channel' from the raw communication in a python variable?

Thanks so much for this library! I've got it streaming the information (for quoinex.com) to the screen using one of your examples, via both logging and print.

However, I'm finding that logging provides more information than print at the moment - logging includes event and channel. Is there a way to access these bits of information outside of logging?

The problem I have is that if I subscribe to lots of channels, I'm not sure how I'll identify which response belongs to which channel. An ugly workaround below is to create a callback function for each subscription, but I assume there is a far more elegant way.

Any help would be appreciated please!

import pysher
import sys
import time

# Add a logging handler so we can see the raw communication data
import logging
root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
root.addHandler(ch)

pusher = pysher.Pusher('XXXX') #key removed

def channel_callbacksell(message):
    response = "btcjpy_sell: %s" % message
    print(response)
    
def channel_callbackbuy(message):
    response = "btcjpy_buy: %s" % message
    print(response)
    
def connect_handler(data):
    channelsell = pusher.subscribe('price_ladders_cash_btcjpy_sell')
    channelsell.bind('updated', channel_callbacksell)
    channelbuy = pusher.subscribe('price_ladders_cash_btcjpy_buy')
    channelbuy.bind('updated', channel_callbackbuy)
        
pusher.connection.bind('pusher:connection_established', connect_handler)
pusher.connect()

while True:
    time.sleep(1)

The results I get to screen are:

Logging Output (with 'event' and 'channel'):

{"event":"updated","channel":"price_ladders_cash_btcjpy_buy","data":"[[\"902803.86848\",\"0.53500000\"],[\"902525.42000\",\"0.24500000\"],[\"902500.00000\",\"0.35320000\"],[\"902041.67444\",\"0.23510000\"],[\"901864.00000\",\"0.01856800\"],[\"901525.40000\",\"0.02000000\"],[\"901518.40000\",\"0.08000000\"],[\"900968.40000\",\"0.02000000\"],[\"900967.63000\",\"0.01609600\"],[\"900936.40000\",\"0.02000000\"],[\"900830.39000\",\"0.02000000\"],[\"900620.00000\",\"2.00000000\"],[\"900532.41000\",\"0.01000000\"],[\"899420.00000\",\"0.01000000\"],[\"899394.25718\",\"0.09366000\"],[\"899379.78211\",\"0.09459000\"],[\"899344.29123\",\"0.18108000\"],[\"899326.67050\",\"0.10873000\"],[\"899244.96171\",\"0.42860000\"],[\"899209.18772\",\"0.42569000\"],[\"899194.03279\",\"0.43184000\"],[\"899182.76156\",\"0.18316000\"],[\"899111.77941\",\"0.42505000\"],[\"899065.00000\",\"1.10000026\"],[\"899064.65503\",\"0.83353000\"],[\"899024.92879\",\"0.74487000\"],[\"899000.00000\",\"0.07000000\"],[\"898784.00000\",\"2.37200000\"],[\"898774.00000\",\"0.10000000\"],[\"898733.00000\",\"2.36500000\"],[\"898710.00000\",\"0.02000000\"],[\"898593.50106\",\"0.87417000\"],[\"898517.91761\",\"0.99008000\"],[\"898504.00000\",\"0.00900000\"],[\"898467.31863\",\"3.68813000\"],[\"898121.09000\",\"3.00000000\"],[\"898000.00000\",\"0.07000000\"],[\"897457.94012\",\"4.23122000\"],[\"897337.00000\",\"2.37200000\"],[\"897000.00000\",\"0.07000000\"]]"}

Print Output (with just 'data'):

[["902803.86848","0.53500000"],["902525.42000","0.24500000"],["902500.00000","0.35320000"],["902041.67444","0.23510000"],["901864.00000","0.01856800"],["901525.40000","0.02000000"],["901518.40000","0.08000000"],["900968.40000","0.02000000"],["900967.63000","0.01609600"],["900936.40000","0.02000000"],["900830.39000","0.02000000"],["900620.00000","2.00000000"],["900532.41000","0.01000000"],["899420.00000","0.01000000"],["899394.25718","0.09366000"],["899379.78211","0.09459000"],["899344.29123","0.18108000"],["899326.67050","0.10873000"],["899244.96171","0.42860000"],["899209.18772","0.42569000"],["899194.03279","0.43184000"],["899182.76156","0.18316000"],["899111.77941","0.42505000"],["899065.00000","1.10000026"],["899064.65503","0.83353000"],["899024.92879","0.74487000"],["899000.00000","0.07000000"],["898784.00000","2.37200000"],["898774.00000","0.10000000"],["898733.00000","2.36500000"],["898710.00000","0.02000000"],["898593.50106","0.87417000"],["898517.91761","0.99008000"],["898504.00000","0.00900000"],["898467.31863","3.68813000"],["898121.09000","3.00000000"],["898000.00000","0.07000000"],["897457.94012","4.23122000"],["897337.00000","2.37200000"],["897000.00000","0.07000000"]]

Configuring the logger overrides what is configured in logging.config

here:

https://github.com/nlsdfnbch/Pysher/blob/master/pysher/connection.py#L40-L43

The level is forced on the logger that is created. This will override any configuration of the logger using the standard logging.config module, for example: dictConfig or fileConfig.

So for example, if I do this in my logging config:

'loggers': {
                'pysher.connection': {
                    'level': 'WARNING',
                    'handlers': ['stream'],
                    'propagate': 'no'
                }
            }

Even though I have explicitly specified the level I want, the act of initializing the Connection object overrides my decision silently.

My proposed solve for this problem is to just omit line 43:

https://github.com/nlsdfnbch/Pysher/blob/master/pysher/connection.py#L43

Then it will play nice the built in python logging/logging configuration system.

Consumer example not working

I'm trying to use latest pysher version, however the example in README.md is not working:

error from callback <bound method Connection._on_open of <Connection(PysherEventLoop, started daemon 139662709860096)>>: _on_open() takes exactly 2 arguments (1 given) error from callback <bound method Connection._on_message of <Connection(PysherEventLoop, started daemon 139662709860096)>>: _on_message() takes exactly 3 arguments (2 given) error from callback <bound method Connection._on_error of <Connection(PysherEventLoop, started daemon 139662709860096)>>: _on_error() takes exactly 3 arguments (2 given) Connection: Connection closed

Versions:

websocket-client==0.53.0
Pysher Version: 1.0.3

in addition, the example code misses imports of time and sys.

Channel callback doesn't fire

Tried implementing basic example. The 'data' event doesn't seem to be firing.

import pysher
import time

def channel_callback(data):
    print(data)

def connection_callback(data):
    channel = pusher.subscribe("order_book_BTC_USD")
    channel.bind("data", channel_callback)
    
pusher = pysher.Pusher("de504dc5763aeef9ff52")
pusher.connection.bind("pusher:connection_established", connection_callback)
pusher.connect()

while True:
    time.sleep(1)

Getting data in a variable

Hey thanks for your skript!
I tries your code with a specific website (Bitstamp)

The data that is printed is some kind of a dictionary. what I want is to get that dict written on a variable to use it like My_dict = 'The data I'm receiving via websocket' and later work with pandas or indexing.

Thanks in advance!

Robin

PS:I don't see the difference between args and kwargs here.

my code just in case:

import pysher
import sys
import time


import logging
root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
root.addHandler(ch)

pusher = pysher.Pusher('de504dc5763aeef9ff52')

def  my_func(*args, **kwargs):
    print("processing Args:", args)
    print("processing Kwargs:", kwargs)


def connect_handler(data):
    channel = pusher.subscribe('order_book')
    channel.bind('data', my_func)

pusher.connection.bind('pusher:connection_established', connect_handler)
pusher.connect()

while True:
	time.sleep(1)

Question: Connection Message vs Callback print outs

Hello,

first, thanks for the script it is great and saved me a lot of work!

I want to ask how it comes that the prints of the logger (Connection Message ...) seems to print a lot more data than the callback function?
Some data of the logger is equal but neverthless I do not understand how it comes that there is big number of lines which are not printed by the callback function.

Thanks in advance for answer my question.
Best regards
Bruno

huge number of threads spin up for lot's of messages processing.

Hi,

I'm using pysher which works for me -so thanks !- but with some caveats. I'm connected to a pusher channel sending 10's or 100's of message per second, each a few B to 0.5MB in size (bigger rarer following a log rule).

I observe fairly high cpu usage on the process using the library, and that has caused me trouble on low end machines (Atom N2800 @ 1.8Ghz). higher end machines (i3) take up the load without problems.

So looking at cpu usage and profiling a bit, I find 2 things fairly odd. One, it seems 2 threads are spun off for each message call back call and die thereafter. But the call back is not processed in the context of either of those 2 threads, it is processed in the context of the main websocket app thread, it seems.
ok, that's fair enough, why not.

I'm not sure why those 2 threads are spun off, and do what, then die. The other thing is that these threads are definitely created in the websocket module, as far as I can make out.

I'm hoping to reduce the cpu load that pysher uses to receive messages. Not sure if that will be achieved by changing the threading situation or something, but thought worth mentioning the thread behaviour, as I found it unusual (I quickly get into 10k 's of threads created and destroyed after a few minutes) and certainly it seems related to cpu consumption.

It's late for me, so I'm hanging off for today, I'm happy to work on solving this later, but thru this message hoping to get some kind of hint or architectural description that may help me start on it at least. (and who knows, maybe it'll get solved while I sleep :) )

Cheers.

Secret keys do not work on Python 3

This happens because you're passing a unicode string to hmac.new(), but hashes operate on bytestrings, not unicode strings. The result: TypeError: Unicode-objects must be encoded before hashing.

Invalid number of arguments to `_on_open` and `_on_message` callbacks

When trying to implement a simple script following the given example the following errors are shown:

error from callback <bound method Connection._on_open of <Connection(PysherEventLoop, started daemon 123145544798208)>>: _on_open() takes 1 positional argument but 2 were given
error from callback <bound method Connection._on_message of <Connection(PysherEventLoop, started daemon 123145544798208)>>: _on_message() takes 2 positional arguments but 3 were given
Connection: Connection closed

When checking out the documentation for websocket-client, the implementation given in its example does not seem to match the implementation in connection.py.

Pysher version: 1.0.1 (installed with pip)
websocket-client version: 0.52.0
Python version: 3.7.0
OS: Mac OS X (Mojave)

Reconnect after receive Error 4201

In my project I receive the following Error and my app reconnect to the pusher service. The Error fires al lot of times while running the app over a day.
pysher.connection:Connection: Received error 4201
Connection: Received error 4201
websocket:close status: 4201
close status: 4201 `

I use Python 3.7.11 and pysher 1.0.4 with websocket-client 0.57.0.

What can I do to prevent my app from this error and the reconnect?

v1.x doesn't work for me

I have tried version 1 and 1.02 but can not connect to pusher and get following error messages:

error from callback <bound method Connection._on_open of <Connection(Thread-1, started daemon 140250322847488)>>: _on_open() missing 1 required positional argument: 'ws'
error from callback <bound method Connection._on_message of <Connection(Thread-1, started daemon 140250322847488)>>: _on_message() missing 1 required positional argument: 'message'

websocket-client==0.49.0 -> _on_open() missing 1 required positional argument: 'ws'

Hey,

The recently released websocket-client==0.49.0 seems to have broken this library:

error from callback <bound method Connection._on_open of <Connection(Thread-1, started daemon 123145309167616)>>: _on_open() missing 1 required positional argument: 'ws'
error from callback <bound method Connection._on_message of <Connection(Thread-1, started daemon 123145309167616)>>: _on_message() missing 1 required positional argument: 'message'

I see you specify the websocket-client==0.48.0 in the requirements.txt, but that doesn't seem to be respected in the setup.

Installing pysher…
Collecting pysher
  Using cached https://files.pythonhosted.org/packages/02/6e/bd0804087be5f432fe2407b8bf00b2abc95f7475274fdc26e82f7d4db0cb/Pysher-0.5.0-py3-none-any.whl
Collecting websocket-client (from pysher)
  Using cached https://files.pythonhosted.org/packages/8c/59/613755914b733a490982e8c9bb666636dc7362c35beafe32df7fbc6bbf4e/websocket_client-0.49.0-py2.py3-none-any.whl
Collecting six (from websocket-client->pysher)
  Using cached https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl
Installing collected packages: six, websocket-client, pysher
Successfully installed pysher-0.5.0 six-1.11.0 websocket-client-0.49.0

Adding pysher to Pipfile's [packages]…
Installing dependencies from Pipfile.lock (0326cd)…

Getting initial socket_id for auth endpoint - Docs request

Similar to #22

Server:
const auth = pusher.authenticate(socket_id, channel_name);
socket_id and channel_name are required for the auth payload to the endpoint.

Client:
How does one get the initial socket_id to post to an auth endpoint to get the auth string during the initialization of the client?

Currently the private channel example has the secret passed in via an command line argument.
https://github.com/nlsdfnbch/Pysher/blob/master/examples/private.py

Perhaps an example of subscribing to a private channel with an auth endpoint could be added to the docs.

Write proper unittests for library

the current testing setup is still identical to the originally forked project's test-suite. As it is no longer up-to-date with this fork, it needs an update.

This should be done using a unittest suite, using pytest, and an integration test suite (similar to the legacy test code).

UnitTest cases :

  • assert robustness of system message handling (messages sent by Pusher to us should be handled correctly).
  • URLs for websocket connection is built correctly.
  • connection state updates are handled correctly.

Integration tests:

  • connect to pusher using credentials.
  • subscribing to a channel works.
  • unsubscribing from a channel works.
  • pings invoke a pong response.
  • registering a callback works for single event per channel.
  • registering callbacks for multiple events per channel works.

Unsatisfied requirements when upgrading to 1.0.4 from 0.5.0

Hello, I used Pysher==0.5.0. I upgraded to version 1.0.4 but I did not received new messages from websocket. The problem was with unsatisfied version of websocket-client. In requirements.txt is mentioned websocket-client==0.51.0 but I had only 0.48.0. I think, it should be updated properly when installed new version of Pysher or at least, it should informed me about unmatching versions. This is what I received when I installed Pysher version 1.0.4.

pip3 install Pysher==1.0.4
Collecting Pysher==1.0.4
  Using cached https://files.pythonhosted.org/packages/0e/ca/0e4b7d71944e6244da5fdccca51bb49e047fe295925e899776b919f6e638/Pysher-1.0.4-py3-none-any.whl
Requirement already satisfied: websocket-client!=0.49 in /usr/local/lib/python3.6/dist-packages (from Pysher==1.0.4)
Requirement already satisfied: six in /usr/lib/python3/dist-packages (from websocket-client!=0.49->Pysher==1.0.4)
Installing collected packages: Pysher
  Found existing installation: Pysher 0.5.0
    Uninstalling Pysher-0.5.0:
      Successfully uninstalled Pysher-0.5.0
Successfully installed Pysher-1.0.4

According to me, it should not print Requirements already satisfied.

When I installed websocket-client=0.51.0, it works without any problem.
When I installed (without upgrade) Pysher==1.0.4 in new virtual env , it works without any problem.

Support websocket path for custom host

The Pusher js client supports a websocket path so you can use a url like ws://example.test/ws/app/pusher-key?protocol=7&client=js&version=7.0.0&flash=false for a custom url where the host is example.txt and the path is /ws.

Reconnect after connection error 4200 or similar fails

When encountering connection error 4200 or similar, the pysher code obviously tries to re-establish the websocket connection more than once and then fails, see logs below.

Thereafter no further messages from pusher are received unless the script is restarted manually.
Unfortunately this is really bad for my use case.

I have tried setting the flag self.needs_reconnect to False in the function "def _connect(self)" before the while statement, but then encountered other issues.
Any hints how to make reconnect after connection errors work automatically?

Log messages:

Connection: Received error 4200
close status: 4200
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.5/dist-packages/pysher/connection.py", line 94, in run
self._connect()
File "/usr/local/lib/python3.5/dist-packages/pysher/connection.py", line 118, in _connect
self.socket.run_forever(**self.socket_kwargs)
File "/usr/local/lib/python3.5/dist-packages/websocket/_app.py", line 203, in run_forever
raise WebSocketException("socket is already opened")
websocket._exceptions.WebSocketException: socket is already opened

1.0.5 Install error

Error installing version 1.0.5.linux-x86_64 with pip

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-ts394rq3\\pysher\\setup.py'

PS: pip will install 1.0.4 by default if you don't specify version

Thread exception

Hi,
when received error 4xxx, the connection performs reconnect, but it seems the websocket thread exception raised because of socket re-open, and then the thread exits. You can see the following 'ping' get no 'pong' respond(2018-04-08 22:32:26,969 ping), and can not reconnect any more unless restart the program. It happens one time in several hours.
Here is the log information from connection.py:

2018-04-08 22:30:26,962 - connection.py[line:278] - ERROR: Connection: Received error 4201
2018-04-08 22:30:26,963 - connection.py[line:88] - INFO: start Reconnect:0
2018-04-08 22:30:26,963 - connection.py[line:92] - INFO: Connection: Reconnect in 0
2018-04-08 22:30:26,963 - connection.py[line:97] - INFO: socket.close() start
close status: 4201
2018-04-08 22:30:26,964 - connection.py[line:99] - INFO: socket.close() ok
2018-04-08 22:30:26,971 - connection.py[line:125] - INFO: Attempting to connect again in 0 seconds.
2018-04-08 22:30:26,971 - connection.py[line:133] - INFO: self.socket.run_forever start
Exception in thread Thread-1:
Traceback (most recent call last):
File "/home/ubuntu/.pyenv/versions/3.6.4/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/home/ubuntu/work/dataapi/python/pysher/connection.py", line 102, in run
self._connect()
File "/home/ubuntu/work/dataapi/python/pysher/connection.py", line 134, in _connect
self.socket.run_forever(**self.socket_kwargs)
File "/home/ubuntu/.pyenv/versions/3.6.4/lib/python3.6/site-packages/websocket/_app.py", line 203, in run_forever
raise WebSocketException("socket is already opened")
websocket._exceptions.WebSocketException: socket is already opened

2018-04-08 22:32:26,969 - connection.py[line:221] - INFO: Connection: ping to pusher
2018-04-08 22:32:26,969 - connection.py[line:225] - ERROR: Failed send ping: socket is already closed.
2018-04-08 22:35:31,972 - connection.py[line:298] - INFO: connection_timed_out:Did not receive any data in time. Reconnecting.
2018-04-08 22:35:31,972 - connection.py[line:88] - INFO: start Reconnect:None
2018-04-08 22:35:31,972 - connection.py[line:92] - INFO: Connection: Reconnect in 10
2018-04-08 22:35:31,972 - connection.py[line:97] - INFO: socket.close() start
2018-04-08 22:35:31,972 - connection.py[line:99] - INFO: socket.close() ok

How to get up and running?

I've tried everything to start up, but nothing seems to work... I filled in the appkey and channel name and event name. But it doesn't seem to to run. Are there any other option of getting it up and running?

Pass proxy config as single dict

Currently, the Pysher.__init__ method takes parameters for proxy configuration - this clutters the method signature in an undesired fashion. Since we compound the parameters into a dictionary anyway, require the proxy configuration to be passed as a single dictionary in the init call instead.

Cut a new release

Looks like there hasn't been a release cut since the fix for the new version of websocket-client was merged in. Could we cut a release and push to pypi?

PR with updated support: #67

Private Channel Error

Hi, i'm trying to subscribe to a private channel, but it gives me some error. I know what the error means I just needed to know how to send the right data on the request:
The error says:

"Auth value for subscription to private-message-answered-5 is invalid: should be of format 'key:signature'"

I need to call my auth endpoint that is /broadcast/auth, and I also need to pass a token on header, when calling the pusher.subscribe method

Does anybody knows how can I achieve that ?

Soketi Support/disconnection error

Hello!

Does this have soketi support? Currently trying to get it working but my client keeps disconnecting when pysher sends the "ping to pusher" message, any ideas?

Cluster error

When trying to use the example code it throws an error:

Connection: Connection opened
Connection: ping to pusher
Connection: Message - {"event":"pusher:error","data":{"code":4001,"message":"Did you forget to specify the cluster when creating the Pusher instance?  App key XXXXX does not exist in this cluster."}}
Connection: Received error 4001
Connection: Error is unrecoverable.  Disconnecting
Callback raised unhandled

After checking the code I can't see any cluster option for the Pusher constructor. :( Am I missing something? (I'm completly new to python)

Release tag for 1.0.1 missing

Hi Nils,

hope you don't mind I am using your component in Home Assistant Gentoo Overlay, ebuilds: https://github.com/onkelbeh/HomeAssistantRepository/tree/master/dev-python/Pysher.

Home Assistant currently relies on pysher==1.0.1 for the goalfeed integration.

You do not publish SDIST for this release on Pypi, and you did not add a tag for 1.0.1 here.
To get a valid source, I forked it, and created the missing tag for it.

Could you please snap a release or add a tag for 1.0.1 so I could get rid of the fork?

Thanks a lot.

Callback function not calling

I'm having problems to call a callback function when trying to subscribe to a channel. The loggin says it has successfuly connected, and I can receive the events on the logs, but the callback function has not been calling.

I made a test function but its not working. What am I doing wrong ?

channel = self.pusher.subscribe(channel_name=channel_name, auth=auth)
channel.bind('MessageAnswered', callback=self.teste)

Tests Failing with ConnectionRefused Error

Failing job:
https://travis-ci.org/nlsdfnbch/Pysher/jobs/347850850

Log:

$ python tests/test_pusherclient.py
ws://127.0.0.1:9000/app/mykey?client=PythonPusherClient&version=0.2.0&protocol=6
Connection: Error - [Errno 111] Connection refused
Connection: Connection closed
Attempting to connect again in 1 seconds.
Connection: Error - [Errno 111] Connection refused
Connection: Connection closed
Attempting to connect again in 1 seconds.
Server: onConnect
Server: onOpen
Server: sendEvent pusher:connection_established
Connection: Connection opened
Connection: ping to pusher
Server: onMessage
Server: sendEvent pusher:pong
Connection: Message - {"event": "pusher:connection_established", "data": "{\"socket_id\": \"testid\"}"}
Connection: Sending event - {'event': 'pusher:subscribe', 'data': {'channel': 'test_channel'}}
Server: onMessage
Server: sendEvent test_event
Connection: Message - {"event": "pusher:pong", "data": "\"\""}
Connection: pong from pusher
Connection: Message - {"event": "test_event", "data": "{\"message\": \"test\"}", "channel": "test_channel"}
Client: {"message": "test"}
Connection: Error - 0
The command "python tests/test_pusherclient.py" exited with 2.
Done. Your build exited with 1.

Pysher 1.0.6 not compatible with websocket-client==0.58.0

This is due to:
websocket-client/websocket-client@3112b7d

error from callback <bound method Connection._on_message of <Connection(PysherEventLoop, started daemon 123145690574848)>>: _on_message() takes 2 positional arguments but 3 were given
error from callback <bound method Connection._on_message of <Connection(PysherEventLoop, started daemon 123145707364352)>>: _on_message() takes 2 positional arguments but 3 were given
error from callback <bound method Connection._on_open of <Connection(PysherEventLoop, started daemon 123145724153856)>>: _on_open() takes 1 positional argument but 2 were given
error from callback <bound method Connection._on_message of <Connection(PysherEventLoop, started daemon 123145724153856)>>: _on_message() takes 2 positional arguments but 3 were given
error from callback <bound method Connection._on_open of <Connection(PysherEventLoop, started daemon 123145740943360)>>: _on_open() takes 1 positional argument but 2 were given
error from callback <bound method Connection._on_message of <Connection(PysherEventLoop, started daemon 123145740943360)>>: _on_message() takes 2 positional arguments but 3 were given

Connection.needs_reconnect isn't reset

Whenever self.needs_reconnect is set to True due to missed ping message or timing out, it never gets set back to False. I would recommend putting the line self.needs_reconnect = False in the method Connection._on_open. I might be misunderstanding the design incorrectly, but the way it is now will have self.needs_reconnect set to True after the socket has already reconnected and is receiving messages. Thanks for reading

Is it possible to connect Pysher to a Laravel-Websockets server

Hello,

I'm tried to refactor a project away from using Pusher to Laravel-Websockets.

Has anyone tried this or had any success, I'm trying the following

def init_channel_join(self):
    print('init channel join')
    self.clientPusher = pysher.Pusher(self.app_key, cluster=self.app_cluster, log_level=logging.DEBUG, custom_host="www.projectwebsite.com", port=6001)
    self.clientPusher.connection.bind('pusher:connection_established', self.connect_handler)
    self.clientPusher.connect()

def connect_handler(self, data):
    print('connected')
    self.channel = self.clientPusher.subscribe(self.data_channel)
    print('subscribed')
    print('binding')
    self.channel.bind('App\\Events\\update', self.pusher_callback)

def pusher_callback(self, message):
    print(data)

I get a 'init channel join' message but it never connects, I'm wondering if I'm doing something wrong or whether the laravel-websocket (Pusher drop in replacement) is just the wrong protocol or something else entirely.

Thanks

Closed socket from time to time

Issue:

Hi, I am using this library and from time to time, I have registered that my websocket stopped working. I tried to debug it, and find out, socket is missing but no error message is logged.

Now, lets show some example. I dockerized (the same problem was discovered even when the application was not dockerized) my application and find out via netstat command, I have opened socket with destination port 443:

docker exec mywebsocket /bin/netstat -tpn
tcp        0      0 172.23.0.13:56340      1.2.3.4:443       ESTABLISHED 1/python3

When I check it with my websocket app that did not receive any messages for a long time, I find out there is no opened socket, but also no errors in output (I checked docker logs and also my app logs):

docker exec mywebsocket /bin/netstat -tpn 

My fix:

I implemented function check_websocket_connection() and insert it inside while loop after sleep:

import os
import psutil
import logging

logger = logging.getLogger()

process = psutil.Process(os.getpid())

def check_websocket_connection():
    for connection in process.connections():
        if connection.raddr.port == 443 and connection.status == 'ESTABLISHED':
            logger.debug('Connections on port 433 is established.')
            return True
        
        return False
while True:
    # Do other things in the meantime here...
    time.sleep(1)
    if not check_websocket_connection():
        logger.error('Missing socket')
        break 

It check every second if there exists some connection with destination port 443 created by programs PID. I know, it can't be used if PID use more than one connection with port 443, but I need only this connection so it works.

This is just snippet, I created whole class with logging, I hope I did not make any mistake here.

It works for now, but is there a better way how to solve it?

Async pysher

Can you provide an example on how to use this library asynchronously.?

Process the received data

Hi, thank you a lot for this great package.

How could I process the received data? I don't want to just log (print) it in the console using logging.getLogger()

Particularly I would like to make some calculations, for example, calculate the greatest number of a list received via pusher connection and send this number it via Django Channels to client side or just save it in the DataBase.

Hint studying your code I think I have to edit event_handler or _on_messsage, but I'm not sure.

Thank you 😃

Error

Lately I periodically get an error like this. What is the reason for this?
Pysher 1.0.1 (cuz 1.0.2 and 1.0.3 not working for me. I don't know why)
websocket-client 0.53

ERROR:websocket:error from callback <bound method Connection._on_message of <Connection(PysherEventLoop, started daemon 8476)

not working with last version

working with Pysher 1.0.1
not working with Pysher 1.0.2 and 1.0.3
websocket-client 0.53

Please help :)

import pysher, json, time


def callback(data):
    event = json.loads(data)
    print(event)


def connection_callback(data):
    channel = pusher.subscribe("inventory_changes")
    channel.bind("listed", callback)
    channel.bind("price_changed", callback)
    channel.bind("delisted_or_sold", callback)
    channel.bind("extra_info", callback)


pusher = pysher.Pusher(key='c0eef4118084f8164bec65e6253bf195', custom_host='notifier.bitskins.com', port=443)
pusher.connection.bind("pusher:connection_established", connection_callback)
pusher.connect()

while True:
    time.sleep(1)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.