Python and Pylons and Jinja2

From Wildsong
Revision as of 18:46, 14 August 2018 by Brian Wilson (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

oh my! STOP NOW. Use Flask instead. Go use Flask, do not turn back. Do not use CherryPy either. Do pass go and collect $200. Use Flask.

Pylons Project Pyramid is for writing web applications in Python.

"Jinja2 is a modern and designer friendly templating language for Python, modeled after Django’s templates."

By "templating" they mean embedding python (or code) inside HTML files, like PHP.

Pyramid helps you write WSGI applications, so you are writing in python and it generates the HTML.

Pyramid

First install it and check to see which version it is

sudo pip install pyramid
python
>>> import pkg_resources
>>> pkg_resources.get_distribution("pyramid").version
'1.5a3'

Then create the minimal greeting aka "Hello, world" application.

Standalone

This is straight out of the manual. Pyramid runs its own web server so you save this to a file such as pyramid-hello.py.

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__':
    config = Configurator()
    config.add_route('hello', '/hello/{name}')
    config.add_view(hello_world, route_name='hello')
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

Next you run it, for example "python pyramid-hello.py" On the command line, you see NOTHING. You connect to your computer at port 8080 with a URL like this "http://ip address:8080/hello/brian" and the response comes back in your browser and you get console output in the shell where you started python.

JohnDay.alseageo.com - - [16/Dec/2013 11:39:30] "GET /hello/brian HTTP/1.1" 200 12

That's great, you can run it and test it using a Python IDE such as Komodo. To deploy you will want to run it as a WSGI based application.

Apache

http://docs.pylonsproject.org/projects/pyramid/en/latest/tutorials/modwsgi/index.html

I had trouble with virtualenv because there was no env/bin/pip in my environment. Eventually I found it installed in env/local/bin instead. Sheesh. After that I was able to get going.

virtualenv v_wsgi
source v_wsgi/bin/activate
export PATH=`pwd`/v_wsgi/local/bin:$PATH
pip install pyramid
easy_install paste
pcreate -s starter myapp
cd myapp
python setup.py install
python setup.py develop

Now, press on. Read the manual. Enjoy.