Blog: https://ask.hellobi.com/blog/zhiji welcome to communicate and study.

There are many options available in Python Web development frameworks, including *Django, Tornado, Flask, Web2py, Pylons, Pyramid, and many more. We have written Django and Tornado before, but today we will focus on Pyramid, starting with the official documentation.

  • The official documentation
  • English Course:Docs.pylonsproject.org/projects/py…
  • Creating Your First Pyramid Application

#1.Pyramid Pyramid is part of a series of software releases under the Pylons project. ** The website ** describes the relationship between Pyramid and the Pylons Project.

Pyramid is known for its efficient and fast-paced development capabilities. Here’s how the official document describes it: Pyramid is a small, fast, down-to-earth Python web framework. It is developed as part of the Pylons Project. It is licensed under a BSD-like license. This open source Web framework has a platform-independent MVC architecture that provides the easiest way to develop. In addition, it is one of the preferred platforms for developing reusable code efficiently.

##Pyramid and other Web frameworks (translated from Pyramid’s English documentation) A precursor of the first Pyramid version (called repoze. BFG) was created in 2008. In late 2010, we renamed Repoze.BFG to Pyramid and merged it into Pylons in November of that year.

Pyramid was inspired by Zope, Pylons 1.0, and Django, and ultimately, Pyramid borrowed concepts and features from each to form a unique framework.

Pyramid traces many of its features back to Zope. Like Zope applications, Pyramid applications are easy to extend: if you follow certain rules, your application will be reused, improved, restructured, and even extended by third party developers without fork the original program. Traversal and Declarative Security were first introduced in Zope.

Pyramid’s URL Dispatch concept was inspired by the Routes system in Version 1.0 of Pylons, with Pyramid having the same liberal policy as In Version 1.0 of Pylons. It doesn’t specify which database you should use, its built-in templates are just for convenience. In fact, it simply provides a mechanism for mapping urls to view code and rules for invoking those views. You can use third-party components for free to meet the needs of your project.

View, a concept often used by Pyramid, comes from Django. Pyramid’s document style is more like Django than Zope’s.

Like Pylons 1.0, but unlike Zope, a Pyramid application developer can use a single statement command to perform a framework’s usual configuration tasks such as adding a View or route. ZCML has similar functionality in Zope. Pyramid supports ready-to-use command statement configuration and modifiers based configuration; ZCML is used through an extension package pyramd_ZCML.

Unlike Zope or “full-stack” frameworks such as Django, Pyramid makes no assumptions about which persistent mechanism you’ll use to build your application. Zope applications rely on ZODB; Pyramid also allows you to create ZODB programs without relying on the ZODB itself. Also, Django tends to assume that you want to store your application data in a relational database. Pyramid never makes these assumptions; it allows you to use relational databases but does not encourage or discourage decisions.

The other Python Web frameworks declare themselves as class members. The Web Framework is called the Model-View-Controller framework, and Pyramid falls into this category.

## Framework VS library (translated by Pyramid)

The biggest difference between a framework and a library is that the code in the library is called by the code you write, while the framework is called by the code you write. Creating an application using a set of libraries is usually easier at first than using a framework, because you can selectively give up some control to library code that you didn’t write. But when you use a framework, you have to give up most of your control to code that you didn’t write: the entire framework. You don’t have to use a framework to create a WEB application using Python. A wealth of libraries have been developed. In practice, however, using a framework to create an application is more useful than using a series of libraries if the framework provides a list of features that meet your project’s requirements.

#2.Pyramid’s installation website is pretty clear, so follow suit.

  • **ez_setup.py**(save the page as ez_setup.py, remember D; \python directory). CMD go to the D:\python directory and execute
python ez_setup.py 
Copy the code

  • Install virtualenv using Script/easy_install in python:
easy_install virtualenv
Copy the code
  • Create a workspace with VirtualEnv
virtualenv --no-site-packages env
Copy the code
  • After installing PYRAMID, you should have an env file, CD env folder, and execute
easy_install pyramid
Copy the code

# 3. The Pyramid is used

1. Create the first PYRAMID application

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response


def hello_world(request):
    return Response('Hello %(name)s! '%request.matchdict)

