[파이썬] Flask-SocketIO 확장

Flask-SocketIO is a powerful extension for Flask that allows you to add real-time communication to your web applications using WebSocket protocol. It provides a simple and intuitive API that makes it easy to incorporate real-time features into your Flask applications. In this blog post, we will explore the basics of Flask-SocketIO and demonstrate how to use it to build real-time web applications.

Installing Flask-SocketIO

To get started with Flask-SocketIO, you first need to install it. You can do this using pip, the Python package manager. Open your terminal and run the following command:

pip install flask-socketio

This will download and install the Flask-SocketIO package along with its dependencies.

Setting up Flask-SocketIO

To use Flask-SocketIO in your Flask application, you need to initialize it and integrate it with your Flask app.

  1. Create a new Flask application or open your existing one.
  2. Import the necessary modules:
from flask import Flask, render_template
from flask_socketio import SocketIO
  1. Initialize the Flask app and the SocketIO object:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
socketio = SocketIO(app)
  1. Define your Flask routes and add the @socketio.on decorator to the routes that require real-time communication.

Adding Real-Time Communication

Flask-SocketIO provides a simple way to handle real-time events and communicate with the server and clients. Here’s an example showcasing how to handle a basic real-time event:

@socketio.on('message')
def handle_message(message):
    print('Received message:', message)
    # Do something with the message

@socketio.on('connect')
def handle_connect():
    print('Client connected')

@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')

In the above example, we have defined three event handlers: handle_message, handle_connect, and handle_disconnect. The @socketio.on decorator is used to associate these functions with the corresponding events.

Running the Flask-SocketIO Application

To run your Flask-SocketIO application, you need to modify your app.run() line to use socketio.run instead. Here’s an example:

if __name__ == '__main__':
    socketio.run(app)

Now you can start your Flask web application as usual, and Flask-SocketIO will handle the real-time communication.

Conclusion

Flask-SocketIO is a powerful extension that allows you to add real-time communication to your Flask applications. It simplifies the process of building real-time web applications by providing an easy-to-use API. With Flask-SocketIO, you can build chat applications, live dashboards, collaborative editing tools, and much more. Give it a try and take your Flask applications to the next level with real-time capabilities!