Suddenly I needed to work on a project using Python and Pyramid, so a note of how I'm studying

https://github.com/YukiMiyatake/YukiMiyatakeWorks/tree/prj/Python/Pyramid/main Leave notes on this branch

I had never done the front desk, but suddenly I was in charge of the front desk and the web server I needed to create a new one with Pyramid of Python that I have never used before Leave a note (although now) This is how I work when I first touch a language framework. Realistic language acquisition

First of all, this time I will work by going back and forth between both Windows and Mac PCs I have set up both PCs I made a Docker image for the time being, but basically I will run Python natively Editor is stable VS Code

Environment

miniconda https://docs.conda.io/en/latest/miniconda.html Since anaconda is big, put miniconda The usage is probably the same Install Python 3.7

VSCode Insert the Python plugin Pythoner is in Lint in May, so be sure to put it in Lint It makes me angry with PEP8 without exception. I don't know what PEP8 is

Python grammar

Prior knowledge

Somehow, what I know from other people's stories

I only know this, but I'm optimistic that it will somehow become an atmosphere

Framework comparison

A rough look at Python web framework comparisons

There is not much information on Pyramid ...

https://hotframeworks.com/languages/python Framework ranking

In the top 3 with Django, Flask, Tornado Bottle, AIOHTTP, web.py, Pyramid, web2.py are about the same rate

Pyramid has little Japanese information, so it seems that you have to program with English information ...

Guess while looking at the code on Github

Choose a Python project with a high Star and look at the code My usual style of finding features and searching for things I don't understand

In the above investigation, it is necessary to investigate around the package again. I was able to understand the Python language.

Start development

Project creation

https://trypyramid.com/ https://docs.pylonsproject.org/projects/pyramid/en/latest/ The formula seems to be above

$ pip install pyramid
$ pcreate -s alchemy testapp
$ cd testapp
$ python setup.py develop
$ pserve development.ini

I might use SQL Alchemy (maybe ORM), so I added the alchemy option and created a testapp template. Start the server with the settings of development.ini and access http: // localhost: 6543 Up to this point

Since SQLAlchemy is not set, it is in the browser

Pyramid is having a problem using your SQL database.  The problem
might be caused by one of the following things:

1.  You may need to run the "initialize_testapp_db" script
    to initialize your database tables.  Check your virtual
    environment's "bin" directory for this script and try to run it.

2.  Your database server may not be running.  Check that the
    database server referred to by the "sqlalchemy.url" setting in
    your "development.ini" file is running.

After you fix the problem, please restart the Pyramid application to
try it again.

Is displayed It seems that you need to create a SQLite database to make it work for the time being

$ initialize_testapp_db development.ini

It moved easily

SnapCrab_NoName_2020-1-7_23-27-51_No-00.png

I imagined a yellow desert because it was called Pyramid, but the image color seems to be red.

I will investigate what I care about

pychache is made arbitrarily, so check it

It seems that Python compiles and makes it. Put it in .gitignore and remove it from source control

call You can call an instance different from the constructor with ().

Is it operator () in C ++?

I want to change the extension .jinja2 of view.

Add to config of init in project root

    config.add_jinja2_renderer(".html")

Template separator

In jinja2, {{}} seems to be the default separator

block {% extends "layout.html" %} {% block content %} {% endblock content %} It was a mystery at first, but I found out when I executed it while rewriting the HTML in this jinja2 seems to be able to inherit the template Based on layout.html. It is specified in extends And rewrite the parent block with the child template block It seems that you are creating a page like that

dynamic url I don't know if you call it that {{request.static_url('testapp:static/pyramid.png')}} I was curious about this part. Perhaps render from the framework instead of writing the path directly I think this is the way We will investigate the details of the parameters later. It is a mystery to enter the application name Other instructions are below, so you might use something https://docs.pylonsproject.org/projects/pyramid/en/latest/api/request.html

routing Located in routes.py

