Python Pyramid – Logging

Python Pyramid – Logging ”; Previous Next In order to collect useful information about the application, Pyramid uses the logging module from Python”s standard library. It proves useful in development as well as production mode to detect problems if any, during the running of the application. The application log can include your own messages integrated with messages from third-party modules. The logged messages have following predefined types (in the order of decreasing severity) − CRITICAL ERROR WARNING INFO DEBUG NOTSET By default, he logging messages are redirected to sys.stderr stream. To start collecting logging messages, we need to declare a Logger object. import logging log = logging.getLogger(__name__) Log messages can now be generated with logger methods corresponding to the desired logging levels. To generate a message which can prove useful for debugging the application, use log.debug() message with appropriate message string. A Pyramid application based on PasteDeploy configuration makes it very easy to enable incorporate logging support. The PasteDEploy files (development.ini as well as production.ini) use the ConfigParser format used in the logging module”s configuration parameters. The logging related sections in development.ini are passed to the logging module”s configuration process when it is invoked by pserve command. Various logger sections in the configuration file specify the keys, formats and the logger levels for the application objects. Following logging related sections are declared in a typical “development.ini” file − # Begin logging configuration [loggers] keys = root, hello [logger_hello] level = DEBUG handlers = qualname = hello [handlers] keys = console [formatters] keys = generic [logger_root] #level = INFO level=DEBUG handlers = console [handler_console] class = StreamHandler args = (sys.stderr,) level = NOTSET formatter = generic [formatter_generic] format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s # End logging configuration Let us add these sections in the development.ini file of our Hello application in the previous chapter. Example Next, declare the Logger object and put a debug message in the hello_world() few function. Here”s the __init__.py code − from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config import logging log = logging.getLogger(__name__) from pyramid.renderers import render_to_response def hello_world(request): log.debug(”In hello view”) return render_to_response(”templates/hello.html”, {”name”:request.matchdict[”name”]},request=request) def main(global_config, **settings): config = Configurator(settings=settings) config.include(”pyramid_jinja2”) config.add_jinja2_renderer(“.html”) config.add_route(”hello”, ”/{name}”) config.add_view(hello_world, route_name=”hello”) return config.make_wsgi_app() The hello_world() view renders the following hello.html template − <html> <body> <h1>Hello, {{ name }}!</h1> </body> </html> Run the application as usual − pserve development.ini When http://localhost:6543/Tutorialpoint URL is entered in the browser, the command window echoes following debug message − Starting monitor for PID 11176. Starting server in PID 8472. 2022-06-26 01:22:47,032 INFO [waitress][MainThread] Serving on http://[::1]:6543 2022-06-26 01:22:47,032 INFO [waitress][MainThread] Serving on http://127.0.0.1:6543 2022-06-26 01:22:47,418 DEBUG [hello][waitress-1] In hello view Output Since the debug toolbar is enabled in the configuration, it is displayed in the browser − The debug message is also displayed on the logging tab of the debug toolbar as shown below − Print Page Previous Next Advertisements ”;

Python Pyramid – Overview

Python Pyramid – Overview ”; Previous Next Pyramid is an open source, WSGI compliant web framework written in Python. Initially the project named as Pylons, but later released under the new name Pyramid. Pyramid is a minimalistic web framework. It doesn”t come packaged with any templating library or doesn”t have support for any specific database packages. However, it can be integrated both with SQL databases via SQLAlchemy and with the Zope Object Database, as well as other NoSQL databases such as CouchDB. Pyramid can also be configured to work with templating libraries such as Mako, Jinja2 or Chameleon. Pyramid has been developed by Chris McDonough. The first version of Pyramid was released in January 2011. The latest version, Pyramid 2.0 has been released in March 2021. Comparison with Other Python Frameworks Pyramid web application framework is inspired by Zope and Django frameworks. As a result, it combines the best provisions of the two. Pyramid is largely based on repose.bfg framework. After it was merged with the Pylons project, the same was renamed as Pyramid in 2010. The ability to extend Pyramid application is borrowed from Zope library. Without modifying the application code, the application can be reused, modified or extended. The features such as declarative security layer and traversal of routes is inherited from Zope. As is the case of Pylons 1.0, Pyramid doesn”t enforce any policy. It also lets the user choose any database or templating system The URL dispatch approach is also inspired by Pylons. The concept of views is based on similar approach of Django. Extensive documentation is also a Django features adapted by Pyramid. Although the definition doesn”t fit exactly, Pyramid can be said to follow MVC (Model-View-Controller) approach. Print Page Previous Next Advertisements ”;

