An Introduction to Python Web Development Using the Pyramid Framework, Part 7
If you haven't read Part 6 of this series, I recommend you do that before continuing with this article. In Part 6, we looked at different types of templates and how to render them.
This article covers the request, Response, and Session objects. These objects are probably among the most important with regard to a Pyramid web application, as they handle the direct HTTP processing for the app. Basic logging is also covered in this article.
We'll start by examing some of the more common methods used with the request and Response objects, followed by how to use Session objects with Pyramid, and wrap up with how to issue logging statements.
Catch Up on All of the Articles in this Python Series
Jesse Smith has written seven articles in this series. Here are the earlier installments:
Request and Response
The request object is actually a wrapper around a dictionary of environment variables such as the query-string parameters, content type, path variables, and more. Once you invoke a method on the request object, a multi-dictionary instance is returned. A multi-dictionary is an ordered dictionary that can have more than one value for a key. An example would be a URL from which we want to obtain the query parameters. If we wanted to get all the values for just the b parameters, then the following code would work:
b = req.GET.getall('b')
The getall() method is actually a method of the MultiDict class and will work on all multi-dictionary instances.
If we want to get all values from the query-string and request body, then the req.params method call can be used. If we want to get the entire request body as a string, we could use this:
reqBody = req.Body
There are numerous other methods for the request object, such as getting the URL, cookies, and headers information. With Pyramid, you can even get the view_name with request.view_name.
You can also change the type of request content you want to access. For example, if you're working with JSON, you can return the body of a JSON request with this code:
jsonRequest = request.json_body
As with the request object, the Response object also provides details about data packet information. You can get the content-type this way:
responseContentType = response.content_type
Or you may want to get the status with reponse.status. You can also set page caching to expire within a certain amount of time:
response.cache_expires(seconds=0)
You can even change the type of response you want to receive. For example, if you're working with JSON, you can return the body of a JSON response with this code:
jsonBody = response.json
Sessions
Sessions are common to all web-based languages, and they're important for carrying variables from one page to the next. Pyramid has a Session factory that allows you to set up sessions using the session_factory argument passed to the Configurator class:
from pyramid.session import UnencryptedCookieSessionFactoryConfig my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet') from pyramid.config import Configurator config = Configurator(session_factory = my_session_factory)
The code above sets up an unencrypted session factory configuration for the application.
Because Pyramid uses cookies to store session information, this means the cookie will not be encrypted. If this were sensitive user credentials, encryption would be a good choice.
Once the session factory has been set up, you can start creating and using session variables, similarly to that of other languages:
from pyramid.response import Response def myview(request): session = request.session session['username'] = 'Ted' session['gender'] = 'Male'
Session objects in Pyramid can be used like Dictionary objects, as they contain all the same methods, along with some additional attributes (properties), such as created and new. created is an integer timestamp giving the time the session was created. new is a Boolean attribute indicating whether the session is new.
Logging
Another common component of web-based languages is logging objects. Logging can be helpful in keeping track of what's going on with the application in certain situations. Logging environment variables for initializing logging are stored in the development.ini and production.ini files.
To use logging in the application, just use the log class:
import logging log = logging.getLogger(__name__) def myview(request): content_type = 'text/plain' content = 'Hello World!' log.debug('Returning: %s (content-type: %s)', content, content_type) request.response.content_type = content_type return request.response
In this example, the __name__ attribute refers to the module's fully qualified path name. The get_logger method binds the application to the log class instance. Upon an error within the class myview, for example, the following will be printed to the console:
16:20:20,440 DEBUG [MyProject.views] Returning: Hello World! (content-type: text/plain)
You can also log exceptions, but that's beyond the scope of this article. To log exceptions, you need to install the pyramid_exclog package. This add-on is handy if there's an exception, because the add-on will send the URL, exception type, and trace information back to the Python logger.
Conclusion
In this article, you learned more about the request and Response objects. These objects are important for extracting data-packet information such as the header attributes or the content type. Pyramid also has some methods for capturing JSON content of a request or response.
The request and Response objects tend to get used often; numerous less-common methods aren't covered in this article.
Sessions are "convenience" objects. They allow the application to maintain a set of session variables that are accessible from any page of the application. They can be used in both the presentation and business layers of the application. With Pyramid, setting up a session factory for the application is simple, and once it's set up, you can easily create and manage Session variables.
Logging is important for keeping an audit of application behavior. The log.debug method allows you to pass in the string to print to the console or a logging file. Logging has environment variables in the application's setup .ini files that determine how the logger class will behave.
In a later article, I'll cover the security objects offered by the Pyramid framework for securing the application.
This concludes my seven-part series on the Pyramid framework. I hope you learned as much as I did about using the framework for web-based Python applications.