An Introduction to Python Web Development Using the Pyramid Framework, Part 7
If you haven't readPart 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 therequest,Response, andSessionobjects. 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 therequestandResponseobjects, followed by how to useSessionobjects 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
Therequestobject 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 therequestobject, 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 thebparameters, then the following code would work:
b = req.GET.getall('b')
Thegetall()method is actually a method of theMultiDictclass and will work on all multi-dictionary instances.
If we want to get all values from the query-string andrequestbody, then thereq.paramsmethod call can be used. If we want to get the entirerequestbody as a string, we could use this:
reqBody = req.Body
There are numerous other methods for therequestobject, such as getting the URL, cookies, and headers information. With Pyramid, you can even get theview_namewithrequest.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 therequestobject, theResponseobject 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 withreponse.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是常见的所有网络语言,他们呢important for carrying variables from one page to the next. Pyramid has aSession factorythat allows you to set up sessions using thesession_factoryargument passed to theConfiguratorclass:
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 likeDictionaryobjects, as they contain all the same methods, along with some additional attributes (properties), such ascreatedandnew.createdis an integer timestamp giving the time the session was created.newis a Boolean attribute indicating whether the session is new.
Logging
Another common component of web-based languages islogging 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 thedevelopment.iniandproduction.inifiles.
To use logging in the application, just use thelogclass:
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. Theget_loggermethod binds the application to the logclassinstance. Upon an error within the classmyview, 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 thepyramid_exclogpackage. 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 therequestandResponseobjects. 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.
TherequestandResponseobjects 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 manageSessionvariables.
Logging is important for keeping an audit of application behavior. Thelog.debugmethod 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.inifiles 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.