Pyramid – Application Configuration

Python Pyramid – Application Configuration ”; Previous Next The Pyramid application object has an application registry that stores mappings of view functions to routes, and other application-specific component registrations. The Configurator class is used to build the application registry. The Configurator life cycle is managed by a context manager that returns an application object. with Configurator(settings=settings) as config: #configuration methods app = config.make_wsgi_app() The Configurator class defines the following important methods to customize the application − add_route() This method registers a route for URL dispatch. Following arguments are used − name − The first required positional argument must be a unique name for the route. The name is used to identify the route when registering views or generating URLs. pattern − The second required positional argument is a string representing the URL path optionally containing variable placeholders for parsing the variable data from the URL. The placeholders are surrounded by curly brackets. For example, “/students/{id}”. request_method − The value can be one of “GET”, “POST”, “HEAD”, “DELETE”, “PUT”. Requests only of this type will be matched against the route. add_view() This method adds a view configuration to the application registry. It binds a view function to the route_name present in the configuration. The arguments required are − view − The name of a view function. route_name − A string that must match the name of a route configuration declaration. request_method − Either a string (such as “GET”, “POST”, “PUT”, “DELETE”, “HEAD” or “OPTIONS”) representing an HTTP REQUEST_METHOD, or a tuple containing one or more of these strings. add_static_view() This method adds a view used to render static assets such as images and CSS files, and uses the following arguments − name − This argument is a string representing an application-relative local URL prefix, or a full URL. Path − This argument represents the path on disk where the static files reside. Its value can be an absolute or a package-relative path. This method in turn calls the add_route() method of Configurator object. add_notfound_view() This method adds a view to be executed when a matching view cannot be found for the current request. The following code shows an example − from pyramid.config import Configurator from pyramid.response import Response def notfound(request): return Response(”Not Found”, status=”404 Not Found”) config.add_notfound_view(notfound) add_forbidden_view() Configures the application registry so as to define a view to be executed when there is HTTPForbidden exception raised. The argument list contains a reference to a function that returns a 403 status response. If no argument is provided, the registry adds default_exceptionresponse_view(). add_exception_view() This method causes addition of an exception view function to the configuration, for the specified exception. make_wsgi_app() This method returns a Pyramid WSGI application object. scan() This is a wrapper for registering views. It imports all application modules looking for @view_config decorators. For each one, it calls config.add_view(view) with the same keyword arguments. A call to scan() function performs the scan of the package and all the subpackages for all the decorations. A typical sequence of statements that performs configuration of application registry is as in the following code snippet − from pyramid.config import Configurator with Configurator() as config: config.add_route(”hello”, ”/”) config.add_view(hello_world, route_name=”hello”) app = config.make_wsgi_app() This approach towards configuration of the application is called imperative configuration. Pyramid provides another approach towards configuration, called as decorative configuration. Declarative Configuration Sometimes, it becomes difficult to do the configuration by imperative code, especially when the application code is spread across many files. The declarative configuration is a convenient approach. The pyramid.view model defines view_config – a function, class or method decorator – that allows the view registrations very close to the definition of view function itself. Two important arguments are provided to @view_config() decorator. They are route_name and request_method. They bear same explanation as in add_route() method of Configurator class. The function just below it is decorated so that it is bound to the route added to the registry of the application object. Give below is the example of declarative configuration of hello_world() view function − from pyramid.response import Response from pyramid.view import view_config @view_config(route_name=”hello”, request_method=”GET”) def hello_world(request): return Response(”Hello World!”) The view_config decorator adds an attribute to the hello_world() function, making it available for a scan to find it later. Example The combination of configuration decoration and the invocation of a scan is collectively known as declarative configuration. Following code configures the application registry with declarative approach. The scan() function discovers the routes and their mapped views, so that there is the need to add imperative configuration statements. from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config @view_config(route_name=”hello”, request_method=”GET”) def hello_world(request): return Response(”Hello World!”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) config.scan() app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() The scanner translates the arguments to view_config into a call to the pyramid.config.Configurator.add_view() method, so that the action is equivalent to the following statement − config.add_view(hello_world, route_name=”hello”, request_method=”GET”) Output After the above program is run, the WSGI server starts. When the browser visits the link http://localhost:6543/, the “Hello World” message is rendered as before. Print Page Previous Next Advertisements ”;

