Python Falcon - Websocket
Last Updated :
19 Mar, 2024
Websockets provide a powerful mechanism for establishing bidirectional communication between a client and a server over a single, long-lived connection. Python Falcon, a lightweight and fast web framework, offers support for implementing websockets, enabling real-time communication between clients and servers.
What is a Websocket?
WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection. It's commonly used for real-time web applications such as chat applications, online gaming, and live updates. Falcon is a high-performance Python web framework for building RESTful APIs. While Falcon itself doesn't have built-in WebSocket support, you can integrate WebSocket functionality into a Falcon application using libraries such as websocket-server
or websockets
.
Python Falcon - Websocket
Below is the step-by-step procedure to understand about websocket in Python Falcon:
Step 1: Installation
Here, we will install the following libraries and modules before starting:
- Install Python Falcon
- Install Python
Step 2: Setting Up the Environment
Before diving into the implementation, make sure you have the necessary dependencies installed. You'll need falcon, falcon-asgi, jinja2, and uvicorn. You can install them via pip:
pip install falcon falcon-asgi jinja2 uvicorn
Step 3: Implementing WebSocket Chat in Falcon
In this example, we define an HTML template for the chat interface with the title "GeeksforGeeks Chat" and a light green background color. The chat container is centered on the page using flexbox CSS. We implement a Falcon resource called ChatResource. The on_get method serves the HTML template, while the on_websocket method handles WebSocket connections. The WebSocket handler accepts incoming connections and echoes any received messages back to the client.
Python3
import uvicorn
import falcon
import falcon.asgi
import jinja2
html = """
<!DOCTYPE html>
<html>
<head>
<title>GeeksforGeeks Chat</title>
<style>
body {
background-color: #f0f8ea;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
#chat-container {
width: 400px;
padding: 20px;
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body>
<div id="chat-container">
<h1>GeeksforGeeks Chat</h1>
<ul id='messages'></ul>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
</div>
<script>
var ws = new WebSocket("ws://localhost:8000/chat");
ws.onmessage = function(event) {
var messages = document.getElementById('messages');
var message = document.createElement('li');
var content = document.createTextNode(event.data);
message.appendChild(content);
messages.appendChild(message);
};
function sendMessage(event) {
var input = document.getElementById("messageText");
ws.send(input.value);
input.value = '';
event.preventDefault();
}
</script>
</body>
</html>
"""
class ChatResource:
async def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = falcon.HTTP_200
resp.content_type = 'text/html'
template = jinja2.Template(html)
resp.body = template.render()
async def on_websocket(self, req, websocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message: {data}")
app = falcon.asgi.App()
chat = ChatResource()
app.add_route('/chat', chat)
if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
Step 4: Running the Application
To run the Falcon application with WebSocket chat support, execute the script:
python app.py
This will start the Falcon application using the Uvicorn server, which supports ASGI and WebSocket protocols. You can then access the WebSocket chat interface by navigating to http://localhost:8000/chat in your web browser.
Output:

Similar Reads
Python Falcon - Waitress In this article, we will explore Python Falcon-Waitress, a powerful combination for building web APIs with Falcon, and we'll illustrate its usage with practical examples. Falcon-Waitress offers seamless integration of the Falcon framework with the Waitress production-quality WSGI server, enabling yo
7 min read
Sockets | Python What is socket? Sockets act as bidirectional communications channel where they are endpoints of it.sockets may communicate within the process, between different process and also process on different places.Socket Module- s.socket.socket(socket_family, socket_type, protocol=0) socket_family-AF_UNIX
3 min read
Python Falcon - Uvicorn Python-based libraries, Falcon and Uvicorn are two powerful tools that, when used together, form a robust framework for building high-performance web applications. Falcon is a minimalist web framework designed for building fast and efficient APIs. Uvicorn serves as an ASGI server, bringing asynchron
3 min read
Python Falcon - Request & Response Python Falcon, a nimble web framework, simplifies the process of building web APIs by efficiently managing incoming requests, which are messages asking for something from your API, and providing an easy way to create structured responses that Falcon then sends back to the requester, making it a swif
7 min read
Python Falcon - Hello World Falcon is a powerful and minimalistic Python framework for building high-performance APIs. In this article, we'll take a closer look at Falcon and build a simple "Hello World" application using the WSGI (Web Server Gateway Interface) specification. What is Falcon?Falcon is an open-source Python web
2 min read
Python Falcon - WSGI vs ASGI When developing web applications or APIs with Falcon, one crucial decision you'll need to make is whether to use WSGI (Web Server Gateway Interface) or ASGI (Asynchronous Server Gateway Interface) as the communication protocol between Falcon and your web server. In this article, we'll explore the di
7 min read
Web crawling with Python Web crawling is widely used technique to collect data from other websites. It works by visiting web pages, following links and gathering useful information like text, images, or tables. Python has various libraries and frameworks that support web crawling. In this article we will see about web crawl
4 min read
Socket Programming in Python Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the serv
6 min read
Python Falcon - Environment Setup Falcon is a Python library renowned for its proficiency in crafting indispensable REST APIs and microservices. Capable of accommodating both the WSGI (Web Server Gateway Interface) and ASGI (Asynchronous Server Gateway Interface) standards, Falcon has gained widespread recognition since its inceptio
3 min read
WebSockets Protocol and Long Polling As one facet of net development, real-time access Among consumers and servers has now become an important step in creating interactive web programs as well as mouth-watering. Request-reaction mechanisms, even flexible and powerful as they are, may not be suitable for circumstances that call for rapi
10 min read