def includeme(config):
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')

First of all, I'm curious about include me https://docs.pylonsproject.org/projects/pyramid/en/latest/api/config.html I'm not sure, but at first glance, if there is a function named includeme, Pyramid will call it by default (the function name can be omitted).

The first argument of config.add_route is the name and the second argument is the URL. Match View with the name of the first argument

View views/default.py

@view_config(route_name='home', renderer='../templates/mytemplate.html')
def my_view(request):
    try:
        query = request.dbsession.query(MyModel)
        one = query.filter(MyModel.name == 'one').first()
    except DBAPIError:
        return Response(db_err_msg, content_type='text/plain', status=500)
    return {'one': one, 'project': 'testapp'}

view_config decorator. route_name matches the name of the previous route renderer is a template to render There are other request_method, match_param, etc., and it seems that various cases can be divided. https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/viewconfig.html

The normal system returns an associative array containing one and project. Expected to render the value to mytemplate.html. Hit.

Perhaps if you return the Dictionary it will render in the template If you return it with Response etc., it will be rendered independently without using a template

Remodel and remember

Add View

Create a new page by adding routing, View and Template

POST from form

If I used the form tag, I could simply do it with HTML, but it seems that I should use the form library Deform seems to be used in pyramid https://docs.pylonsproject.org/projects/pyramid/en/latest/quick_tutorial/forms.html

Apparently it seems to be used together with something called colander Create a schema (class) derived from the colander object It seems that the member variable of that class = the item of the form Very convenient

schema


import colander
from deform.widget import TextAreaWidget

class NewPageSchema(colander.MappingSchema):
    username = colander.SchemaNode(colander.String(), title="username",
                                   validator=colander.Length(min=4, min_err='Shorter than minimum length ${min}'),
                                   default="")

In view, create an instance of this schema and create a Form from the schema Just pass it to View Since it's a big deal, make a class by imitating only the sample (I don't know Python at all, but it looks like this)

view



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

    @reify
    def form_(self):
        schema = NewPageSchema()
        btn = deform.form.Button(name="newpage", title="newpage")
        return deform.form.Form(schema, buttons=(btn,), action="/newpage")

    @view_config(route_name='home', renderer='../templates/mytemplate.html')
    def my_view(self):
        form = self.form_.render()
        return {"rendered_form": form}

    @view_config(route_name="newpage", renderer="../templates/newpage.html")
    def newpage(self):
        username = self.request.params.get("username", "")
        return {"username": username}

What is reify ... https://docs.pylonsproject.org/projects/pyramid/en/latest/api/decorator.html

It behaves like a Python property, but once called it saves the value as a Dictionary I wonder what·· Python properties are probably like properties in other languages, like C # Is it a function that can be called without (), or a function that returns a value? However, in the case of reify, it is called on the first call, but after that it seems to return the same value Since the value can be overwritten from the outside, it is a little strange thing different from the singleton

In the above case, return form

The posted parameters can be obtained with request.params.get ("hoge")

For template

{{ rendered_form | safe }}

Then, the form is displayed just by putting the variable of form. I investigated what safe is, but this seems to be a feature of jinja2 Normally jinja2 seems to escape tags at render time to prevent XSS attacks When I actually turned off safe, the escaped HTML was displayed. However, if you add safe, you can write HTML without escaping.

I haven't validated the form yet, but the form is very clear.

Perform Validation

https://docs.pylonsproject.org/projects/deform/en/latest/validation.html Even if I write the code as shown here, I don't know if CSRFSchema can be imported in the first place. There is no colander.Drop I managed to write such code

Actually, since the validator is set in Schema, you can validate it by calling it properly.

Get controls to do validation I haven't followed in detail, but I think it's the content and value of the form

And if you pass controls to validate of the form object, the validator will be checked If NG, ValidationFailure exception will be thrown

