About Python Pyramid traversal

I tried to touch Python's web framework Pyramid. This article is a memorandum focusing on things that are likely to get caught, such as "Then what to do when actually implementing", omitting the basics of "I installed it www".

Traversal

In addition to the familiar URL dispatch, Pyramid has a URL mapping method called Traversal.

Regarding traversal, only conceptual things are described in the explanation of the original English site, and even if you search the vast net, there are several descriptions, but it seems that the interpretation (?) Is different for each, and the implementation method is Wrong.

However, in order to implement access control, it seems that traversal must be used as in the example of the original site, so as long as you create a website with Pyramid, you can not avoid this.

Traversal concept and Python dictionary

Since the concept of traversal is described in the head family, detailed explanation is omitted, but in simple terms, each element of the URL is regarded as a key value of a nested Python dictionary, and the last remaining key is the view name and the last. This is a URL mapping method in which the element that hits is the context (operation target).

For example, if the URL for editing the user information of the account'testuser'of a site is "http://example.com/account/testuser/edit", in traversal

--Root ['account'] ['testuser'] The element obtained by is a resource --edit is the view name

Will be. The above Root is described for convenience, but it is actually the starting element of traversal, and is a resource generated every time there is a request from the user. There is a fallacy, but http://example.com can be said to be the root resource for this site.

To summarize it properly, it is written as above, but it hits the wall immediately.

Implementation of user accounts using traversal

The above content has already been described (in English) on the original website. If you take the original site as a swallow, the implementation of resources related to user accounts will be as follows.

def site_root_factory(request):
    root = dict()
    root['account'] = dict()
    root['account']['testuser'] = request.dbsession.Query(User).filter(name = 'testuser').first()

As for Atarimae, it cannot be said that it is an implementation. Even if it is a fixed site, it is natural that the user account can be'registered'/'deleted', and it is not always one, for example, what if'foouser' is added?

In other words, if you want to create a traversal and dynamic website, you can't just implement the resource as a Python dictionary and its elements.

Implementation method by resource class

A resource is not just a'dictionary dict ()'`` `, but a class / object that implements the` `__getitem__ method. If this is not written, it will be difficult for beginners. __getitem__What is it? This is proof that you haven't read the python original documentation, so you should read it now.

Using the above example, the element obtained by the key'account'can be implemented as the following `AccountFactory``` class that implements ``` __ getitem__ `.

class AccountResource(object):
    def __init__(self, parent, request, model):
         self.request = request
         self.model = model
         self.parent = parent

    @property
    def __name__(self):
         return self.model.name

    @property
    def __parent__(self):
         return self.parent


class AccountFactory(object):
    def __init__(self, parent, request):
         self.request = request
         self.parent  = parent

    @property
    def __name__(self):
         return 'account'

    @property
    def __parent__(self):
         return self.parent

    def __getitem__(self, key):
         m = self.request.dbsession.Query(User).filter(name = key).first()
         if m: 
             reurn m
         else: 
             raise KeyError(key)


def site_root_factory(request):
    root = dict()
    root['account'] = AccountFactory(root, request)

Now, when `root ['account'] ['testuser']` is called, the getitem method of `` `AccountFactory will be `key ='testuser". Called with'```, the `User``` model will be called as the final context.

To define an edit view that manipulates this context (User model), for example:

@view_config(name='edit', context='User', renderer='editview.jinja2')
def edit(context, request)
    #context is the User model obtained as a result of traversal
    #The process to operate the User model is described below.

For some reason, there was no example of traversal when DB access occurred as in the above example, so it is described here.

Status

There is almost no Japanese literature. I'm guessing.

Even if there is a routine Pyramid installation and "Started!" Article. How about the fact that there is only one thing here in the era when you can install it quickly with pip? I'm wondering what to do with the installation method article as described on the original site.

Recommended Posts

About Python Pyramid traversal
About python slices
About python comprehension
About Python tqdm.
About python, class
About python inheritance
About python, range ()
About python reference
About Python decorators
[Python] About multi-process
About Python for loops
Summary about Python scraping
About function arguments (python)
About Python, for ~ (range)
About Python3 character code
[Python] Memo about errors
About Python development environment
Python: About function arguments
Python, about exception handling
About Python3 ... (Ellipsis object)
[Python] Chapter 01-01 About Python (First Python)
[Python] About standard input
About __all__ in python
[Python] Find out about pip
About Fabric's support for Python 3
About python objects and classes
About Python variables and objects
About the Python module venv
Think about architecture in python
About python beginner's memorandum function
About the ease of Python
About the enumerate function (python)
About various encodings of Python 3
About Python, len () and randint ()
About Perl, Python, PHP, Ruby
A memorandum about Python mock
About Python string comparison operators
About Python and regular expressions
About the features of Python
About "for _ in range ():" in python
About Python and os operations
Python # About reference and copy
About Python sort () and reverse ()
A note about [python] __debug__
Python
[Python] Let's write briefly about comprehensions
About python dict and sorted functions
About dtypes in Python and Cython
[Python] What is @? (About the decorator)
What was surprising about Python classes
About Python pickle (cPickle) and marshal
[Python] About Executor and Future classes
About Python, from and import, as
pyramid
I learned about processes in Python
About the basics list of Python basics
A note about mock (Python mock library)
About building GUI using TKinter of Python
[Python Kivy] About changing the design theme
About the virtual environment of python version 3.7
Memorandum of python beginners About inclusion notation