Pyramid – Environment Setup

Python Pyramid – Environment Setup ”; Previous Next It is recommended that the Pyramid package be installed on a system having Python 3.6 or above version installed. Pyramid can be installed on Linux, MacOS as well as Windows platform. Simplest way of installing it is by using PIP installer, preferably under a Python virtual environment. pip3 install pyramid Although a Pyramid web application can be run using the built-in WSGI development server that is a part of the wsgiref module, it is not recommended for use in production environment. Hence, we also install Waitress, a production-quality pure-Python WSGI server (also a part of Pylons project). pip3 install waitress This will install Pyramid (ver 2.0), Waitress (ver 2.1.2) in addition to other dependencies from Pylon project such that WebOb, PasteDeploy, and others. To check what gets installed, run pip freeze command. pip3 freeze hupper==1.10.3 PasteDeploy==2.1.1 plaster==1.0 plaster-pastedeploy==0.7 pyramid==2.0 translationstring==1.4 venusian==3.0.0 waitress==2.1.2 WebOb==1.8.7 zope.deprecation==4.4.0 zope.interface==5.4.0 Print Page Previous Next Advertisements ”;

Python Pyramid – Home

Python Pyramid Tutorial PDF Version Quick Guide Resources Job Search Discussion Pyramid is an open source, WSGI compliant web framework written in Python. Initially the project named as Pylons, but later released under the new name Pyramid. Apart from Pyramid, the Pylons Project consists of different web application technologies such as Waitress (a WSGI server), SubstanceD (Pyramid-based application server), WebOb (a WSGI request/response library), and many more. Audience This tutorial is designed for Python developers who want to learn to build robust, scalable MVC pattern web applications using Pyramid framework. Prerequisites Before you proceed, make sure that you understand the basics of procedural and object-oriented programming in Python. Knowledge of REST architecture is an added advantage. Print Page Previous Next Advertisements ”;

Python Pyramid – Url Routing

