Skip to content

Commit 2e654f8

Browse files
committed
Release v1.0.48 - Added Flask and SocketIO
1 parent 55da3d4 commit 2e654f8

File tree

2 files changed

+108
-28
lines changed

2 files changed

+108
-28
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# Change Log
22

3+
## [1.0.48] 2023-07-03
4+
### Changes
5+
6+
- UPD [Flask Section](https://docs.appseed.us/technologies/flask/)
7+
- [Flask and SocketIO](https://docs.appseed.us/technologies/flask/socketio/)
8+
- General `Concepts` and `Coding Sample`
9+
310
## [1.0.47] 2023-06-25
411
### Changes
512

docs/technologies/flask/socketio.mdx

Lines changed: 101 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,16 @@ import SubHeading from "@site/src/components/SubHeading";
88

99
<SubHeading color="#25c2a0">Learn how to use Flask with SocketIO</SubHeading>
1010

11-
> Coding Sample: https://github.com/app-generator/sample-flask-socketio
11+
- 👉 [Flask SocketIO Sample](https://github.com/app-generator/sample-flask-socketio) - published on `GitHub`
12+
- 👉 Free [Support](https://appseed.us/support/) via Email & Discord
1213

1314
## 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.
1515

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`:
1721
1822
1. Real-time communication: Socket.IO enables instantaneous and bidirectional data exchange between web clients and servers, eliminating the need for page refreshes.
1923

@@ -33,20 +37,27 @@ Socket.IO finds application in various scenarios, including:
3337

3438
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.
3539

40+
<br />
3641

3742
## 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).
46+
47+
<br />
3948

4049
### Setting up Flask application
4150

42-
* Clone the repository into your machine
51+
> Clone the repository into your machine
52+
4353
```bash
4454
$ git clone https://github.com/app-generator/sample-flask-socketio
4555
$ cd sample-flask-socketio
4656
sample-flask-socketio$
4757
```
4858

49-
* Create a virtual environment and activate the environment to isolate the development environment from your global Python installation
59+
> Create a virtual environment and activate the environment to isolate the development environment from your global Python installation
60+
5061
```bash
5162
sample-flask-socketio$ virtualenv venv
5263
sample-flask-socketio$
@@ -55,28 +66,34 @@ sample-flask-socketio$
5566
sample-flask-socketio$ .\venv\Scripts\activate # on Windows
5667
```
5768

58-
* Install the project dependencies using pip
69+
> Install the project dependencies using pip
70+
5971
```bash
6072
(venv) sample-flask-socketio$ pip install -r requirements.txt
6173
```
6274

63-
* 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+
6477
```bash
6578
(venv) sample-flask-socketio$ flask run
6679
```
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 />
6884

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`
7086

71-
### Integrating Socket.IO with flask
7287
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.
7388

7489
* Install `flask-socketio` package using the command
90+
7591
```bash
7692
(venv) sample-flask-socketio$ pip install flask-socketio
7793
```
7894

7995
* 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+
8097
```py
8198
# apps/events.py
8299

@@ -90,6 +107,7 @@ def connect_event():
90107
```
91108

92109
* Add Socket.IO to the application by making the following changes to `apps/__init__.py`
110+
93111
```
94112
# apps/__init__.py
95113
...
@@ -102,9 +120,13 @@ def create_app(config):
102120
return app
103121
```
104122

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.
106127

107128
* Make the following changes to `run.py`
129+
108130
```py
109131
# run.py
110132
...
@@ -116,12 +138,13 @@ if __name__ == "__main__":
116138
```
117139

118140
* Add SocketIO script tag to `apps/templates/home/index.html`, this loads the Socket.IO library and establishes a connection.
141+
119142
```html
120143
<!-- apps/templates/home/index.html -->
121144
...
122145
<body>
123146
...
124-
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
147+
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
125148
<script>
126149
const socket = io();
127150
socket.on('connect', function(data) {
@@ -132,17 +155,23 @@ if __name__ == "__main__":
132155
```
133156

134157
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).
139158

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.
142170

143171
Next, we will be sending a message from the client to the server and then we will print that message on the terminal.
144172

145173
* Make the following change to `apps/templates/home/base.html`
174+
146175
```html
147176
<!-- apps/templates/home/index.html -->
148177
...
@@ -156,19 +185,26 @@ Next, we will be sending a message from the client to the server and then we wil
156185
```
157186

158187
* Add the following line of code to `apps/events.py`
188+
159189
```py
160190
# apps/events.py
161191
...
162192
@socketio.on('message')
163193
def handle_message(data):
164194
print('This is a message:', data)
165195
```
196+
166197
Refresh your browser and check your Python terminal. You will observe that the message from the client is printed on the Python terminal.
167198

199+
<br />
200+
168201
#### 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.
170205

171206
* Create a custom event called `new event` by adding the code below to `apps/events.py`
207+
172208
```py
173209
# apps/events.py
174210
...
@@ -179,6 +215,7 @@ def handle_new_event(data):
179215
```
180216

181217
* Add the code below to `apps/templates/home/index.html` to receive and send events from the client side
218+
182219
```html
183220
<!-- apps/templates/home/index.html -->
184221
<script type="text/javascript" charset="utf-8">
@@ -190,12 +227,18 @@ def handle_new_event(data):
190227
});
191228
</script>
192229
```
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.
194230

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+
196238
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.
197239

198240
* 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+
199242
```py
200243
# apps/home/model.py
201244
from apps import db
@@ -222,6 +265,7 @@ class Sales(db.Model):
222265
```
223266

224267
* Make the following update to `apps/__init__.py` so the new `Sales` table can be created when the flask server starts up.
268+
225269
```py
226270
# apps/__init__.py
227271
...
@@ -230,12 +274,18 @@ def register_extensions(app):
230274
db.init_app(app)
231275
...
232276
```
277+
233278
Please restart the Flask server and visit the homepage. This action will result in the addition of the `Sales` table to the database.
234279

280+
<br />
281+
235282
### 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.
237286

238287
* We will be creating a route for adding new entries to the `Sales` table. Add the code below to `apps/home/routes.py`
288+
239289
```py
240290
# apps/home/routes.py
241291
...
@@ -260,16 +310,19 @@ def add_sale():
260310
emit('sales', data, broadcast=True, namespace='/')
261311
return jsonify(dict(**request.form), 200)
262312
```
313+
263314
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.
264315

265316
While the Flask server is running, open another terminal and execute the following command to add entries to your database using the route:
266317

267318
```bash
268319
curl -X POST -F product=product-name -F amount=product-amount -F status=Completed http://localhost:5000/sales
269320
```
321+
270322
**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`.
271323

272324
* 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
325+
273326
```html
274327
<!-- apps/templates/home/index.html -->
275328
...
@@ -281,12 +334,18 @@ curl -X POST -F product=product-name -F amount=product-amount -F status=Complete
281334
});
282335
</script>
283336
```
337+
284338
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.
285339

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+
287344
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.
288345

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+
290349
```py
291350
# apps/home/routes.py
292351
...
@@ -300,6 +359,7 @@ def index():
300359
```
301360

302361
* Let's make the following changes to `apps/templates/home/index.html` to retrieve the orders received from the database
362+
303363
```html
304364
<!-- apps/templates/home/index.html -->
305365
...
@@ -310,9 +370,11 @@ def index():
310370
</div>
311371
...
312372
```
373+
313374
**NOTE** Take note of the added `id` attribute inside the `span` tags
314375

315376
* 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+
316378
```html
317379
...
318380
<script type="text/javascript" charset="utf-8">
@@ -328,12 +390,23 @@ def index():
328390
</script>
329391
...
330392
```
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 />
332398

333399
## 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.
335400

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.
408+
409+
<br />
337410

338411
## Resources
339412

0 commit comments

Comments
 (0)