if __name__ == '__main__':
    Create an instance config of the Configuration class
    config = Configurator()
    # register a URL route that starts with /hello/. The route name is 'hello'.
    config.add_route('hello'.'/hello/{name}')
    # register a view callable URL Path (e.g. /hello/world)-> route(e.g. 'hello')->view callable(e.g.
    config.add_view(hello_world,route_name='hello')
    # pyramid. Config. Configurator. Make_wsgi_app () method to create WSGI applications
    app = config.make_wsgi_app()
    A WSGI service is started
    server = make_server('0.0.0.0',8080,app)
    The #serve_forever() method creates a loop to accept requests from the outside world
    server.serve_forever()
Copy the code

Open your browser, losing run run into http://localhost:8080/hello/world, will display the “Hello world!” . Now that we have a basic understanding of the sample program, let’s take a step by step look at how it works.

  • The Imports package introduces the Configurator class of the pyramid.config module in line 2, and creates an instance of it in line 10 to configure our application. Like other Python Web frameworks, Pyramid uses the WSGI protocol to link an application to a Web server. The wsGIref module used in the first line is a wrapper around WSGI services, and WSGIRef is now included in the Python standard library. The third row pyramid is introduced. The response. The response, used to return the response information.

  • The View Callable statement Line 6 defines a hello_world function, the incoming request parameters, return to the pyramid. The response. An instance of this class. Enter the matching name path by calling the Matchdict method of the Request object. Because of our visit is http://localhost:8080/hello/world, so match to the world and return to “hello world” string, if you visit HTTP: / / localhost: 8080 / hello/pyramid, then the return would be “hello pyramid!” . This function is called view Callable (you can call it view call, but I prefer English). A view call takes one argument: Request. It will return a Response object. A View callable doesn’t have to be a function. It can also be a class or an instance, but for simplicity we’ll use a function here. A View callable is always accompanied by a call to the Request object. A Request object represents an HTTP request sent to PYRAMID through an activated WSGI server. A View callable also needs to return a Response object. Because a Response object has all the information necessary to formulate an actual HTTP response. This object is converted into text messages sent back to the requesting browser via the WSGI server, or Pyramid. To return a response, each view callable creates an instance of response. In the hello_world function, a string is returned as the body of response.

  • Lines 10-15 are the Application Configuration information. Line 10 creates an instance of the Configuration class config to configure our Pyramid application, including routing, IP, port, and so on. The various methods of Config are called to set up the Application Registry to register our application. What is Application Registry? Here’s the official explanation:

    Line 11 call pyramid. Config. Configurator. Add_route () method, registered a begin with/hello/URL routing, routing is called ‘hello’. In line 12 config.add_v runs ieW (hello_world, route_name=’hello’), registers a view callable (that is, hello_world), This function should be called when a route named ‘hello’ is matched. The mapping is URL Path (e.g. /hello/world)-> route(e.g. ‘hello’)->view callable(e.g. Hello_world). Thus, a foreground page corresponds to a background processing method.WSGI Application Creation Creates a WSGI ApplicationWhen all the configuration after the completion of the work, python scripts by pyramid. Config. Configurator. Make_wsgi_app () method to create WSGI applications. This method returns a WSGI application object and passes it to the APP reference for the WSGI server to use. WSGI is a protocol that allows servers to communicate with Python applications. We won’t go into WSGI here, but if you’re interested, you can go to WSGI’s websitewsgi.orgLearn more.WSGI Application ServingIn the last two lines, we start a WSGI service. The make_server(‘0.0.0.0’,8080,app) method binds the IP and port, and the last argument passes our app object (a Router), which is the application we want to serve. The serve_forever() method creates a loop to accept requests from the outside world.

#4.Pyramid partial syntax

  • Usage: Locals () directly transmits all the variables in the function to the template. Of course, this may pass some extra parameters, which is a bit of a waste of memory.

  • The Render () method is a new shortcut to render_to_response, which automatically uses RequestContext. The latter has to be coded, and that’s the most obvious difference, but of course the former is more concise.

return render_to_response('blog_add.html', {'blog': blog, 
'form': form, 'id': id, 'tag': tag},
context_instance=RequestContext(request))

return render(request, 'blog_add.html', 
{'blog': blog, 'form': form, 'id': id, 'tag': tag})
Copy the code