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
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
Somehow, what I know from other people's stories
I only know this, but I'm optimistic that it will somehow become an atmosphere
A rough look at Python web framework comparisons
Django Full stack framework A lot of information on the Web First choice in Python web framework
Bottle WSGI Lightweight framework
Flask WSGI Lightweight framework
Tornado Non-blocking I / O
Plone
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 ...
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
def
and end with :. C-style prototype declaration. No return value or type specified" ""
~ "" "
`. Apparently indentation is important. It seems that triple quotes are not comments, but string literals!* arg
seems to be a variadic argument without keywords** kwargs
seems to be variadic with keywordsclass
syntax and seems to be mostly object-oriented.__init__
method seems to act as a constructorthis
pointer, with self
as the first argument.class
withclass name ()
@ xxx
. Called a decorator@ classmethod
, which can literally specify a function as a class method.__Init __. Py
Difficult. Initialize the package, etc. If you do not create an empty file, it will not load normally. Let's dig deep in the futureIn the above investigation, it is necessary to investigate around the package again. I was able to understand the Python language.
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
I imagined a yellow desert because it was called Pyramid, but the image color seems to be red.
It seems that Python compiles and makes it. Put it in .gitignore and remove it from source control
Is it operator () in C ++?
Add to config of init in project root
config.add_jinja2_renderer(".html")
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
Create a new page by adding routing, View and Template
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.
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