Python Pyramid – Url Routing ”; Previous Next Before the advent of MVC architecture, web applications used the mechanism of mapping the URL entered by the user in the browser, to a program file whose output was rendered as HTML to as a response back to the browser. Pyramid framework uses a routing mechanism where the endpoint of the URL is matched with different URL patterns registered in the application”s registry, invokes its mapped view and renders the response. A typical URL comprises of three parts: The protocol (such as http:// or https://) followed by the IP address or hostname. The remaining part of the URL after first / after the hostname is called as the path or endpoint. The endpoint followed by one or more variable parts forms the route. The variable part identifiers are surrounded by curly brackets. For example, for the above URL, the route is /blog/{id} The WSGI application acts as a router. It checks the incoming request against the URL patterns present in the route map. If a match is found, its associated view callable is executed and the response is returned. Route Configuration A new route is added to the application by invoking add_route() method of the Configurator object. A route has a name, which acts as an identifier to be used for URL generation and a pattern that is meant to match against the PATH_INFO portion of a URL (the portion following the scheme and port, e.g., /blog/1 in the URL http://example.com/blog/1). As mentioned earlier, the pattern parameter of add_route() method can have one or more placeholder identifiers surrounded by curly brackets and separated by /. Following statement assigns ”index” as the name of route given to ”/{name}/{age}” pattern. config.add_route(”index”, ”/{name}/{age}”) To associate a view callable to this route, we use add_view() function as follows − config.add_view(index, route_name=”index”) The index() function should be available for the route to be matched to it. def index(request): return Response(”Root Configuration Example”) Example We put these statements in the program below − from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def index(request): return Response(”Root Configuration Example”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”index”, ”/{name}/{age}”) config.add_view(index, route_name=”index”) app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() Output Run the above code and visit http://localhost:6543/Ravi/21 in the browser. As the URL”s PATH_INFO matches with the index route, the following output is displayed − The pattern used in route configuration usually starts with a forward slash (/) character. A pattern segment (an individual item between / characters in the pattern) may either be a literal string, or it may be a placeholder marker (e.g., {name}), or a certain combination of both. A replacement marker does not need to be preceded by a / character. Here are some examples of route patterns /student/{name}/{marks} /{id}/student/{name}/{marks} /customer/{id}/item/{itemno} /{name}/{age} The place holder identifier must be a valid Python identifier. Hence, it must begin with an uppercase or lowercase ASCII letter or an underscore, and it can only have uppercase or lowercase ASCII letters, underscores, and numbers. Route Matching When the incoming request matches with the URL pattern associated with a particular route configuration, a dictionary object named matchdict is added as an attribute of the request object. The request.matchdict contains the values that match replacement patterns in the pattern element. The keys in a matchdict are strings, while their values are Unicode objects. In the previous example, change the index() view function to following − def index(request): return Response(str(request.matchdict)) The browser displays the path parameters in the form of a dict object. When the request matches a route pattern, the request object passed to the view function also includes a matched_route attribute. The name of the matched route can be obtained from its name property. Example In the following example, we have two view functions student_view() and book_view() defined with the help of @view.config() decorator. The application”s registry is configured to have two corresponding routes – ”student” mapped to ”/student/{name}/{age}” pattern and ”book” mapped to ”/book/{title}/{price}” pattern. We call the scan() method of configurator object to add the views. from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config @view_config(route_name=”student”) def student_view(request): return Response(str(request.matchdict)) @view_config(route_name=”book”) def book_view(request): title=request.matchdict[”title”] price=request.matchdict[”price”] return Response(”Title: {}, Price: {}”.format(title,price)) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”student”, ”/student/{name}/{age}”) config.add_route(”book”, ”/book/{title}/{price}”) config.scan() app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() Output When the browser is given http://localhost:6543/student/Ravi/21 URL, the output is {”name”: ”Ravi”, ”age”: ”21”} If the URL entered is http://localhost:6543/book/Python/300, the output is Title: Python, Price: 300 Print Page Previous Next Advertisements ”;

Python Pyramid – Hello World

Python Pyramid – Hello World ”; Previous Next Example To check whether Pyramid along with its dependencies are properly installed, enter the following code and save it as hello.py, using any Python-aware editor. from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def hello_world(request): return Response(”Hello World!”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) config.add_view(hello_world, route_name=”hello”) app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() The Configurator object is required to define the URL route and bind a view function to it. The WSGI application object is obtained from this config object is an argument to the make_server() function along with the IP address and port of localhost. The server object enters a listening loop when serve_forever() method is called. Run this program from the command terminal as. Python hello.py Output The WSGI server starts running. Open the browser and enter http://loccalhost:6543/ in the address bar. When the request is accepted, the hello_world() view function gets executed. It returns the Hello world message. The Hello world message will be seen in the browser window. As mentioned earlier, the development server created by make_server() function in the wsgiref module is not suited for production environment. Instead, we shall use Waitress server. Modify the hello.py as per the following code − from pyramid.config import Configurator from pyramid.response import Response from waitress import serve def hello_world(request): return Response(”Hello World!”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) config.add_view(hello_world, route_name=”hello”) app = config.make_wsgi_app() serve(app, host=”0.0.0.0”, port=6543) All other functionality is same, except we use serve() function of waitress module to start the WSGI server. On visiting the ”/” route in the browser after running the program, the Hello world message is displayed as before. Instead of a function, a callable class can also be used as a view. A callable class is the one which overrides the __call__() method. from pyramid.response import Response class MyView(object): def __init__(self, request): self.request = request def __call__(self): return Response(”hello world”) Print Page Previous Next Advertisements ”;

Python Pyramid – View Configuration

Python Pyramid – View Configuration ”; Previous Next The term “View Configuration” refers to the mechanism of associating a view callable (a function, method or a class) with the information of route configuration. Pyramid finds the best callable for the given URL pattern. There are three ways to configure a view − Using add_view() method Using @view_config() decorator Using @view_defaults () class decorator Using add_view() Method This is the simplest method of configuring a view imperatively by calling the add_view() method of the Configurator object. This method uses the following arguments − name − The view name required to match this view callable. If name is not supplied, the empty string is used (implying the default view). context − This resource must be an object of a Python class in order for this view to be found and called. If context is not supplied, the value None, which matches any resource, is used. route_name − This value must match the name of a route configuration declaration that must match before this view will be called. If route_name is supplied, the view callable will be invoked only when the named route has matched. request_type − an interface that the request must provide in order for this view to be found and called. request_method − a string (such as “GET”, “POST”, “PUT”, “DELETE”, “HEAD”, or “OPTIONS”) representing an HTTP REQUEST_METHOD or a tuple containing one or more of these strings. The view will be called only when the method attribute of the request matches a supplied value. request_param − This argument can be any string or a sequence of strings. The view will only be called when the request.params dictionary has a key which matches the supplied value. Example In the following example, two functions getview() and postview() are defined and associated with two routes of the same name. These functions just return the name of the HTTP method by which they are called. The getview() function is called when the URL /get is requested using GET method. Similarly, the postview() function is executed when /post path id requested by POST method. from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def getview(request): ret=request.method return Response(”Method: {}”.format(ret)) def postview(request): ret=request.method return Response(”Method: {}”.format(ret)) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”getview”, ”/get”) config.add_route(”postview”, ”/post”) config.add_view(getview, route_name=”getview”,request_method=”GET”) config.add_view(postview,route_name=”postview”, request_method=”POST”) app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() While the GET request can be sent by using the web browser as HTTP client, it is not possible to use it for POST request. Hence, we use the CURL command line utility. C:UsersAcer>curl localhost:6543/get Method: GET C:UsersAcer>curl -d “param1=value1” -H “Content-Type: application/json” -X POST http://localhost:6543/post Method: POST As mentioned earlier, the request_method parameter can be a list of one or more HTTP methods. Let us modify the above program and define a single oneview() function that identifies the HTTP method that causes its execution. def oneview(request): ret=request.method return Response(”Method: {}”.format(ret)) This function is registered in the application”s configuration for all the HTTP methods. config.add_route(”oneview”, ”/view”) config.add_view(oneview, route_name=”oneview”, request_method=[”GET”,”POST”, ”PUT”, ”DELETE”]) Output The CURL output is shown as below − C:UsersAcer>curl localhost:6543/view Method: GET C:UsersAcer>curl -d “param1=value1” -H “Content-Type: application/json” -X POST http://localhost:6543/view Method: POST C:UsersAcer>curl -d “param1=value1” -H “Content-Type: application/json” -X PUT http://localhost:6543/view Method: PUT C:UsersAcer>curl -X DELETE http://localhost:6543/view Method: DELETE Using @view_config() Decorator Instead of adding views imperatively, the @view_config decorator can be used to associate the configured routes with a function, a method or even a callable class. Example As described in the Declarative Configuration section, a registered route can be associated with a function as in the following example − from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config @view_config(route_name=”hello”) def hello_world(request): return Response(”Hello World!”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) config.scan() app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() Note that the views are added into the application configuration only after calling the scan() method. While removes the need for imperatively adding the views, the performance may be slightly slower. Output The view_config() decorator can also be given same arguments as that of add_view() method. All arguments may be omitted. @view_config() def hello_world(request): return Response(”Hello World!”) In such a case, the function will be registered with any route name, any request method or parameters. The view_config decorator is placed just before the definition of callable view function, as in the above example. It can also be put on top of a class if it is to be used as the view callable. Such a class must have a __call__() method. In the following Pyramid application code, the MyView class is used as a callable and is decorated by the @view_config decorator. from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config @view_config(route_name=”hello”) class MyView(object): def __init__(self, request): self.request = request def __call__(self): return Response(”hello World”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) #config.add_view(MyView, route_name=”hello”) config.scan() app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() Note that instead of scanning for view configurations, we can add views by explicitly calling the add_view() method. Example If the methods in a class have to be associated with different routes, separate @view_config() should be used on top of each one of them, as done in the following example. Here, we have two methods bound to two separate routes. from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import class MyView(object): def __init__(self, request): self.request = request @view_config(route_name=”getview”, request_method=”GET”) def getview(self): return Response(”hello GET”) @view_config(route_name=”postview”,

