Open In App

Python Pyramid – Url Routing

Last Updated : 27 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

URL routing is a fundamental aspect of web application development, as it defines how different URLs in your application are mapped to specific views or functions. In Python Pyramid, a powerful web framework, URL routing is made simple and flexible. In this article, we will explore the concept of URL routing in Python Pyramid, with practical examples with proper output screenshots.

URL routing in Python Pyramid

URL routing is the process of defining how incoming URLs are processed within your web application. It involves mapping URLs to specific views or functions, allowing users to access different parts of your application by navigating to distinct URLs. Python Pyramid provides a robust and customizable URL routing system that enables developers to define and manage URL structures efficiently.

Key Concepts Related to URL Routing:

  1. Routing Paths: Within Pyramid, URL routing predominantly relies on routing paths. A routing path corresponds to a specific view/function based on a URL pattern. In your Pyramid application’s setup, you have the ability to establish these routing paths. Each path is composed of a URL structure, a unique identifier, and a view function.
  2. Functioning Views : A functioning view is a Python function connected with a routing path. When a user accesses a URL matching a specific path, the connected view function executed. These view functions manage user requests, process data, and produce responses.
  3. URL Matching : URL matching is the procedure of linking an incoming URL to a predefined path. Pyramid’s URL dispatcher handles this process efficiently. It recognizes the path that corresponds to the URL and executes the related view function.
  4. Path Variables : Paths can encompass variables enclosed within curly braces `{}`. These variables capture data from the URL and provide them as inputs to the view function. Path variables are valuable for constructing dynamic and data-influenced views.

Example 1: Basic Routing

In this example, we define a route ‘/hello‘ that maps to the hello view callable. When a user accesses ‘/hello’, the “Hello, GFG User!” message is displayed. Here, we defined function named hello. This function is a view callable, which means it handles incoming HTTP requests and returns HTTP responses. In this case, the hello view returns a “Hello, GFG User!” response.

The config.add_route method is used to define a route named ‘hello’. This route is associated with the URL pattern ‘/hello’. It specifies that when a user accesses the ‘/hello’ URL, the associated view function (in this case, ‘hello’) should be called. The config.add_view method is used to associate the ‘hello’ route with the ‘hello’ view function. This means that when a user accesses the ‘/hello’ URL, the ‘hello’ view function will be executed to generate a response.

Here config.make_wsgi_app() method is called to create a WSGI (Web Server Gateway Interface) application based on the configuration set up by the config object. This application is ready to handle HTTP requests and route them according to the defined route. Here the make_server function to create a simple WSGI server. This server will listen on IP address ‘127.0.0.1’ (localhost) and port 6543.

Python3




# Import necessary modules
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
 
# Define a view function 'hello' that returns a "Hello, Pyramid!" response
def hello(request):
    return Response("Hello, GFG User!")
 
# Check if this script is the main program
if __name__ == '__main__':
    # Create a Pyramid configurator
    config = Configurator()
 
    # Define a route named 'hello' with the URL pattern '/hello'
    config.add_route('hello', '/hello')
 
    # Associate the 'hello' route with the 'hello' view function
    config.add_view(hello, route_name='hello')
 
    # Create a WSGI application based on the configuration
    app = config.make_wsgi_app()
 
    # Create a simple WSGI server listening on IP '127.0.0.1' and port 6543
    server = make_server('127.0.0.1', 6543, app)
 
    # Start the WSGI server and serve the application indefinitely
    server.serve_forever()


VS Code Output:

Screenshot-2023-10-19-103929

VS code terminal output example 1

Browser Output:

New-InPrivate-tab---[InPrivate]---Microsoft_-Edge-2023-10-19-10-36-19

Browser Output example 1

Example 2: Route with Parameters

In this example, we define a route ‘/greet/{name}‘ that maps to the hello view callable. When a user accesses ‘/greet/Ajay’, the “Hello, Ajay!” message is displayed. Here, we defined function named greet. This function is a view callable, which means it handles incoming HTTP requests and returns HTTP responses.

Python3




# Import necessary modules
from wsgiref.simple_server import make_server  # Import make_server from the wsgiref package
from pyramid.config import Configurator
from pyramid.response import Response
 
# Define a view function 'greet' that accepts a 'name' parameter from the route
def greet(request):
    # Retrieve the 'name' parameter from the route's matchdict
    name = request.matchdict['name']
     
    # Generate a response message that includes the provided 'name'
    return Response(f"Hello, {name}!")
 
# Check if this script is the main program
if __name__ == '__main__':
    # Create a Pyramid configurator
    config = Configurator()
 
    # Define a route named 'greet' with a URL pattern '/greet/{name}'
    config.add_route('greet', '/greet/{name}')
 
    # Associate the 'greet' route with the 'greet' view function
    config.add_view(greet, route_name='greet')
 
    # Create a WSGI application based on the configuration
    app = config.make_wsgi_app()
 
    # Create a simple WSGI server listening on IP '127.0.0.1' and port 6543
    server = make_server('127.0.0.1', 6543, app)
 
    # Start the WSGI server and serve the application indefinitely
    server.serve_forever()


VS Code Output:

Screenshot-2023-10-19-104534

VS code terminal output example 2

Browser Output:

New-InPrivate-tab---[InPrivate]---Microsoft_-Edge-2023-10-19-10-43-48

Browser Output example 2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads