All addresses to go to a single page (catch-all route to a single view) in Python Pyramid

2024/10/18 15:03:05

I am trying to alter the Pyramid hello world example so that any request to the Pyramid server serves the same page. i.e. all routes point to the same view. This is what iv got so far:

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Responsedef hello_world(request):return Response('Hello %(name)s!' % request.matchdict)if __name__ == '__main__':config = Configurator()config.add_route('hello', '/*')config.add_view(hello_world, route_name='hello')app = config.make_wsgi_app()server = make_server('0.0.0.0', 8080, app)server.serve_forever()

All iv done is change the line (from the hello world example):

    config.add_route('hello', '/hello/{name}')

To:

    config.add_route('hello', '/*')

So I want the route to be a 'catch-all'. Iv tried various variations and cant get it to work. Does anyone have any ideas?

Thanks in advance

Answer

The syntax for the catchall route (which is called "traversal subpath" in Pyramid) is *subpath instead of *. There's also *traverse which is used in hybrid routing which combines route dispatch and traversal. You can read about it here: Using *subpath in a Route Pattern

In your view function you'll then be able to access the subpath via request.subpath, which is a tuple of path segments caught by the catchall route. So, your application would look like this:

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Responsedef hello_world(request):if request.subpath:name = request.subpath[0]else:name = 'Incognito'return Response('Hello %s!' % name)if __name__ == '__main__':with Configurator() as config:config.add_route('hello', '/*subpath')config.add_view(hello_world, route_name='hello')app = config.make_wsgi_app()server = make_server('0.0.0.0', 8081, app)server.serve_forever()

Don't do it via custom 404 handler, it smells of PHP :)

https://en.xdnf.cn/q/73104.html

Related Q&A

Python singleton / object instantiation

Im learning Python and ive been trying to implement a Singleton-type class as a test. The code i have is as follows:_Singleton__instance = Noneclass Singleton:def __init__(self):global __instanceif __i…

Single-Byte XOR Cipher (python)

This is for a modern cryptography class that I am currently taking.The challenge is the cryptopals challenge 3: Single-Byte XOR Cipher, and I am trying to use python 3 to help complete this.I know that…

Basemap Heat error / empty map

I am trying to plot a scattered heat map on a defined geo location. I can very well plot a normal scattered map with no background but I want to combine it with a given lat and lon. I get the following…

Keras custom loss function per tensor group

I am writing a custom loss function that requires calculating ratios of predicted values per group. As a simplified example, here is what my Data and model code looks like: def main():df = pd.DataFrame…

How does numpy.linalg.inv calculate the inverse of an orthogonal matrix?

Im implementing a LinearTransformation class, which inherits from numpy.matrix and uses numpy.matrix.I to calculate the inverse of the transformation matrix.Does anyone know whether numpy checks for or…

pandas: Using color in a scatter plot

I have a pandas dataframe:-------------------------------------- | field_0 | field_1 | field_2 | -------------------------------------- | 0 | 1.5 | 2.9 | -------------------…

Framing Errors in Celery 3.0.1

I recently upgraded to Celery 3.0.1 from 2.3.0 and all the tasks run fine. Unfortunately. Im getting a "Framing Error" exception pretty frequently. Im also running supervisor to restart the t…

decorator() got an unexpected keyword argument

I have this error on Django view:TypeError at /web/host/1/ decorator() got an unexpected keyword argument host_id Request Method: GET Request URL: http://127.0.0.1:8000/web/host/1/edit Django Versio…

Conflict between sys.stdin and input() - EOFError: EOF when reading a line

I cant get the following script to work without throwing an EOFError exception:#!/usr/bin/env python3import json import sys# usage: # echo [{"testname": "testval"}] | python3 test.p…

Requests - inability to handle two cookies with same name, different domain

I am writing a Python 2.7 script using Requests to automate access to a website that sets two cookies with the same name, but different domains, E.g. Name mycookie, Domain www.example.com and subdomain…