1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
|
'\" t
.\" Man page generated from reStructuredText.
.
.
.nr rst2man-indent-level 0
.
.de1 rstReportMargin
\\$1 \\n[an-margin]
level \\n[rst2man-indent-level]
level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
-
\\n[rst2man-indent0]
\\n[rst2man-indent1]
\\n[rst2man-indent2]
..
.de1 INDENT
.\" .rstReportMargin pre:
. RS \\$1
. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
. nr rst2man-indent-level +1
.\" .rstReportMargin post:
..
.de UNINDENT
. RE
.\" indent \\n[an-margin]
.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
.nr rst2man-indent-level -1
.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
..
.TH "FLASK-SOCKETIO" "1" "Mar 12, 2025" "" "Flask-SocketIO"
.SH NAME
flask-socketio \- flask-socketio Documentation
.sp
\fBFlask\-SocketIO\fP gives Flask applications access to low latency
bi\-directional communications between the clients and the server. The
client\-side application can use any of the \X'tty: link http://socket.io'\fI\%SocketIO\fP\X'tty: link'
client libraries in Javascript, Python, C++, Java and Swift, or any other
compatible client to establish a permanent connection to the server.
.SH INTRODUCTION
.SS Installation
.sp
You can install this package in the usual way using \fBpip\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install flask\-socketio
.EE
.UNINDENT
.UNINDENT
.SS Requirements
.sp
Flask\-SocketIO is compatible with Python 3.6+. The asynchronous services that
this package relies on can be selected among three choices:
.INDENT 0.0
.IP \(bu 2
\X'tty: link http://eventlet.net/'\fI\%eventlet\fP\X'tty: link' is the best performant option, with
support for long\-polling and WebSocket transports.
.IP \(bu 2
\X'tty: link http://www.gevent.org/'\fI\%gevent\fP\X'tty: link' is supported in a number of different
configurations. The long\-polling transport is fully supported with the
gevent package, but unlike eventlet, gevent does not have native WebSocket
support. To add support for WebSocket there are currently two options.
Installing the \X'tty: link https://pypi.python.org/pypi/gevent-websocket/'\fI\%gevent\-websocket\fP\X'tty: link'
package adds WebSocket support to gevent or one can use the \X'tty: link https://uwsgi-docs.readthedocs.io/en/latest/'\fI\%uWSGI\fP\X'tty: link' web server, which
comes with WebSocket functionality. The use of gevent is also a performant
option, but slightly lower than eventlet.
.IP \(bu 2
The Flask development server based on Werkzeug can be used as well, with the
caveat that this web server is intended only for development use, so it
should only be used to simplify the development workflow and not for
production.
.UNINDENT
.sp
The extension automatically detects which asynchronous framework to use based
on what is installed. Preference is given to eventlet, followed by gevent.
For WebSocket support in gevent, uWSGI is preferred, followed by
gevent\-websocket. If neither eventlet nor gevent are installed, then the Flask
development server is used.
.sp
If using multiple processes, a message queue service must be configured to
allow the servers to coordinate operations such as broadcasting. The supported
queues are \X'tty: link http://redis.io/'\fI\%Redis\fP\X'tty: link', \X'tty: link https://www.rabbitmq.com/'\fI\%RabbitMQ\fP\X'tty: link',
\X'tty: link http://kafka.apache.org/'\fI\%Kafka\fP\X'tty: link', and any other message queues supported by
the \X'tty: link http://kombu.readthedocs.org/en/latest/'\fI\%Kombu\fP\X'tty: link' package.
.sp
On the client\-side, the official Socket.IO Javascript client library can be
used to establish a connection to the server. There are also official clients
written in Swift, Java and C++. Unofficial clients may also work, as long as
they implement the
\X'tty: link https://github.com/socketio/socket.io-protocol'\fI\%Socket.IO protocol\fP\X'tty: link'\&.
The \X'tty: link https://github.com/miguelgrinberg/python-socketio'\fI\%python\-socketio\fP\X'tty: link'
package (which provides the Socket.IO server implementation used by
Flask\-SocketIO) includes a Python client.
.SS Version compatibility
.sp
The Socket.IO protocol has been through a number of revisions, and some of these
introduced backward incompatible changes, which means that the client and the
server must use compatible versions for everything to work.
.sp
The version compatibility chart below maps versions of this package to versions
of the JavaScript reference implementation and the versions of the Socket.IO and
Engine.IO protocols.
.TS
box center;
l|l|l|l|l|l.
T{
JavaScript Socket.IO version
T} T{
Socket.IO protocol revision
T} T{
Engine.IO protocol revision
T} T{
Flask\-SocketIO version
T} T{
python\-socketio version
T} T{
python\-engineio version
T}
_
T{
0.9.x
T} T{
1, 2
T} T{
1, 2
T} T{
Not supported
T} T{
Not supported
T} T{
Not supported
T}
_
T{
1.x and 2.x
T} T{
3, 4
T} T{
3
T} T{
4.x
T} T{
4.x
T} T{
3.x
T}
_
T{
3.x and 4.x
T} T{
5
T} T{
4
T} T{
5.x
T} T{
5.x
T} T{
4.x
T}
.TE
.SH GETTING STARTED
.SS Initialization
.sp
The following code example shows how to add Flask\-SocketIO to a Flask
application:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config[\(aqSECRET_KEY\(aq] = \(aqsecret!\(aq
socketio = SocketIO(app)
if __name__ == \(aq__main__\(aq:
socketio.run(app)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBinit_app()\fP style of initialization is also supported. To start the
web server simply execute your script. Note the way the web server is started.
The \fBsocketio.run()\fP function encapsulates the start up of the web server and
replaces the \fBapp.run()\fP standard Flask development server start up. When the
application is in debug mode the Werkzeug development server is still used and
configured properly inside \fBsocketio.run()\fP\&. In production mode the eventlet
web server is used if available, else the gevent web server is used. If
eventlet and gevent are not installed, the Werkzeug development web server is
used.
.sp
The \fBflask run\fP command introduced in Flask 0.11 can be used to start a
Flask\-SocketIO development server based on Werkzeug, but this method of starting
the Flask\-SocketIO server is not recommended due to lack of WebSocket support.
Previous versions of this package included a customized version of the
\fBflask run\fP command that allowed the use of WebSocket on eventlet and gevent
production servers, but this functionality has been discontinued in favor of the
\fBsocketio.run(app)\fP startup method shown above which is more robust.
.sp
The application must serve a page to the client that loads the Socket.IO
library and establishes a connection:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
<script src=\(dqhttps://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js\(dq integrity=\(dqsha512\-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==\(dq crossorigin=\(dqanonymous\(dq></script>
<script type=\(dqtext/javascript\(dq charset=\(dqutf\-8\(dq>
var socket = io();
socket.on(\(aqconnect\(aq, function() {
socket.emit(\(aqmy event\(aq, {data: \(aqI\e\(aqm connected!\(aq});
});
</script>
.EE
.UNINDENT
.UNINDENT
.SS Receiving Messages
.sp
When using SocketIO, messages are received by both parties as events. On the
client side Javascript callbacks are used. With Flask\-SocketIO the server
needs to register handlers for these events, similarly to how routes are
handled by view functions.
.sp
The following example creates a server\-side event handler for an unnamed
event:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqmessage\(aq)
def handle_message(data):
print(\(aqreceived message: \(aq + data)
.EE
.UNINDENT
.UNINDENT
.sp
The above example uses string messages. Another type of unnamed events use
JSON data:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqjson\(aq)
def handle_json(json):
print(\(aqreceived json: \(aq + str(json))
.EE
.UNINDENT
.UNINDENT
.sp
The most flexible type of event uses custom event names. The message data for
these events can be string, bytes, int, or JSON:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqmy event\(aq)
def handle_my_custom_event(json):
print(\(aqreceived json: \(aq + str(json))
.EE
.UNINDENT
.UNINDENT
.sp
Custom named events can also support multiple arguments:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqmy_event\(aq)
def handle_my_custom_event(arg1, arg2, arg3):
print(\(aqreceived args: \(aq + arg1 + arg2 + arg3)
.EE
.UNINDENT
.UNINDENT
.sp
When the name of the event is a valid Python identifier that does not collide
with other defined symbols, the \fB@socketio.event\fP decorator provides a more
compact syntax that takes the event name from the decorated function:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.event
def my_custom_event(arg1, arg2, arg3):
print(\(aqreceived args: \(aq + arg1 + arg2 + arg3)
.EE
.UNINDENT
.UNINDENT
.sp
Named events are the most flexible, as they eliminate the need to include
additional metadata to describe the message type. The names \fBmessage\fP,
\fBjson\fP, \fBconnect\fP and \fBdisconnect\fP are reserved and cannot be used for
named events.
.sp
Flask\-SocketIO also supports SocketIO namespaces, which allow the client to
multiplex several independent connections on the same physical socket:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqmy event\(aq, namespace=\(aq/test\(aq)
def handle_my_custom_namespace_event(json):
print(\(aqreceived json: \(aq + str(json))
.EE
.UNINDENT
.UNINDENT
.sp
When a namespace is not specified a default global namespace with the name
\fB\(aq/\(aq\fP is used.
.sp
For cases when a decorator syntax isn\(aqt convenient, the \fBon_event\fP method
can be used:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
def my_function_handler(data):
pass
socketio.on_event(\(aqmy event\(aq, my_function_handler, namespace=\(aq/test\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
Clients may request an acknowledgement callback that confirms receipt of a
message they sent. Any values returned from the handler function will be
passed to the client as arguments in the callback function:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqmy event\(aq)
def handle_my_custom_event(json):
print(\(aqreceived json: \(aq + str(json))
return \(aqone\(aq, 2
.EE
.UNINDENT
.UNINDENT
.sp
In the above example, the client callback function will be invoked with
two arguments, \fB\(aqone\(aq\fP and \fB2\fP\&. If a handler function does not return any
values, the client callback function will be invoked without arguments.
.SS Sending Messages
.sp
SocketIO event handlers defined as shown in the previous section can send
reply messages to the connected client using the \fBsend()\fP and \fBemit()\fP
functions.
.sp
The following examples bounce received events back to the client that sent
them:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from flask_socketio import send, emit
@socketio.on(\(aqmessage\(aq)
def handle_message(message):
send(message)
@socketio.on(\(aqjson\(aq)
def handle_json(json):
send(json, json=True)
@socketio.on(\(aqmy event\(aq)
def handle_my_custom_event(json):
emit(\(aqmy response\(aq, json)
.EE
.UNINDENT
.UNINDENT
.sp
Note how \fBsend()\fP and \fBemit()\fP are used for unnamed and named events
respectively.
.sp
When working with namespaces, \fBsend()\fP and \fBemit()\fP use the namespace of
the incoming message by default. A different namespace can be specified with
the optional \fBnamespace\fP argument:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqmessage\(aq)
def handle_message(message):
send(message, namespace=\(aq/chat\(aq)
@socketio.on(\(aqmy event\(aq)
def handle_my_custom_event(json):
emit(\(aqmy response\(aq, json, namespace=\(aq/chat\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
To send an event with multiple arguments, send a tuple:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqmy event\(aq)
def handle_my_custom_event(json):
emit(\(aqmy response\(aq, (\(aqfoo\(aq, \(aqbar\(aq, json), namespace=\(aq/chat\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
SocketIO supports acknowledgment callbacks that confirm that a message was
received by the client:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
def ack():
print(\(aqmessage was received!\(aq)
@socketio.on(\(aqmy event\(aq)
def handle_my_custom_event(json):
emit(\(aqmy response\(aq, json, callback=ack)
.EE
.UNINDENT
.UNINDENT
.sp
When using callbacks, the Javascript client receives a callback function to
invoke upon receipt of the message. After the client application invokes the
callback function the server invokes the corresponding server\-side callback.
If the client\-side callback is invoked with arguments, these are provided as
arguments to the server\-side callback as well.
.SS Broadcasting
.sp
Another very useful feature of SocketIO is the broadcasting of messages.
Flask\-SocketIO supports this feature with the \fBbroadcast=True\fP optional
argument to \fBsend()\fP and \fBemit()\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqmy event\(aq)
def handle_my_custom_event(data):
emit(\(aqmy response\(aq, data, broadcast=True)
.EE
.UNINDENT
.UNINDENT
.sp
When a message is sent with the broadcast option enabled, all clients
connected to the namespace receive it, including the sender. When namespaces
are not used, the clients connected to the global namespace receive the
message. Note that callbacks are not invoked for broadcast messages.
.sp
In all the examples shown until this point the server responds to an event
sent by the client. But for some applications, the server needs to be the
originator of a message. This can be useful to send notifications to clients
of events that originated in the server, for example in a background thread.
The \fBsocketio.send()\fP and \fBsocketio.emit()\fP methods can be used to
broadcast to all connected clients:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
def some_function():
socketio.emit(\(aqsome event\(aq, {\(aqdata\(aq: 42})
.EE
.UNINDENT
.UNINDENT
.sp
Note that \fBsocketio.send()\fP and \fBsocketio.emit()\fP are not the same
functions as the context\-aware \fBsend()\fP and \fBemit()\fP\&. Also note that in the
above usage there is no client context, so \fBbroadcast=True\fP is assumed and
does not need to be specified.
.SS Rooms
.sp
For many applications it is necessary to group users into subsets that can be
addressed together. The best example is a chat application with multiple rooms,
where users receive messages from the room or rooms they are in, but not from
other rooms where other users are. Flask\-SocketIO supports this concept of
rooms through the \fBjoin_room()\fP and \fBleave_room()\fP functions:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from flask_socketio import join_room, leave_room
@socketio.on(\(aqjoin\(aq)
def on_join(data):
username = data[\(aqusername\(aq]
room = data[\(aqroom\(aq]
join_room(room)
send(username + \(aq has entered the room.\(aq, to=room)
@socketio.on(\(aqleave\(aq)
def on_leave(data):
username = data[\(aqusername\(aq]
room = data[\(aqroom\(aq]
leave_room(room)
send(username + \(aq has left the room.\(aq, to=room)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBsend()\fP and \fBemit()\fP functions accept an optional \fBto\fP argument
that cause the message to be sent to all the clients that are in the given
room.
.sp
All clients are assigned a room when they connect, named with the session ID
of the connection, which can be obtained from \fBrequest.sid\fP\&. A given client
can join any rooms, which can be given any names. When a client disconnects it
is removed from all the rooms it was in. The context\-free \fBsocketio.send()\fP
and \fBsocketio.emit()\fP functions also accept a \fBto\fP argument to broadcast
to all clients in a room.
.sp
Since all clients are assigned a personal room, to address a message to a
single client, the session ID of the client can be used as the \fBto\fP argument.
.SS Connection Events
.sp
Flask\-SocketIO also dispatches connection and disconnection events. The
following example shows how to register handlers for them:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqconnect\(aq)
def test_connect(auth):
emit(\(aqmy response\(aq, {\(aqdata\(aq: \(aqConnected\(aq})
@socketio.on(\(aqdisconnect\(aq)
def test_disconnect(reason):
print(\(aqClient disconnected, reason:\(aq, reason)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBauth\fP argument in the connection handler is optional. The client can
use it to pass authentication data such as tokens in dictionary format. If the
client does not provide authentication details, then this argument is set to
\fBNone\fP\&. If the server defines a connection event handler without this
argument, then any authentication data passed by the client is discarded.
.sp
The connection event handler can return \fBFalse\fP to reject the connection, or
it can also raise \fIConnectionRefusedError\fP\&. This is so that the client can be
authenticated at this point. When using the exception, any arguments passed to
the exception are returned to the client in the error packet. Examples:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from flask_socketio import ConnectionRefusedError
@socketio.on(\(aqconnect\(aq)
def connect():
if not self.authenticate(request.args):
raise ConnectionRefusedError(\(aqunauthorized!\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The disconnection event handler receives a \fBreason\fP argument that indicates
the cause of the disconnection. The \fBflask_socketio.SocketIO.reason\fP
member includes constants for all the possible reasons.
.sp
Note that connection and disconnection events are sent individually on each
namespace used.
.SS Class\-Based Namespaces
.sp
As an alternative to the decorator\-based event handlers described above, the
event handlers that belong to a namespace can be created as methods of a
class. The \fBflask_socketio.Namespace\fP is provided as a base class to
create class\-based namespaces:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from flask_socketio import Namespace, emit
class MyCustomNamespace(Namespace):
def on_connect(self):
pass
def on_disconnect(self, reason):
pass
def on_my_event(self, data):
emit(\(aqmy_response\(aq, data)
socketio.on_namespace(MyCustomNamespace(\(aq/test\(aq))
.EE
.UNINDENT
.UNINDENT
.sp
When class\-based namespaces are used, any events received by the server are
dispatched to a method named as the event name with the \fBon_\fP prefix. For
example, event \fBmy_event\fP will be handled by a method named \fBon_my_event\fP\&.
If an event is received for which there is no corresponding method defined in
the namespace class, then the event is ignored. All event names used in
class\-based namespaces must use characters that are legal in method names.
.sp
As a convenience to methods defined in a class\-based namespace, the namespace
instance includes versions of several of the methods in the
\fBflask_socketio.SocketIO\fP class that default to the proper namespace
when the \fBnamespace\fP argument is not given.
.sp
If an event has a handler in a class\-based namespace, and also a
decorator\-based function handler, only the decorated function handler is
invoked.
.SS Error Handling
.sp
Flask\-SocketIO can also deal with exceptions:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on_error() # Handles the default namespace
def error_handler(e):
pass
@socketio.on_error(\(aq/chat\(aq) # handles the \(aq/chat\(aq namespace
def error_handler_chat(e):
pass
@socketio.on_error_default # handles all namespaces without an explicit error handler
def default_error_handler(e):
pass
.EE
.UNINDENT
.UNINDENT
.sp
Error handler functions take the exception object as an argument.
.sp
The message and data arguments of the current request can also be inspected
with the \fBrequest.event\fP variable, which is useful for error logging and
debugging outside the event handler:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from flask import request
@socketio.on(\(dqmy error event\(dq)
def on_my_event(data):
raise RuntimeError()
@socketio.on_error_default
def default_error_handler(e):
print(request.event[\(dqmessage\(dq]) # \(dqmy error event\(dq
print(request.event[\(dqargs\(dq]) # (data,)
.EE
.UNINDENT
.UNINDENT
.SS Debugging and Troubleshooting
.sp
To help you debug issues, the server can be configured to output logs to the
terminal:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
socketio = SocketIO(logger=True, engineio_logger=True)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBlogger\fP argument controls logging related to the Socket.IO protocol,
while \fBengineio_logger\fP controls logs that originate in the low\-level
Engine.IO transport. These arguments can be set to \fBTrue\fP to output logs to
\fBstderr\fP, or to an object compatible with Python\(aqs \fBlogging\fP package
where the logs should be emitted to. A value of \fBFalse\fP disables logging.
.sp
Logging can help identify the cause of connection problems, 400 responses,
bad performance and other issues.
.SH IMPLEMENTATION NOTES
.SS Access to Flask\(aqs Context Globals
.sp
Handlers for SocketIO events are different than handlers for routes and that
introduces a lot of confusion around what can and cannot be done in a SocketIO
handler. The main difference is that all the SocketIO events generated for a
client occur in the context of a single long running request.
.sp
In spite of the differences, Flask\-SocketIO attempts to make working with
SocketIO event handlers easier by making the environment similar to that of a
regular HTTP request. The following list describes what works and what doesn\(aqt:
.INDENT 0.0
.IP \(bu 2
An application context is pushed before invoking an event handler making
\fBcurrent_app\fP and \fBg\fP available to the handler.
.IP \(bu 2
A request context is also pushed before invoking a handler, also making
\fBrequest\fP and \fBsession\fP available. But note that WebSocket events do not
have individual requests associated with them, so the request context that
started the connection is pushed for all the events that are dispatched
during the life of the connection.
.IP \(bu 2
The \fBrequest\fP context global is enhanced with a \fBsid\fP member that is set
to a unique session ID for the connection. This value is used as an initial
room where the client is added.
.IP \(bu 2
The \fBrequest\fP context global is enhanced with \fBnamespace\fP and \fBevent\fP
members that contain the currently handled namespace and event arguments.
The \fBevent\fP member is a dictionary with \fBmessage\fP and \fBargs\fP keys.
.IP \(bu 2
The \fBsession\fP context global behaves in a different way than in regular
requests. A copy of the user session at the time the SocketIO connection is
established is made available to handlers invoked in the context of that
connection. If a SocketIO handler modifies the session, the modified session
will be preserved for future SocketIO handlers, but regular HTTP route
handlers will not see these changes. Effectively, when a SocketIO handler
modifies the session, a \(dqfork\(dq of the session is created exclusively for
these handlers. The technical reason for this limitation is that to save the
user session a cookie needs to be sent to the client, and that requires HTTP
request and response, which do not exist in a SocketIO connection. When
using server\-side sessions such as those provided by the Flask\-Session or
Flask\-KVSession extensions, changes made to the session in HTTP route
handlers can be seen by SocketIO handlers, as long as the session is not
modified in the SocketIO handlers.
.IP \(bu 2
The \fBbefore_request\fP and \fBafter_request\fP hooks are not invoked for
SocketIO event handlers.
.IP \(bu 2
SocketIO handlers can take custom decorators, but most Flask decorators will
not be appropriate to use for a SocketIO handler, given that there is no
concept of a \fBResponse\fP object during a SocketIO connection.
.UNINDENT
.SS Authentication
.sp
A common need of applications is to validate the identity of their users. The
traditional mechanisms based on web forms and HTTP requests cannot be used in
a SocketIO connection, since there is no place to send HTTP requests and
responses. If necessary, an application can implement a customized login form
that sends credentials to the server as a SocketIO message when the submit
button is pressed by the user.
.sp
However, in most cases it is more convenient to perform the traditional
authentication process before the SocketIO connection is established. The
user\(aqs identity can then be recorded in the user session or in a cookie, and
later when the SocketIO connection is established that information will be
accessible to SocketIO event handlers.
.sp
Recent revisions of the Socket.IO protocol include the ability to pass a
dictionary with authentication information during the connection. This is an
ideal place for the client to include a token or other authentication details.
If the client uses this capability, the server will provide this dictionary as
an argument to the \fBconnect\fP event handler, as shown above.
.SS Using Flask\-Login with Flask\-SocketIO
.sp
Flask\-SocketIO can access login information maintained by
\X'tty: link https://flask-login.readthedocs.org/en/latest/'\fI\%Flask\-Login\fP\X'tty: link'\&. After a
regular Flask\-Login authentication is performed and the \fBlogin_user()\fP
function is called to record the user in the user session, any SocketIO
connections will have access to the \fBcurrent_user\fP context variable:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@socketio.on(\(aqconnect\(aq)
def connect_handler():
if current_user.is_authenticated:
emit(\(aqmy response\(aq,
{\(aqmessage\(aq: \(aq{0} has joined\(aq.format(current_user.name)},
broadcast=True)
else:
return False # not allowed here
.EE
.UNINDENT
.UNINDENT
.sp
Note that the \fBlogin_required\fP decorator cannot be used with SocketIO event
handlers, but a custom decorator that disconnects non\-authenticated users can
be created as follows:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import functools
from flask import request
from flask_login import current_user
from flask_socketio import disconnect, emit
def authenticated_only(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
if not current_user.is_authenticated:
disconnect()
else:
return f(*args, **kwargs)
return wrapped
@socketio.on(\(aqmy event\(aq)
@authenticated_only
def handle_my_custom_event(data):
emit(\(aqmy response\(aq, {\(aqmessage\(aq: \(aq{0} has joined\(aq.format(current_user.name)},
broadcast=True)
.EE
.UNINDENT
.UNINDENT
.SH DEPLOYMENT
.sp
There are many options to deploy a Flask\-SocketIO server, ranging from simple
to the insanely complex. In this section, the most commonly used options are
described.
.SS Embedded Server
.sp
The simplest deployment strategy is to start the web server by calling
\fBsocketio.run(app)\fP as shown in examples above. This will look through the
packages that are installed for the best available web server and start the
application on it. The current web server choices that are evaluated are
\fBeventlet\fP, \fBgevent\fP and the Flask development server.
.sp
If eventlet or gevent are available, \fBsocketio.run(app)\fP starts a
production\-ready server using one of these frameworks. If neither of these are
installed, then the Flask development web server is used, and in this case the
server is not intended to be used in a production deployment.
.sp
Unfortunately this option is not available when using gevent with uWSGI. See
the uWSGI section below for information on this option.
.SS Gunicorn Web Server
.sp
An alternative to \fBsocketio.run(app)\fP is to use
\X'tty: link http://gunicorn.org/'\fI\%gunicorn\fP\X'tty: link' as web server, using the eventlet or gevent
workers. For this option, eventlet or gevent need to be installed, in addition
to gunicorn. The command line that starts the eventlet server via gunicorn is:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
gunicorn \-\-worker\-class eventlet \-w 1 module:app
.EE
.UNINDENT
.UNINDENT
.sp
If you prefer to use gevent, the command to start the server is:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
gunicorn \-k gevent \-w 1 module:app
.EE
.UNINDENT
.UNINDENT
.sp
When using gunicorn with the gevent worker and the WebSocket support provided
by gevent\-websocket, the command that starts the server must be changed to
select a custom gevent web server that supports the WebSocket protocol. The
modified command is:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
gunicorn \-k geventwebsocket.gunicorn.workers.GeventWebSocketWorker \-w 1 module:app
.EE
.UNINDENT
.UNINDENT
.sp
A third option with Gunicorn is to use the threaded worker, along with the
\X'tty: link https://github.com/miguelgrinberg/simple-websocket'\fI\%simple\-websocket\fP\X'tty: link'
package for WebSocket support. This is a particularly good solution for
applications that are CPU heavy or are otherwise incompatible with eventlet
and gevent use of green threads. The command to start a threaded web server
is:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
gunicorn \-w 1 \-\-threads 100 module:app
.EE
.UNINDENT
.UNINDENT
.sp
In all these commands, \fBmodule\fP is the Python module or package that defines
the application instance, and \fBapp\fP is the application instance itself.
.sp
Due to the limited load balancing algorithm used by gunicorn, it is not possible
to use more than one worker process when using this web server. For that reason,
all the examples above include the \fB\-w 1\fP option.
.sp
The workaround to use multiple worker processes with gunicorn is to launch
several single\-worker instances and put them behind a more capable load
balancer such as \X'tty: link https://www.nginx.com/'\fI\%nginx\fP\X'tty: link'\&.
.SS uWSGI Web Server
.sp
When using the uWSGI server in combination with gevent, the Socket.IO server
can take advantage of uWSGI’s native WebSocket support.
.sp
A complete explanation of the configuration and usage of the uWSGI server is
beyond the scope of this documentation. The uWSGI server is a fairly complex
package that provides a large and comprehensive set of options. It must be
compiled with WebSocket and SSL support for the WebSocket transport to be
available. As way of an introduction, the following command starts a uWSGI
server for the example application app.py on port 5000:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
$ uwsgi \-\-http :5000 \-\-gevent 1000 \-\-http\-websockets \-\-master \-\-wsgi\-file app.py \-\-callable app
.EE
.UNINDENT
.UNINDENT
.SS Using nginx as a WebSocket Reverse Proxy
.sp
It is possible to use nginx as a front\-end reverse proxy that passes requests
to the application. However, only releases of nginx 1.4 and newer support
proxying of the WebSocket protocol. Below is a basic nginx configuration that
proxies HTTP and WebSocket requests:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
server {
listen 80;
server_name _;
location / {
include proxy_params;
proxy_pass http://127.0.0.1:5000;
}
location /static/ {
alias <path\-to\-your\-application>/static/;
expires 30d;
}
location /socket.io {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection \(dqUpgrade\(dq;
proxy_pass http://127.0.0.1:5000/socket.io;
}
}
.EE
.UNINDENT
.UNINDENT
.sp
The next example adds the support for load balancing multiple Socket.IO
servers:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
upstream socketio_nodes {
ip_hash;
server 127.0.0.1:5000;
server 127.0.0.1:5001;
server 127.0.0.1:5002;
# to scale the app, just add more nodes here!
}
server {
listen 80;
server_name _;
location / {
include proxy_params;
proxy_pass http://127.0.0.1:5000;
}
location /static/ {
alias <path\-to\-your\-application>/static/;
expires 30d;
}
location /socket.io {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection \(dqUpgrade\(dq;
proxy_pass http://socketio_nodes/socket.io;
}
}
.EE
.UNINDENT
.UNINDENT
.sp
While the above examples can work as an initial configuration, be aware that a
production install of nginx will need a more complete configuration covering
other deployment aspects such as SSL support.
.SS Using Multiple Workers
.sp
Flask\-SocketIO supports multiple workers behind a load balancer starting with
release 2.0. Deploying multiple workers gives applications that use
Flask\-SocketIO the ability to spread the client connections among multiple
processes and hosts, and in this way scale to support very large numbers of
concurrent clients.
.sp
There are two requirements to use multiple Flask\-SocketIO workers:
.INDENT 0.0
.IP \(bu 2
The load balancer must be configured to forward all HTTP requests from a
given client always to the same worker. This is sometimes referenced as
\(dqsticky sessions\(dq. For nginx, use the \fBip_hash\fP directive to achieve this.
Gunicorn cannot be used with multiple workers because its load balancer
algorithm does not support sticky sessions.
.IP \(bu 2
Since each of the servers owns only a subset of the client connections, a
message queue such as Redis or RabbitMQ is used by the servers to coordinate
complex operations such as broadcasting and rooms.
.UNINDENT
.sp
When working with a message queue, there are additional dependencies that need to
be installed:
.INDENT 0.0
.IP \(bu 2
For Redis, the package \fBredis\fP must be installed (\fBpip install redis\fP).
.IP \(bu 2
For RabbitMQ, the package \fBkombu\fP must be installed (\fBpip install kombu\fP).
.IP \(bu 2
For Kafka, the package \fBkafka\-python\fP must be installed (\fBpip install kafka\-python\fP).
.IP \(bu 2
For other message queues supported by Kombu, see the \X'tty: link http://docs.celeryproject.org/projects/kombu/en/latest/introduction.html#transport-comparison'\fI\%Kombu documentation\fP\X'tty: link'
to find out what dependencies are needed.
.IP \(bu 2
If eventlet or gevent are used, then monkey patching the Python standard
library is normally required to force the message queue package to use
coroutine friendly functions and classes.
.UNINDENT
.sp
For eventlet, monkey patching is done with:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import eventlet
eventlet.monkey_patch()
.EE
.UNINDENT
.UNINDENT
.sp
For gevent, you can monkey patch the standard library with:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from gevent import monkey
monkey.patch_all()
.EE
.UNINDENT
.UNINDENT
.sp
In both cases it is recommended that you apply the monkey patching at the top
of your main script, even above your imports.
.sp
To start multiple Flask\-SocketIO servers, you must first ensure you have the
message queue service running. To start a Socket.IO server and have it connect to
the message queue, add the \fBmessage_queue\fP argument to the \fBSocketIO\fP
constructor:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
socketio = SocketIO(app, message_queue=\(aqredis://\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The value of the \fBmessage_queue\fP argument is the connection URL of the
queue service that is used. For a redis queue running on the same host as the
server, the \fB\(aqredis://\(aq\fP URL can be used. Likewise, for a default RabbitMQ
queue the \fB\(aqamqp://\(aq\fP URL can be used. For Kafka, use a \fBkafka://\fP URL.
The Kombu package has a \X'tty: link http://docs.celeryproject.org/projects/kombu/en/latest/userguide/connections.html?highlight=urls#urls'\fI\%documentation
section\fP\X'tty: link'
that describes the format of the URLs for all the supported queues.
.SS Emitting from an External Process
.sp
For many types of applications, it is necessary to emit events from a process
that is not the SocketIO server, for an example a Celery worker. If the
SocketIO server or servers are configured to listen on a message queue as
shown in the previous section, then any other process can create its own
\fBSocketIO\fP instance and use it to emit events in the same way the server
does.
.sp
For example, for an application that runs on an eventlet web server and uses
a Redis message queue, the following Python script broadcasts an event to
all clients:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
socketio = SocketIO(message_queue=\(aqredis://\(aq)
socketio.emit(\(aqmy event\(aq, {\(aqdata\(aq: \(aqfoo\(aq}, namespace=\(aq/test\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
When using the \fBSocketIO\fP instance in this way, the Flask application
instance is not passed to the constructor.
.sp
The \fBchannel\fP argument to \fBSocketIO\fP can be used to select a specific
channel of communication through the message queue. Using a custom channel
name is necessary when there are multiple independent SocketIO services
sharing the same queue.
.sp
Flask\-SocketIO does not apply monkey patching when eventlet or gevent are
used. But when working with a message queue, it is very likely that the Python
package that talks to the message queue service will hang if the Python
standard library is not monkey patched.
.sp
It is important to note that an external process that wants to connect to
a SocketIO server does not need to use eventlet or gevent like the main
server. Having a server use a coroutine framework, while an external process
is not a problem. For example, Celery workers do not need to be
configured to use eventlet or gevent just because the main server does. But if
your external process does use a coroutine framework for whatever reason, then
monkey patching is likely required, so that the message queue accesses
coroutine friendly functions and classes.
.SS Cross\-Origin Controls
.sp
For security reasons, this server enforces a same\-origin policy by default. In
practical terms, this means the following:
.INDENT 0.0
.IP \(bu 2
If an incoming HTTP or WebSocket request includes the \fBOrigin\fP header,
this header must match the scheme and host of the connection URL. In case
of a mismatch, a 400 status code response is returned and the connection is
rejected.
.IP \(bu 2
No restrictions are imposed on incoming requests that do not include the
\fBOrigin\fP header.
.UNINDENT
.sp
If necessary, the \fBcors_allowed_origins\fP option can be used to allow other
origins. This argument can be set to a string to set a single allowed origin, or
to a list to allow multiple origins. A special value of \fB\(aq*\(aq\fP can be used to
instruct the server to allow all origins, but this should be done with care, as
this could make the server vulnerable to Cross\-Site Request Forgery (CSRF)
attacks.
.SH UPGRADING TO FLASK-SOCKETIO 5.X FROM THE 4.X RELEASES
.sp
The Socket.IO protocol recently introduced a series of backwards incompatible
changes. The 5.x releases of Flask\-SocketIO adopted these changes, and for
that reason it can only be used with clients that have also been updated to
the current version of the protocol. In particular, this means that the
JavaScript client must be upgraded to a 3.x release, and if your client hasn\(aqt
been upgraded to the latest version of the Socket.IO protocol, then you must
use a Flask\-SocketIO 4.x release.
.sp
The following protocol changes are of importance, as they may affect existing
applications:
.INDENT 0.0
.IP \(bu 2
The default namespace \fB\(aq/\(aq\fP is not automatically connected anymore, and is
now treated in the same way as other namespaces.
.IP \(bu 2
Each namespace connection has its own \fBsid\fP value, different from the others
and different from the Engine.IO \fBsid\fP\&.
.IP \(bu 2
Flask\-SocketIO now uses the same ping interval and timeout values as the
JavaScript reference implementation, which are 25 and 5 seconds respectively.
.IP \(bu 2
The ping/pong mechanism has been reversed. In the current version of the
protocol, the server issues a ping and the client responds with a pong.
.IP \(bu 2
The default allowed payload size for long\-\-polling packets has been lowered
from 100MB to 1MB.
.IP \(bu 2
The \fIio\fP cookie is not sent to the client anymore by default.
.UNINDENT
.SH API REFERENCE
.INDENT 0.0
.IP \(bu 2
\fI\%Index\fP
.IP \(bu 2
\fI\%Module Index\fP
.IP \(bu 2
\fI\%Search Page\fP
.UNINDENT
.SH AUTHOR
Miguel Grinberg
.SH COPYRIGHT
2018, Miguel Grinberg
.\" Generated by docutils manpage writer.
.
|