This time, if you catch an exception, you are redirected to /. I want to know a better way

        if 'newpage' in self.request.params:
            controls = self.request.POST.items()

            try:
                self.form_.validate(controls)
            except ValidationFailure as e:
                return HTTPFound(location='/')

        username = self.request.params.get("username")
        email = self.request.params.get("email")
        return {"username": username, "email": email }

Up to here for this time. .. .. .. Continue if there is hope

Tag up to the present https://github.com/YukiMiyatake/YukiMiyatakeWorks/tree/pyramid_deform_validation

Recommended Posts

Suddenly I needed to work on a project using Python and Pyramid, so a note of how I'm studying
When I tried to create a project using Python on Docker with PyCharm, it didn't work, but it worked with Docker Compose.
How to build a LAMP environment using Vagrant and VirtulBox Note
I tried to make a regular expression of "amount" using Python
[Python] I tried to implement stable sorting, so make a note
I tried to make a regular expression of "time" using Python
I tried to make a regular expression of "date" using Python
How to build a Python environment using Virtualenv on Ubuntu 18.04 LTS
I did a lot of research on how Python is executed
How to make Python 3.x and 2.x coexist on Mac (I also included opencv as a bonus)
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
[Fabric] I was addicted to using boolean as an argument, so make a note of the countermeasures.
I tried to create a sample to access Salesforce using Python and Bottle
I want to make a web application using React and Python flask
Work memorandum (pymongo) Part 3. I don't want to look it up again, so make a note of it (aggregate)
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
How to build an environment for using multiple versions of Python on Mac
I made a script to record the active window using win32gui of Python
I set up TensowFlow and was addicted to it, so make a note
What to do when matplotlib gets angry on CentOS saying "I'm using Agg so I can't issue a figure"
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
How to build a beautiful Python environment on a new Mac and install Jupter Notebook
I want to take a screenshot of the site on Docker using any font
How to create a Python 3.6.0 environment by putting pyenv on Amazon Linux and Ubuntu
I'm used to php + twig, so I changed the template engine of pyramid 1.5 to jinja2
A Python beginner made a chat bot, so I tried to summarize how to make it.
I tried to summarize how to use matplotlib of python
How to write a list / dictionary type of Python3
I stumbled upon using MoviePy, so make a note
How to build a Django (python) environment on docker
I want to work with a robot in python.
How to make a Python package using VS Code
How to execute a command using subprocess in Python
I tried using Python (3) instead of a scientific calculator
How to build a Python environment on amazon linux 2
Python Note: The mystery of assigning a variable to a variable
How to build a Python virtual execution environment using Visual Studio Code and pipenv on a Windows machine (also Jupyter notebook)
Parallel processing of Python joblib does not work in uWSGI environment. How to process in parallel on uWSGI?
How to start a simple WEB server that can execute cgi of php and python
How to create an instance of a particular class from dict using __new__ () in python
[Python] How to delete rows and columns in a table (list of drop method options)
I want to create a karaoke sound source by separating instruments and vocals using Python
How to know the number of GPUs from python ~ Notes on using multiprocessing with pytorch ~
I made a function to crop the image of python openCV, so please use it.
How to easily draw the structure of a neural network on Google Colaboratory using "convnet-drawer"
I want to make a voice changer using Python and SPTK with reference to a famous site
[Python] How to make a list of character strings character by character
How to build a new python virtual environment on Ubuntu
[python] Summary of how to retrieve lists and dictionary elements
How to shuffle a part of a Python list (at random.shuffle)
I want to start a lot of processes from python
[Python] Summary of how to use split and join functions
I tried "How to get a method decorated in Python"
How to develop in a virtual environment of Python [Memo]
Comparison of how to use higher-order functions in Python 2 and 3
How to register a package on PyPI (as of September 2017)
How to get a list of built-in exceptions in python
I want to know the features of Python and pip
I tried to make a stopwatch using tkinter in python
How to write a metaclass that supports both python2 and python3
I made a Chatbot using LINE Messaging API and Python