Coder Social home page Coder Social logo

wwww-wwww / phxsocket Goto Github PK

View Code? Open in Web Editor NEW
17.0 2.0 5.0 43 KB

Phoenix websocket client for Python

Home Page: https://pypi.org/project/phxsocket

License: GNU General Public License v3.0

Python 100.00%
python python3 phoenix-elixir phoenix-framework phoenix-channels websocket websockets websocket-client

phxsocket's Introduction

phxsocket

Synchronous phoenix websocket client using callbacks

Phoenix channels

Requirements

websockets

Usage

Import the package

import phxsocket

Create socket client

# endpoint.ex
socket "/socket", MyAppWeb.Socket, websocket: true, longpoll: false
socket = phxsocket.Client("wss://target.url/socket/websocket", {"name": "my name"})

Socket params go to Phoenix.Socket connect/3

Connect and join a channel

# mysocket.ex
defmodule MyAppWeb.Socket do
  use Phoenix.Socket

  channel("channel:*", MyAppWeb.Channel)

  def connect(%{"name" => name} = params, socket, _connect_info) do
    {:ok, socket |> assign(name: name)}
  end

  def id(socket), do: nil
end

defmodule MyAppWeb.Channel do
  use Phoenix.Channel

  def join("channel:" <> room_name, %{"password" => password}, socket) do
    if password == "1234" do
      {:ok, socket}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end
end
if socket.connect(): # blocking, raises exception on failure
  channel = socket.channel("channel:my room", {"password": "1234"})
  resp = channel.join() # also blocking, raises exception on failure

Alternatively

def connect_to_channel(socket):
  channel = socket.channel("channel:my room", {"password": "1234"})
  resp = channel.join()

socket.on_open = connect_to_channel
connection = socket.connect(blocking=False)

connection.wait() # blocking, raises exception on failure

Reconnect on disconnection

socket.on_close = lambda socket: socket.connect()

Subscribe to events

def do_something(payload):
  content = payload["content"]

channel.on("message", do_something)
MyAppWeb.Endpoint.broadcast("channel:my room", "message", %{"content": "hello"})

Push data to a channel

defmodule MyAppWeb.Channel do
...
def handle_in("message", %{"content" => content}, socket) do
  IO.inspect("received from #{socket.assigns.name}: #{content}")
  {:reply, {:ok, "hello"}, socket}
end
channel.push("message", {"content": "hello"})

This throws away the reply if the return value of handle_in is :reply

Push data and wait for a response

message = channel.push("message", {"content": "hello"}, reply=True)
payload = message.wait_for_response() # blocking

Push data and react to the response with a callback

def response(payload):
  print(payload["status"]) # ok
  print(payload["response"]) # hello

channel.push("message", {"content": "hello"}, response)

Leave a channel

channel.leave()

Disconnect

socket.close()

phxsocket's People

Contributors

andrewwljackson avatar wwww-wwww avatar

Stargazers

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

Watchers

 avatar  avatar

phxsocket's Issues

Support python3.10: "unexpected keyword argument 'loop'"

I'm getting the following traceback when trying to open a channel on a connected socket (following the example from the readme):

ERROR:root:phxsocket: Traceback (most recent call last):
  File "/home/work/.local/lib/python3.11/site-packages/phxsocket/client.py", line 109, in run
    loop.run_until_complete(
  File "/usr/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/home/work/.local/lib/python3.11/site-packages/phxsocket/client.py", line 97, in _run
    await asyncio.wait({listen, shutdown, broadcast},
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: wait() got an unexpected keyword argument 'loop'

According to the python asincio docs the loop argument was removed in python 3.10.

newly setup phx channels not supported?

using the Usage section on a newly setup phx channels project yields
websockets.exceptions.InvalidStatusCode: server rejected WebSocket connection: HTTP 200

Impossible to join a channel to the socket

Hello

You can find below a code snippet using phxsocket.

def connect_to_channel(socket: Client):

    print('OLITESTESTEST')
    channel = socket.channel("collection:boredapeyachtclub", {"payload": "{}"})
    resp = channel.join()

    print(f'OLI - Check channel is connected: {resp}')


def process_data(msg: Message):
    print(f'New data at {datetime.now()}: {msg}')

    if msg.event in [event.value for event in OpenseaStreamEvents]:

        data = msg.payload
        event_type = data['event_type']
        event_data = data['payload']
        event_data['event_type'] = event_type

        events.append(event_data)


socket = Client("wss://stream.openseabeta.com/socket/websocket", {'token': os.getenv('API_KEY_OPENSEA')})

socket.on_open = connect_to_channel
socket.on_message = process_data

print('Connecting...')
connection = socket.connect(blocking=False)

When running in a Jupyter notebook, everything works fine.
However, in a python script, the code above doesn't work. When stopping the code and checking the channels joined to the socket, I get an empty dictionary whereas in the notebook the dictionary contains the channel added in the connect_to_channel function.

Do you have an idea why is this happening ? thank you

Latest Release

Hi there,

This repo looks awesome. Pip installing phxsocket seems to install an earlier version of your code. Could you release the latest version? I'm excited to try and use it!

Thanks so much

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.