Python Pyramid – Templates

Python Pyramid – Templates ”; Previous Next By default, the content-type of the response of a view function is in plain text. In order to render HTML, the text of the response body may include HTML tags, as in the following example − Example from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response def hello_world(request): return Response(”<h1 style=”text-align:center;”>Hello World!</h1>”) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) config.add_view(hello_world, route_name=”hello”) app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() Output After starting the server (by running the above code), visit to http://localhost:6543/, the browser renders following output − However, this method of rendering HTML, especially if it is likely to contain certain variable data, is extremely cumbersome. For this purpose, web frameworks use templating libraries. A template library merges the variable data with the otherwise static HTML code to generate and render web pages dynamically. Template Bindings Pyramid provides templating support with the help of bindings to popular template libraries such as jinja2, Mako and Chameleon. Template Language Pyramid Bindings Default Extensions Chameleon pyramid_chameleon .pt, .txt Jinja2 pyramid_jinja2 .jinja2 Mako pyramid_mako .mak, .mako First of all, we need to install the corresponding Python library for using the required template library. For example, to use jinja2 template, install pyramid_jinja2 using PIP installer. pip3 install pyramid_jinja2 Then we need to include it in the application configuration. config.include(”pyramid_jinja2”) The pyramid.renderers module defines render_to_response() function. It is used with following parameters − render_to_response(renderer_name, value, request) The renderer_name is the template web page, usually saved in the templates subfolder of the application directory, the value parameter is a dictionary passed as a context to the template, and the request object obtained from WSGI environment. Save the following HTML script as hello.jinja2 in the templates folder. <html> <body> <h1>Hello, {{ name }}!</h1> </body> </html> Jinja2 Template Library Here, ”name” is a jinja2 template variable. The jinja2 template language inserts variables and programming constructs in the HTML scripts using following syntax − Expressions {{ … }} for Expressions to print to the template output. {% … %} for Statements. {# … #} for Comments not included in the template output. Conditionals {% if expr %} {% else %} {% endif %} Loop {% for var in iterable %} {% endfor %} In hello.jinja2 {{ name }}, the value of ”name” context variable is dynamically rendered in the view response. Rendering Template The hello_world() view function directly renders this template by calling render_to_response() function. It also sends a context value to the template. from pyramid.renderers import render_to_response def hello_world(request): return render_to_response(”templates/hello.jinja2”,{”name”:”Tutorialspoint”}, request=request) Example As usual, this view is added to the hello route, pointing to / URL. The complete application code is as follows − from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.renderers import render_to_response def hello_world(request): return render_to_response(”templates/hello.jinja2”, {”name”:”Tutorialspoint”}, request=request) if __name__ == ”__main__”: with Configurator() as config: config.add_route(”hello”, ”/”) config.include(”pyramid_jinja2”) config.add_view(hello_world, route_name=”hello”) app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() Output Run the server and visit http://localhost:6543/. The browser shows following result − Every view must return a response object. The render_to_response() function is a shortcut function that actually returns a response object. This allows the hello_world view above to simply return the result of its call to render_to_response() directly. On the other hand, pyramid.renderers.render() function renders a template to a string. We can manufacture a response object directly, and use that string as the body of the response. Let us change the hello_world() view function as follows − from pyramid.renderers import render def hello_world(request): retval = render(”templates/hello.jinja2”, {”name”:”Tutorialspoint”}, request=request) return Response(retval) Remaining code being same, the browser also shows the same output as above. Rendering via Configuration As mentioned earlier, the content_type of HTTP response returned by Pyramid”s view callable id text/plain. However, it can be altered to string, JSON or JSONP if the renderer parameter of the @view_config decorator is assigned with any of these values. Pyramid thus have following built-in renderers − JSON String JSONP Example In the following example, the hello_world() view function is configured to render JSON response. from pyramid.view import view_config @view_config(route_name=”hello”,renderer=”json”) def hello_world(request): return {”content”:”Hello World!”} Output The setting of renderer type to JSON also sets the content_type header of the HTTP response to application/json. The browser displays the JSON response as in the following figure − The renderer parameter of the @view_config() decorator can be set to a template web page (which must be present in the templates folder). The prerequisite conditions are that the appropriate Python binding of the template library must be installed, and the application configuration must include the binding. We have already installed python_jinja2 package, so that we can use jinja2 template to be rendered by the hello_world() view function, decorated by @view_config() with renderer parameter. The hello.jinja2 template HTML code is as follows − <html> <body> <h1>Hello, {{ name }}!</h1> </body> </html> The decorated hello_world() function is written as − from pyramid.view import view_config @view_config(route_name=”hello”, renderer=”templates/hello.jinja2”) def hello_world(request): return {”name”:”Pyramid!”} Example In this case, the view function returns a dictionary object. It is made available to the template as the context data, that can be inserted in the HTML text with the help of template language syntax elements. The complete code to render a jinja2 template is as follows −

