Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Aug 21, 2025. It is now read-only.
/realtime-pyPublic archive

A Python Client for Phoenix Channels

License

NotificationsYou must be signed in to change notification settings

supabase/realtime-py


Supabase Logo

Supabase Realtime Client

Send ephemeral messages withBroadcast, track and synchronize state withPresence, and listen to database changes withPostgres Change Data Capture (CDC).

Guides ·Reference Docs ·Multiplayer Demo

Overview

This client enables you to use the following Supabase Realtime's features:

  • Broadcast: send ephemeral messages from client to clients with minimal latency. Use cases include sharing cursor positions between users.
  • Presence: track and synchronize shared state across clients with the help of CRDTs. Use cases include tracking which users are currently viewing a specific webpage.
  • Postgres Change Data Capture (CDC): listen for changes in your PostgreSQL database and send them to clients.

Usage

Installing the Package

pip3 install realtime

Creating a Channel

importasynciofromtypingimportOptionalfromrealtimeimportAsyncRealtimeClient,RealtimeSubscribeStatesasyncdefmain():REALTIME_URL="ws://localhost:4000/websocket"API_KEY="1234567890"socket=AsyncRealtimeClient(REALTIME_URL,API_KEY)channel=socket.channel("test-channel")def_on_subscribe(status:RealtimeSubscribeStates,err:Optional[Exception]):ifstatus==RealtimeSubscribeStates.SUBSCRIBED:print("Connected!")elifstatus==RealtimeSubscribeStates.CHANNEL_ERROR:print(f"There was an error subscribing to channel:{err.args}")elifstatus==RealtimeSubscribeStates.TIMED_OUT:print("Realtime server did not respond in time.")elifstatus==RealtimeSubscribeStates.CLOSED:print("Realtime channel was unexpectedly closed.")awaitchannel.subscribe(_on_subscribe)

Notes:

  • REALTIME_URL isws://localhost:4000/socket when developing locally andwss://<project_ref>.supabase.co/realtime/v1 when connecting to your Supabase project.
  • API_KEY is a JWT whose claims must containexp androle (existing database role).
  • Channel name can be anystring.

Broadcast

Your client can send and receive messages based on theevent.

# Setup...channel=client.channel("broadcast-test", {"config": {"broadcast": {"ack":False,"self":False}}})awaitchannel.on_broadcast("some-event",lambdapayload:print(payload)).subscribe()awaitchannel.send_broadcast("some-event", {"hello":"world"})

Notes:

  • Settingack totrue means that thechannel.send promise will resolve once server replies with acknowledgement that it received the broadcast message request.
  • Settingself totrue means that the client will receive the broadcast message it sent out.
  • Settingprivate totrue means that the client will use RLS to determine if the user can connect or not to a given channel.

Presence

Your client can track and sync state that's stored in the channel.

# Setup...channel=client.channel("presence-test",    {"config": {"presence": {"key":""            }        }    })channel.on_presence_sync(lambda:print("Online users: ",channel.presence_state()))channel.on_presence_join(lambdanew_presences:print("New users have joined: ",new_presences))channel.on_presence_leave(lambdaleft_presences:print("Users have left: ",left_presences))awaitchannel.track({'user_id':1 })

Postgres CDC

Receive database changes on the client.

# Setup...channel=client.channel("db-changes")channel.on_postgres_changes("*",schema="public",callback=lambdapayload:print("All changes in public schema: ",payload),)channel.on_postgres_changes("INSERT",schema="public",table="messages",callback=lambdapayload:print("All inserts in messages table: ",payload),)channel.on_postgres_changes("UPDATE",schema="public",table="users",filter="username=eq.Realtime",callback=lambdapayload:print("All updates on users table when username is Realtime: ",payload    ),)channel.subscribe(lambdastatus,err:status==RealtimeSubscribeStates.SUBSCRIBEDandprint("Ready to receive database changes!"))

Get All Channels

You can see all the channels that your client has instantiated.

# Setup...client.get_channels()

Cleanup

It is highly recommended that you clean up your channels after you're done with them.

  • Remove a single channel
# Setup...channel=client.channel('some-channel-to-remove')channel.subscribe()awaitclient.remove_channel(channel)
  • Remove all channels
# Setup...channel1=client.channel('a-channel-to-remove')channel2=client.channel('another-channel-to-remove')awaitchannel1.subscribe()awaitchannel2.subscribe()awaitclient.remove_all_channels()

Credits

This repo draws heavily fromphoenix-js.

License

MIT.

About

A Python Client for Phoenix Channels

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

 

Contributors28


[8]ページ先頭

©2009-2025 Movatter.jp