Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Pyramid - Url Routing
Next article icon

Python Pyramid - Url Routing

Last Updated : 27 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
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

Next Article
Python Pyramid - Url Routing

A

ajaymakvana
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

    Python Falcon - Routing
    Falcon is Python based a lightweight and high-performance Python-based web framework designed for building fast and efficient APIs. There are also other Python-based frameworks for building APIs such as Flask, FastAPI, etc. Routing is a fundamental concept in Falcon, as it determines how incoming HT
    4 min read
    Python Pyramid - Request Object
    Python has gained widespread popularity among developers in recent times. Numerous web-related frameworks are available in Python, such as Flask, Django, Pyramid, and FastAPI. Among these frameworks, Python Pyramid stands out as a robust web framework that offers flexibility and scalability for deve
    4 min read
    Check for URL in a String - Python
    We are given a string that may contain one or more URLs and our task is to extract them efficiently. This is useful for web scraping, text processing, and data validation. For example:Input:s = "My Profile: https://auth.geeksforgeeks.org/user/Prajjwal%20/articles in the portal of https://www.geeksfo
    3 min read
    Requesting a URL from a local File in Python
    Making requests over the internet is a common operation performed by most automated web applications. Whether a web scraper or a visitor tracker, such operations are performed by any program that makes requests over the internet. In this article, you will learn how to request a URL from a local File
    4 min read
    How to Urlencode a Querystring in Python?
    URL encoding a query string consists of converting characters into a format that can be safely transmitted over the internet. This process replaces special characters with a '%' followed by their hexadecimal equivalent. In this article, we will explore three different approaches to urlencode a query
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences