You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
- 👉 [Flask SocketIO Sample](https://github.com/app-generator/sample-flask-socketio) - published on `GitHub`
12
+
- 👉 Free [Support](https://appseed.us/support/) via Email & Discord
12
13
13
14
## Introduction
14
-
Socket.IO is a library that enables real-time, bidirectional, and event-driven communication between a client and a server. It is built on top of the WebSocket protocol, which allows for fast and simultaneous communication between the server and the browser. Socket.IO provides additional features like fallback options for HTTP long-polling and automatic reconnection, enhancing the reliability and versatility of real-time applications.
15
15
16
-
Here are the key features of Socket.IO:
16
+
Socket.IO is a library that enables real-time, bidirectional, and event-driven communication between a client and a server.
17
+
It is built on top of the WebSocket protocol, which allows for fast and simultaneous communication between the server and the browser.
18
+
Socket.IO provides additional features like fallback options for HTTP long-polling and automatic reconnection, enhancing the reliability and versatility of real-time applications.
19
+
20
+
> Here are the `key features of Socket.IO`:
17
21
18
22
1. Real-time communication: Socket.IO enables instantaneous and bidirectional data exchange between web clients and servers, eliminating the need for page refreshes.
19
23
@@ -33,20 +37,27 @@ Socket.IO finds application in various scenarios, including:
33
37
34
38
If you're looking to develop real-time web applications, Socket.IO is an excellent choice. It offers simplicity, reliability, and efficiency, and is well-supported across different browsers and devices.
35
39
40
+
<br />
36
41
37
42
## Using Socket.IO with Flask
38
-
To use Socket.IO with Flask, we will utilize the `flask-socketio` package. In this tutorial, we will demonstrate how Socket.IO can update a card on a Flask dashboard. We will utilize the Flask dashboard called [Flask-gradient-able](https://github.com/app-generator/flask-gradient-able).
43
+
44
+
To use Socket.IO with Flask, we will utilize the `flask-socketio` package. In this tutorial, we will demonstrate how Socket.IO can update a card on a Flask dashboard.
45
+
We will utilize the Flask dashboard called [Flask Gradient Able](https://github.com/app-generator/flask-gradient-able).
* Run the flask application to ensure it is properly setup using the command
75
+
> Run the flask application to ensure it is properly setup using the command
76
+
64
77
```bash
65
78
(venv) sample-flask-socketio$ flask run
66
79
```
67
-
* Visit [`http://127.0.0.1:5000`](http://127.0.0.1:5000) on your browser.
80
+
Visit [`http://127.0.0.1:5000`](http://127.0.0.1:5000) on your browser.
81
+
Create an account to view the homepage of the application. You can stop the flask server using `Ctrl + c`.
82
+
83
+
<br />
68
84
69
-
* Create an account to view the homepage of the application. You can stop the flask server using `Ctrl + c`.
85
+
### Integrating `Socket.IO` with `Flask`
70
86
71
-
### Integrating Socket.IO with flask
72
87
To integrate Socket.IO into a Flask application, we will utilize the `flask-socketio` package. This package empowers Flask applications to harness the capabilities and advantages of SocketIO.
73
88
74
89
* Install `flask-socketio` package using the command
* Create a file in the `apps` folder named `events.py`, this file will be used to create the socketio object and will also contain events that will be handled using socketio
96
+
80
97
```py
81
98
# apps/events.py
82
99
@@ -90,6 +107,7 @@ def connect_event():
90
107
```
91
108
92
109
* Add Socket.IO to the application by making the following changes to `apps/__init__.py`
110
+
93
111
```
94
112
# apps/__init__.py
95
113
...
@@ -102,9 +120,13 @@ def create_app(config):
102
120
return app
103
121
```
104
122
105
-
To ensure that the events to be handled by SocketIO are loaded into the `socketio` object and registered with the Flask app, we import `socketio` from `app/events.py` and initialize it with the Flask app using `socketio.init_app(app)`. This ensures that the event handlers are properly integrated with the SocketIO functionality.
123
+
To ensure that the events to be handled by SocketIO are loaded into the `socketio` object and registered with the Flask app,
124
+
we import `socketio` from `app/events.py` and initialize it with the Flask app using `socketio.init_app(app)`.
125
+
126
+
This ensures that the event handlers are properly integrated with the SocketIO functionality.
106
127
107
128
* Make the following changes to `run.py`
129
+
108
130
```py
109
131
# run.py
110
132
...
@@ -116,12 +138,13 @@ if __name__ == "__main__":
116
138
```
117
139
118
140
* Add SocketIO script tag to `apps/templates/home/index.html`, this loads the Socket.IO library and establishes a connection.
To ensure that a connection can be established by your application:
135
-
1. run the flask app using `flask run` from your terminal.
136
-
2. Open `http://127.0.0.1:5000` on your browser.
137
-
3. Log in to the application
138
-
4. Open the developers console using `Ctrl + Shift + I` or `Command + Option + i` (on Mac).
139
158
140
-
### Emitting and receiving events between client and server
141
-
SocketIO sends messages as events, allowing for communication between the server and client in both directions. The server can send events to the client, and vice versa. SocketIO includes default events such as `connect` and `message`, but we can create custom events and handle them on both the client and server-side.
159
+
1. run the flask app using `flask run` from your terminal.
160
+
2. Open `http://127.0.0.1:5000` on your browser.
161
+
3. Log in to the application
162
+
4. Open the developers console using `Ctrl + Shift + I` or `Command + Option + i` (on Mac).
163
+
164
+
<br />
165
+
166
+
### Emitting and Receiving Events
167
+
168
+
SocketIO sends messages as events, allowing for communication between the server and client in both directions.
169
+
The server can send events to the client, and vice versa. SocketIO includes default events such as `connect` and `message`, but we can create custom events and handle them on both the client and server-side.
142
170
143
171
Next, we will be sending a message from the client to the server and then we will print that message on the terminal.
144
172
145
173
* Make the following change to `apps/templates/home/base.html`
174
+
146
175
```html
147
176
<!-- apps/templates/home/index.html -->
148
177
...
@@ -156,19 +185,26 @@ Next, we will be sending a message from the client to the server and then we wil
156
185
```
157
186
158
187
* Add the following line of code to `apps/events.py`
188
+
159
189
```py
160
190
# apps/events.py
161
191
...
162
192
@socketio.on('message')
163
193
defhandle_message(data):
164
194
print('This is a message:', data)
165
195
```
196
+
166
197
Refresh your browser and check your Python terminal. You will observe that the message from the client is printed on the Python terminal.
167
198
199
+
<br />
200
+
168
201
#### Creating custom events
169
-
In addition to having default events, we can create custom events to tailor our code to various situations. The key distinction between messages and custom events lies in how they are triggered. To trigger a custom event, we utilize the `emit` method, as we will see shortly.
202
+
203
+
In addition to having default events, we can create custom events to tailor our code to various situations.
204
+
The key distinction between messages and custom events lies in how they are triggered. To trigger a custom event, we utilize the `emit` method, as we will see shortly.
170
205
171
206
* Create a custom event called `new event` by adding the code below to `apps/events.py`
207
+
172
208
```py
173
209
# apps/events.py
174
210
...
@@ -179,6 +215,7 @@ def handle_new_event(data):
179
215
```
180
216
181
217
* Add the code below to `apps/templates/home/index.html` to receive and send events from the client side
218
+
182
219
```html
183
220
<!-- apps/templates/home/index.html -->
184
221
<scripttype="text/javascript"charset="utf-8">
@@ -190,12 +227,18 @@ def handle_new_event(data):
190
227
});
191
228
</script>
192
229
```
193
-
After making the changes to the code as mentioned, please refresh your browser and examine both your browser console and the Python terminal. You will observe the events being handled by both sides of the application.
194
230
195
-
## Real-time Updates in Flask
231
+
After making the changes to the code as mentioned, please refresh your browser and examine both your browser console and the Python terminal.
232
+
You will observe the events being handled by both sides of the application.
233
+
234
+
<br />
235
+
236
+
## Real-Time Updates in Flask
237
+
196
238
Using SocketIO, we will implement real-time updates in our Flask application. The details of a card on our dashboard will be updated whenever a new entry is added to our database.
197
239
198
240
* First we will be creating a `Sales` table using schema. Create a new file in `apps/home` named `model.py` and add the following code
241
+
199
242
```py
200
243
# apps/home/model.py
201
244
from apps import db
@@ -222,6 +265,7 @@ class Sales(db.Model):
222
265
```
223
266
224
267
* Make the following update to `apps/__init__.py` so the new `Sales` table can be created when the flask server starts up.
Please restart the Flask server and visit the homepage. This action will result in the addition of the `Sales` table to the database.
234
279
280
+
<br />
281
+
235
282
### Implementing real-time updates using Socket.IO
236
-
To implement real-time updates on the application, we will create a new route that allows the addition of entries to the database. Once an entry is added, we will update the card components on the homepage.
283
+
284
+
To implement real-time updates on the application, we will create a new route that allows the addition of entries to the database.
285
+
Once an entry is added, we will update the card components on the homepage.
237
286
238
287
* We will be creating a route for adding new entries to the `Sales` table. Add the code below to `apps/home/routes.py`
Now that we have a route that can add products to the sales database, we emit a `sales` event that is broadcasted to all clients connected to the server.
264
315
265
316
While the Flask server is running, open another terminal and execute the following command to add entries to your database using the route:
266
317
267
318
```bash
268
319
curl -X POST -F product=product-name -F amount=product-amount -F status=Completed http://localhost:5000/sales
269
320
```
321
+
270
322
**NOTE:** You can replace `product-name` with the value you want to add to the database, and `product-amount` with whatever number you choose. `-F status=Completed` can be removed to create an entry with a status of `Not Completed`.
271
323
272
324
* Let's add the following line of code to apps/templates/home/index.html to listen for the sales event emitted from the route we created earlier
You can try adding entries to your database using the command mentioned earlier. Upon checking your browser console, you will observe that the data sent using `curl` is displayed in the console.
285
339
286
-
### Updating a card or component on the Flask dashboard in response to events
340
+
<br />
341
+
342
+
### Updating the UI in response to Events
343
+
287
344
For the final part of our tutorial on using SocketIO to achieve real-time updates in our application, we will write the logic to update the `Orders received` card on the homepage.
288
345
289
-
* Let's make the following changes to `app/home/routes.py` to add a context that sends the numver of sales and sales completed to the homepage. These values will be used to update the `Orders received` card:
346
+
* Let's make the following changes to `app/home/routes.py` to add a context that sends the numver of sales and sales completed to the homepage.
347
+
These values will be used to update the `Orders received` card:
348
+
290
349
```py
291
350
# apps/home/routes.py
292
351
...
@@ -300,6 +359,7 @@ def index():
300
359
```
301
360
302
361
* Let's make the following changes to `apps/templates/home/index.html` to retrieve the orders received from the database
362
+
303
363
```html
304
364
<!-- apps/templates/home/index.html -->
305
365
...
@@ -310,9 +370,11 @@ def index():
310
370
</div>
311
371
...
312
372
```
373
+
313
374
**NOTE** Take note of the added `id` attribute inside the `span` tags
314
375
315
376
* Now let's write the logic to update the cards when a POST request is sent to `http://localhost:5000/sales`. We'll make the following changes to `apps/templates/home/index.html`
377
+
316
378
```html
317
379
...
318
380
<scripttype="text/javascript"charset="utf-8">
@@ -328,12 +390,23 @@ def index():
328
390
</script>
329
391
...
330
392
```
331
-
When the server emits the `sales` event, it triggers the function responsible for updating the card elements on the homepage. This function is automatically executed in response to the event and is responsible for handling the necessary updates to the card components based on the received data.
393
+
394
+
When the server emits the `sales` event, it triggers the function responsible for updating the card elements on the homepage.
395
+
This function is automatically executed in response to the event and is responsible for handling the necessary updates to the card components based on the received data.
396
+
397
+
<br />
332
398
333
399
## Conclusion
334
-
In this tutorial, we learned how to use Socket.IO with Flask to create real-time updates in web applications. We started by setting up a simple Flask application, and then we integrated Socket.IO with Flask. We then learned how to emit and receive events between the client and server. Finally, we implemented real-time updates using Socket.IO, and we updated a card or component on the Flask dashboard in response to events.
335
400
336
-
This tutorial has shown how easy it is to use Socket.IO with Flask to create real-time updates in web applications. Socket.IO is a powerful tool that can be used to create a variety of real-time applications, such as chat applications, multiplayer games, and stock tickers.
401
+
In this tutorial, we learned how to use Socket.IO with Flask to create real-time updates in web applications.
402
+
We started by setting up a simple Flask application, and then we integrated Socket.IO with Flask.
403
+
We then learned how to emit and receive events between the client and server.
404
+
Finally, we implemented real-time updates using Socket.IO, and we updated a card or component on the Flask dashboard in response to events.
405
+
406
+
This tutorial has shown how easy it is to use Socket.IO with Flask to create real-time updates in web applications.
407
+
Socket.IO is a powerful tool that can be used to create a variety of real-time applications, such as chat applications, multiplayer games, and stock tickers.
0 commit comments