Python Pyramid – Route Prefix

Python Pyramid – Route Prefix ”; Previous Next Many times, similar URL patterns are registered with different routes in more than one Python code modules. For example, we have a student_routes.py where /list and /add URL patterns are registered with ”list” and ”add” routes. The view functions associated with these routes are list() and add(), respectively. #student_routes.py from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config @view_config( route_name=”add”) def add(request): return Response(”add student”) @view_config(route_name=”list”) def list(request): return Response(”Student list”) def students(config): config.add_route(”list”, ”/list”) config.add_route(”add”, ”/add”) config.scan() These routes will eventually be registered when the students() function is called. At the same time, there is book_routes.py, in which the same URLs /list and add/ are registered to ”show” and ”new” routes. Their associated views are list() and add() respectively. The module has books() function which adds the routes. #book_routes.py from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config @view_config( route_name=”new”) def add(request): return Response(”add book”) @view_config(route_name=”show”) def list(request): return Response(”Book list”) def books(config): config.add_route(”show”, ”/list”) config.add_route(”new”, ”/add”) config.scan() Obviously, there is a conflict between URL patterns as ”/list” and ”/add” point to two routes each and this conflict must be resolved. This is done by using the route_prefix parameter of the config.include() method. The first parameter to config.include() is the function which adds the routes, and the second is the route_prefix string which will be prepended to the URL pattern used in the included function. Hence, the statement config.include(students, route_prefix=”/student”) will result in the ”/list” URL pattern changed to ”/student/list” and ”/add” becomes ”student/add”. Similarly, we can add prefix to these URL patterns in the books() function. config.include(books, route_prefix=”/books”) Example The code that starts the server is as below − from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from student_routes import students from book_routes import books if __name__ == ”__main__”: with Configurator() as config: config.include(students, route_prefix=”/student”) config.include(books, route_prefix=”/book”) app = config.make_wsgi_app() server = make_server(”0.0.0.0”, 6543, app) server.serve_forever() Output Let us run the above code and test the routes by following CURL commands. C:UsersAcer>curl localhost:6543/student/list Student list C:UsersAcer>curl localhost:6543/student/add add student C:UsersAcer>curl localhost:6543/book/add add book C:UsersAcer>curl localhost:6543/book/list Book list Print Page Previous Next Advertisements ”;