Open In App

Python – Starlette

This article will delve into the Python web framework, Starlette, exploring its advantages and providing illustrative examples. Through these examples, we aim to enhance understanding and comprehension of Starlette’s capabilities and features.

What is Starlette?

Starlette has emerged as a notable addition to the Python web framework landscape, rapidly gaining favor for its simplicity, performance, and seamless integration with asynchronous programming. Created by Tom Christie, known for notable Python libraries such as ‘requests’ and ‘httpie,’ Starlette offers a robust solution for web development.



Handling essential aspects like routing, middleware, and request/response flow, Starlette operates within the ASGI framework. What sets Starlette apart is its flexibility in allowing developers to make independent choices regarding ORM (Object-Relational Mapping) and database tools. This unique feature grants developers the freedom to select the most suitable options for their specific project requirements.

Advantages of Starlette

In this section, we’ll explore some advantages of Python-Starlette:



Required Installation

Install Necessary Libaries

pip install starlette
pip install uvicorn

Run Server : Run the following command to start the server:

uvicorn new:app --reload

Example 1: Basic Starlette Application

Once installed, you can create a new Starlette application by creating a Python file and importing the necessary modules:




from starlette.applications import Starlette
from starlette.routing import Route
from starlette.responses import PlainTextResponse
 
# Define an asynchronous function to handle the homepage route
async def homepage(request):
    # Return a plain text response with the message "Hello, World!"
    return PlainTextResponse("Hello, World!")
 
# Create a Starlette application and define a route for the homepage
app = Starlette(routes=[
    Route("/", homepage)
])

Output

Output

Examples 2: Middleware Implementation

Below code creates a Starlette web application with CORS middleware enabled to allow all origins. It defines a route for the homepage (“/”) that, when accessed, responds with a plain text message showcasing the implementation of middleware.




# Import necessary modules from Starlette
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.middleware.cors import CORSMiddleware
 
# Create a Starlette application
app = Starlette()
 
# Add CORS middleware to allow all origins
app.add_middleware(CORSMiddleware, allow_origins=["*"])
 
# Define a route for the homepage
@app.route("/")
async def homepage(request):
    # Respond with a plain text message
    return PlainTextResponse("Hello, It's an example of middleware implementation!")

Output :

Middleware Implementation

Example 3: Testing & Debugging

Below code demonstrates a simple Starlette web application with a single route (“/”) that responds with a plain text message. The application is tested using the TestClient class, ensuring the homepage route returns a successful response (status code 200) with the expected text. If executed as a script, the application runs on localhost (127.0.0.1) and port 8000 using the UVicorn server. This example is useful for understanding the basics of creating, testing, and running a Starlette web application for testing and debugging purposes.




# Import necessary modules from Starlette
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.testclient import TestClient
 
# Define the Starlette application with a homepage route
app = Starlette()
 
@app.route("/")
async def homepage(request):
    # Respond with a plain text message for testing and debugging
    return PlainTextResponse("Hello, This is an example of Testing & Debugging!")
 
# Test the homepage route using the TestClient
def test_homepage():
    client = TestClient(app)
    response = client.get("/")
    assert response.status_code == 200
    assert response.text == "Hello, This is an example of Testing & Debugging!"
 
# Run the Starlette application if executed as a script
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Output

Testing & Debugging

Example 4: Websocket Support

Below code showcases a basic Starlette web application with WebSocket support. It defines a root route (“/”) handled by an asynchronous function called homepage, responding with a plain text message. The script includes a test function (test_homepage) using TestClient to simulate a request and validate the expected response. When executed as a script, the application runs on localhost (127.0.0.1) and port 8000 using the UVicorn server.




from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.testclient import TestClient
 
app = Starlette()
 
@app.route("/")
async def homepage(request):
    return PlainTextResponse("Hello, This is an example of Websocket Support!")
 
def test_homepage():
    response = TestClient(app).get("/")
    assert response.status_code == 200
    assert response.text == "Hello, This is an example of Websocket Support!"
 
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Output

output

Conclusion

In summary, Starlette is a lightweight and versatile Python web framework designed for building fast and asynchronous web applications. It offers simplicity, flexibility, and features like WebSocket support and middleware, making it suitable for a wide range of projects, from simple APIs to high-performance applications. Its compatibility with ASGI enhances its integration capabilities with other asynchronous servers. Overall, Starlette provides developers with the tools to create modern and responsive web services in Python.


Article Tags :