SlideShare a Scribd company logo
1 of 59
WEB APPLICATIONS ON PYTHON3
AND PYTHON2 WITH TURBOGEARS
Alessandro Molina
@__amol__
amol@turbogears.org
Who am I
● CTO @ Axant.it mostly Python company
(with some iOS and Android)
● TurboGears2 development team member
● MongoDB fan and Ming ODM contributor
● Skeptic developer always looking for a
better solution
What's going to come
● Side by Side Python2 and Python3
● TurboGears on both
● ObjectDispatch, serving our pages
● Template Engines
● Gearbox toolkit
● What Python2 has that Python3 doesn't:
authentication, widgets, i18n, admin
What you think your web app is
What your web app is for real
Some missing pieces
● Not all underlying pieces are available on
Python3, yet
● Know when you need to stick to Python2, it
will save you a lot of problems
● Think of moving to Python3 sooner than
later, it will save you a lot of problems
● Python3 is a better Python, for real!
Why TurboGears
● Full stack framework, most of the features
are builtin and available both on Py2 and
Py3
● Minimal mode, really fast and simple for
API servers and small apps
● Non opinionated, use your favourite
template engine or database
Multiple Python Environments
● pythonbrew: a Python installation manager
○ Might want to try pythonz, fork of pythonbrew
● Have your Python2.x and 3.x installations
side by side
● Start with Python3.2 at least, most libraries
have been ported only to python 3.2 and
newer.
Installing PythonBrew
● Download & Install Pythonbrew:
○ curl -kL http://xrl.us/pythonbrewinstall | bash
● Enabled it in your .bashrc
○ source $HOME/.pythonbrew/etc/bashrc
● List installed interpreters:
○ $ pythonbrew list
● Install Python 3.3
○ $ pythonbrew install 3.3.0
Setup Python2 environment
● Create an environment for your Python2
webapp:
○ $ virtualenv --distribute --no-site-packages py2
● Depending on your virtualenv version and
system --distribute and --no-site-
packages might be the default.
Our Python3 environment
● Switch to Python3
○ $ pythonbrew use Python-3.3.0
● Install virtualenv:
○ $ pip install virtualenv
● Create Python3 environment:
○ $ virtualenv py3
● Recover your standard Python:
○ $ pythonbrew off
Switch env not interpreter
● Work with Python2
○ $ source py2/bin/activate
● Work with Python3
○ $ source py3/bin/activate
● Quit current active environment
○ $ deactivate
Installing TurboGears2
● Enable Python3
○ $ source py3/bin/activate
● Install tg.devtools
○ $ pip install -f http://tg.gy/230 tg.devtools
● You should get TurboGears2-2.3.0b2
● Documentation
○ http://turbogears.readthedocs.org/en/tg2.3.0b2/
○ Don't forget version and trailing slash!
Out first Python3 app
● edit app.py
● TurboGears minimal mode, much like
microframeworks
from wsgiref.simple_server import make_server
from tg import expose, TGController, AppConfig
class RootController(TGController):
@expose()
def index(self):
return "<h1>Hello World</h1>"
config = AppConfig(minimal=True, root_controller=RootController())
print("Serving on port 8080...")
httpd = make_server('', 8080, config.make_wsgi_app())
httpd.serve_forever()
Object Dispatch
● Routing happens on your controller
method names and parameters
● Regular expressions can get messy, never
write one anymore
○ unless your need it: tgext.routes
● Easy to get to the controller that handles
an url just by looking at the url
Object Dispatch
URL CONTROLLER
/index RootController.index
/ RootController.index
/blog/3 BlogEntryController.index
(post = 3)
/blog/update?post=3 BlogEntryController.update
(post = 3)
/about RootController.about
/more/1/2/3 RootController.more
(args[0]=1, args[1]=2, args[3]=3)
/more?data=5 RootController.more
(kw['data']=5)
class BlogEntryController
(BaseController):
@expose()
def index(self, post):
return 'HI'
@expose()
def edit(self, post):
return 'HI'
@expose()
def update(self, post):
return 'HI'
class RootController(BaseController):
blog = BlogEntryController()
@expose()
def index(self):
return 'HI'
@expose()
def about(self):
return 'HI'
@expose()
def more(self, *args, **kw):
return 'HI'
Template Engine agnostic
● Doesn't enforce any template language
bound to your controllers
● Genshi, Jinja, Mako and Kajiki officially
supported
● Genshi is strongly suggested due to the
need of a lingua franca for puggable
applications
Templates out of the box
TYPE NAME URL
Markup + Streamed Genshi http://genshi.edgewall.org/
Text + Compiled Mako http://www.makotemplates.org/
Text + Compiled Jinja http://http://jinja.pocoo.org/
Markup + Compiled Kajiki http://kajiki.pythonisito.com/
Add a Template
● Install Genshi:
○ $ pip install genshi
● Register it as a renderer available to the
framework:
○ base_config.renderers = ['genshi']
● Expose it in controllers:
○ @expose('template.html')
Hello Template
from wsgiref.simple_server import make_server
from tg import expose, TGController, AppConfig
class RootController(TGController):
@expose('index.html')
def index(self):
return dict()
config = AppConfig(minimal=True,
root_controller=RootController())
config.renderers = ['genshi']
print("Serving on port 8080...")
httpd = make_server('', 8080, config.make_wsgi_app())
httpd.serve_forever()
<html xmlns="http://www.w5.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/">
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
● index should now expose index.html
template and return dict()
Hello $user
from wsgiref.simple_server import make_server
from tg import expose, TGController, AppConfig
class RootController(TGController):
@expose('index.html')
def index(self):
return dict(user='World')
config = AppConfig(minimal=True,
root_controller=RootController())
config.renderers = ['genshi']
print("Serving on port 8080...")
httpd = make_server('', 8080, config.make_wsgi_app())
httpd.serve_forever()
<html xmlns="http://www.w5.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/">
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello ${user}</h1>
</body>
</html>
● Every entry in the returned dictionary will
be available inside the exposed template
as a variable
from request import data
from wsgiref.simple_server import make_server
from tg import expose, TGController, AppConfig
class RootController(TGController):
@expose('index.html')
def index(self, user='World', **kw):
return dict(user=user)
config = AppConfig(minimal=True, root_controller=RootController())
config.renderers = ['genshi']
print("Serving on port 8080...")
httpd = make_server('', 8080, config.make_wsgi_app())
httpd.serve_forever()
● All arguments available in your URL will be
passed as method parameters
Going Full Stack
● TurboGears minimal
mode provides a quick
way to be productive.
● Full stack mode
provides an already
configured environment
and more features
What is Full Stack
● ORM and Transaction Manager
● Authentication and Identification
● Interactive Debugger and Error Reporting
● PasteDeploy compatible configuration
● Static Files
● Session and Caching
● Widgets and Admin (on Python2)
Creating a Full Stack application
● Full stack applications are created through
the gearbox toolkit
○ $ gearbox quickstart --skip-tw myapp
○ --skip-tw is required due to forms generation
library not being available on Python3 yet.
● Full stack applications are packages: can
be installed and updated to deploy
What's inside
Install the quickstarted app
● To use the app you need to install it:
○ $ pip install -e .
● Installing also brings in dependencies the
app requires
● Now run your application
○ $ gearbox serve --reload
A lot is there now
● Point your browser to http://localhost:
8080 and see TurboGears in action
● Quite a lot is there now!
● Have a look around
● App pages explain the app
itself
Authentication
● Click the login link in the upper-right
corner
○ username: manager
○ password: managepass
● Crash!
● Database has not been initialized
○ You now know what the interactive debugger
looks like!
Authentication, #2 try
● Create database and basic entities
○ $ gearbox setup-app
○ By default sqlite: devdata.db
● Click the login link in the upper-right
corner
○ username: manager
○ password: managepass
● Woah! Welcome back manager!
Authorization
● Go to http://localhost:8080/secc
○ Secure controller here
● Logout
● Go to http://localhost:8080/secc
○ Only for people with "manage" permission
Users and Permissions
● Default users are created in the application
setup script (setup-app)
○ Have a look at websetup/bootstrap.py
● Default models are provided by the
quickstart command for User, Group and
Permission
○ Have a look at models/auth.py
Predicates and Authorization
● Turbogears checks for authorization
requiring predicates bound to controllers
or methods
● http://turbogears.readthedocs.
org/en/tg2.3.0
@expose('prova.templates.index')
@require(predicates.has_permission('manage', msg=l_('Only for
managers')))
def manage_permission_only(self, **kw):
"""Illustrate how a page for managers only works."""
return dict(page='managers stuff')
Database
Accessing Models
● TurboGears relies on SQLAlchemy for SQL
based databases and on Ming for
MongoDB databases
○ Both are first citizens of the TurboGears Admin
○ Both are supported out of the box
○ Run quickstart --ming to have MongoDB support
○ Run quickstart --nosa to disable database at all
○ gearbox help quickstart
Accessing Models
● TurboGears relies on SQLAlchemy for SQL
based databases and on Ming for
MongoDB databases
○ Both are first citizens of the TurboGears Admin
○ Both are supported out of the box
○ Run quickstart --ming to have MongoDB support
○ Run quickstart --nosa to disable database at all
○ gearbox help quickstart
Create, Read, Update, Delete
● Create
○ DBSession.add(Page(name='index'))
● Read
○ page = DBSession.query(Page).filter_by(name='index').one()
● Update
○ page.data = 'This is an empty page'
● Delete
○ DBSession.delete(page)
Wiki20 Tutorial
● TurboGears documentation provides a
great Wiki in 20 minutes Tutorial
○ http://turbogears.readthedocs.org/en/tg2.3.0
b2/turbogears/wiki20.html#wiki-model
● Just skip up to the Wiki Model section, we
already know the previous parts
Let's play with it!
Python3 no more
Back to Python2
● This is as far as you can get using Python3
● Some features not available there
○ i18n utilities
○ Widgets
○ MongoDB
○ TurboGears Admin
Moving to Widgets and Forms
● Doing forms is a tedious task
● Validating data users write is a mess
● Let's use widgets and forms
○ Generates HTML for us
○ Validates input
○ Keeps track of values in case of errors
○ Reports errors to users
Enable forms
● Switch back to Python2
○ $ source py2/bin/activate
● Enable forms in your project
○ edit config/app_cfg.py
○ base_config.use_toscawidgets2 = True
● Install
○ Add tw2.forms to setup.py install_requires
○ pip install -e .
Writing Widgets and Validation
from tg import validate
import tw2.core as twc
import tw2.forms as twf
class PageForm(twf.TableForm):
pagename = twf.HiddenField(validator=twc.Validator(required=True))
data = twf.TextArea(validator=twc.Validator(required=True))
action = lurl('/save')
class RootController(BaseController):
@expose()
@validate(PageForm, error_handler=edit)
def save(self, pagename, data):
page = DBSession.query(Page).filter_by(pagename=pagename).one()
page.data = data
flash("Page successfully updated!")
return redirect("/" + pagename)
Let's translate
● TurboGears detects language of the user
and translates text in templates and
controllers accordigly
● Translation itself is available on both
Python2 and Python3
● String collection is only available on
Python2
Collect text
● Install Babel
○ $ pip install babel
● Template content is automatically
collected and translated
● Text in controllers must be wrapped with
l_() or _() to make them translatable
● Wrap your flash messages
Perform collection
● Walkthrough on i18n
○ http://turbogears.readthedocs.org/en/tg2.3.0
b2/turbogears/i18n.html
● Utility commands
○ python setup.py extract_messages
○ python setup.py init_catalog -l it
○ poedit i18n/it/LC_MESSAGES/myproj.po
○ python setup.py compile_catalog
TurboGears Admin
● A lot of effort has been spent in
○ writing forms
○ validating data
○ editing pages
● Still a lot to do
○ How do I delete a page?
○ How do I search for a page?
Admin does that for you
Enabling the Admin
● Automatically done if you quickstarted
without --skip-tw option
● Enable manually as we started on Py3
○ $ pip install tgext.admin
○ Add admin controller
from tgext.admin.tgadminconfig import TGAdminConfig
from tgext.admin.controller import AdminController
class RootController(BaseController):
admin = AdminController(model, DBSession, config_type=TGAdminConfig)
Rapid Prototyping
● TurboGears admin is based on tgext.crud,
a powerfull rapid prototyping tool
● Have a look at the admin tutorial
○ http://turbogears.readthedocs.org/en/tg2.3.0
b2/turbogears/wikier/index.html
● Avoid pushing the admin too far
○ Custom solutions are cleaner than a too much
customized admin
Admin is great for REST
● REST api for free
● For real, try to put .json after your pages list
○ /admin/pages.json
● Supports a full featured REST api
○ Meaningful error codes
○ Conditional PUT
● You might want to use tgext.crud directly
to build rest services
Look for ready made plugins
● tgext.pluggable enables pluggable
applications
● The cogbin is a collection of existing
extensions and pluggable apps
○ http://turbogears.org/cogbin.html
● Features like Facebook auth, blogging,
registration and so on available on cogbin
The DebugBar
● Great plugin available is the DebugBar
○ pip install tgext.pluggable
○ pip install tgext.debugbar
● Enable debugbar
○ config/app_cfg.py
○ from tgext.pluggable import plug
○ plug(base_config, 'tgext.debugbar')
DebugBar in action
Going Mongo with Ming
Want to support MongoDB
● Try passing --ming to gearbox quickstart
● Full featured admin and tgext.crud as on
SQLAlchemy
● Ming ODM has similar syntax
● Ming provides Unit of Work pattern like
SQLAlchemy
○ transaction manager missing, pay attention
Want to support MongoDB
● Full featured admin and tgext.crud as on
SQLAlchemy
● DebugBar works also with Ming
○ now with cool hightlighting of map-reduce
javascript code too!
Questions?

More Related Content

What's hot

Ratpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web AppsRatpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web AppsJames Williams
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using PythonAyun Park
 
Ninja Build: Simple Guide for Beginners
Ninja Build: Simple Guide for BeginnersNinja Build: Simple Guide for Beginners
Ninja Build: Simple Guide for BeginnersChang W. Doh
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC FrameworkBala Kumar
 
Capistrano deploy Magento project in an efficient way
Capistrano deploy Magento project in an efficient wayCapistrano deploy Magento project in an efficient way
Capistrano deploy Magento project in an efficient waySylvain Rayé
 
Bootify your spring application
Bootify your spring applicationBootify your spring application
Bootify your spring applicationJimmy Lu
 
Instrumentación de entrega continua con Gitlab
Instrumentación de entrega continua con GitlabInstrumentación de entrega continua con Gitlab
Instrumentación de entrega continua con GitlabSoftware Guru
 
Laravel 4 package development
Laravel 4 package developmentLaravel 4 package development
Laravel 4 package developmentTihomir Opačić
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is DockerNick Belhomme
 
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南Shengyou Fan
 
An intro to the JAMStack and Eleventy
An intro to the JAMStack and EleventyAn intro to the JAMStack and Eleventy
An intro to the JAMStack and EleventyLuciano Mammino
 
PyCon Korea - Real World Graphene
PyCon Korea - Real World GraphenePyCon Korea - Real World Graphene
PyCon Korea - Real World GrapheneMarcin Gębala
 
JLPDevs - Optimization Tooling for Modern Web App Development
JLPDevs - Optimization Tooling for Modern Web App DevelopmentJLPDevs - Optimization Tooling for Modern Web App Development
JLPDevs - Optimization Tooling for Modern Web App DevelopmentJLP Community
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django ArchitectureRami Sayar
 
Bgoug 2019.11 test your pl sql - not your patience
Bgoug 2019.11   test your pl sql - not your patienceBgoug 2019.11   test your pl sql - not your patience
Bgoug 2019.11 test your pl sql - not your patienceJacek Gebal
 
Composer & Drupal
Composer & DrupalComposer & Drupal
Composer & Drupaldrubb
 

What's hot (20)

Ratpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web AppsRatpack - Classy and Compact Groovy Web Apps
Ratpack - Classy and Compact Groovy Web Apps
 
Maven 3.0 at Øredev
Maven 3.0 at ØredevMaven 3.0 at Øredev
Maven 3.0 at Øredev
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 
Ninja Build: Simple Guide for Beginners
Ninja Build: Simple Guide for BeginnersNinja Build: Simple Guide for Beginners
Ninja Build: Simple Guide for Beginners
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
Capistrano deploy Magento project in an efficient way
Capistrano deploy Magento project in an efficient wayCapistrano deploy Magento project in an efficient way
Capistrano deploy Magento project in an efficient way
 
Bootify your spring application
Bootify your spring applicationBootify your spring application
Bootify your spring application
 
Take a Stroll in the Bazaar
Take a Stroll in the BazaarTake a Stroll in the Bazaar
Take a Stroll in the Bazaar
 
Instrumentación de entrega continua con Gitlab
Instrumentación de entrega continua con GitlabInstrumentación de entrega continua con Gitlab
Instrumentación de entrega continua con Gitlab
 
Laravel 4 package development
Laravel 4 package developmentLaravel 4 package development
Laravel 4 package development
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is Docker
 
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
 
An intro to the JAMStack and Eleventy
An intro to the JAMStack and EleventyAn intro to the JAMStack and Eleventy
An intro to the JAMStack and Eleventy
 
PyCon Korea - Real World Graphene
PyCon Korea - Real World GraphenePyCon Korea - Real World Graphene
PyCon Korea - Real World Graphene
 
JLPDevs - Optimization Tooling for Modern Web App Development
JLPDevs - Optimization Tooling for Modern Web App DevelopmentJLPDevs - Optimization Tooling for Modern Web App Development
JLPDevs - Optimization Tooling for Modern Web App Development
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django Architecture
 
Bgoug 2019.11 test your pl sql - not your patience
Bgoug 2019.11   test your pl sql - not your patienceBgoug 2019.11   test your pl sql - not your patience
Bgoug 2019.11 test your pl sql - not your patience
 
Composer & Drupal
Composer & DrupalComposer & Drupal
Composer & Drupal
 

Similar to EuroPython 2013 - Python3 TurboGears Training

Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Pantheon
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with pythonroskakori
 
.NET @ apache.org
 .NET @ apache.org .NET @ apache.org
.NET @ apache.orgTed Husted
 
Creating Extensible Plugins for WordPress
Creating Extensible Plugins for WordPressCreating Extensible Plugins for WordPress
Creating Extensible Plugins for WordPressHristo Chakarov
 
202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUPRonald Hsu
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and MaintenanceJazkarta, Inc.
 
Sphinx + robot framework = documentation as result of functional testing
Sphinx + robot framework = documentation as result of functional testingSphinx + robot framework = documentation as result of functional testing
Sphinx + robot framework = documentation as result of functional testingplewicki
 
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...Alessandro Molina
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsGraham Dumpleton
 
Improving Operations Efficiency with Puppet
Improving Operations Efficiency with PuppetImproving Operations Efficiency with Puppet
Improving Operations Efficiency with PuppetNicolas Brousse
 
Where's the source, Luke? : How to find and debug the code behind Plone
Where's the source, Luke? : How to find and debug the code behind PloneWhere's the source, Luke? : How to find and debug the code behind Plone
Where's the source, Luke? : How to find and debug the code behind PloneVincenzo Barone
 
OpenShift Origin Community Day (Boston) Extending OpenShift Origin: Build You...
OpenShift Origin Community Day (Boston) Extending OpenShift Origin: Build You...OpenShift Origin Community Day (Boston) Extending OpenShift Origin: Build You...
OpenShift Origin Community Day (Boston) Extending OpenShift Origin: Build You...OpenShift Origin
 
OpenShift Origin Community Day (Boston) Writing Cartridges V2 by Jhon Honce
OpenShift Origin Community Day (Boston) Writing Cartridges V2 by Jhon Honce OpenShift Origin Community Day (Boston) Writing Cartridges V2 by Jhon Honce
OpenShift Origin Community Day (Boston) Writing Cartridges V2 by Jhon Honce Diane Mueller
 
Angular.js for beginners
Angular.js for beginners Angular.js for beginners
Angular.js for beginners Basia Madej
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...Alessandro Molina
 
WordPress Plugin Development 201
WordPress Plugin Development 201WordPress Plugin Development 201
WordPress Plugin Development 201ylefebvre
 
Getting started with MariaDB and Python
Getting started with MariaDB and PythonGetting started with MariaDB and Python
Getting started with MariaDB and PythonMariaDB plc
 

Similar to EuroPython 2013 - Python3 TurboGears Training (20)

Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
Creating a Smooth Development Workflow for High-Quality Modular Open-Source P...
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with python
 
Django by rj
Django by rjDjango by rj
Django by rj
 
.NET @ apache.org
 .NET @ apache.org .NET @ apache.org
.NET @ apache.org
 
Creating Extensible Plugins for WordPress
Creating Extensible Plugins for WordPressCreating Extensible Plugins for WordPress
Creating Extensible Plugins for WordPress
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
 
Sphinx + robot framework = documentation as result of functional testing
Sphinx + robot framework = documentation as result of functional testingSphinx + robot framework = documentation as result of functional testing
Sphinx + robot framework = documentation as result of functional testing
 
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
Improving Operations Efficiency with Puppet
Improving Operations Efficiency with PuppetImproving Operations Efficiency with Puppet
Improving Operations Efficiency with Puppet
 
Where's the source, Luke? : How to find and debug the code behind Plone
Where's the source, Luke? : How to find and debug the code behind PloneWhere's the source, Luke? : How to find and debug the code behind Plone
Where's the source, Luke? : How to find and debug the code behind Plone
 
OpenShift Origin Community Day (Boston) Extending OpenShift Origin: Build You...
OpenShift Origin Community Day (Boston) Extending OpenShift Origin: Build You...OpenShift Origin Community Day (Boston) Extending OpenShift Origin: Build You...
OpenShift Origin Community Day (Boston) Extending OpenShift Origin: Build You...
 
OpenShift Origin Community Day (Boston) Writing Cartridges V2 by Jhon Honce
OpenShift Origin Community Day (Boston) Writing Cartridges V2 by Jhon Honce OpenShift Origin Community Day (Boston) Writing Cartridges V2 by Jhon Honce
OpenShift Origin Community Day (Boston) Writing Cartridges V2 by Jhon Honce
 
I18n of java script
I18n of java scriptI18n of java script
I18n of java script
 
Angular.js for beginners
Angular.js for beginners Angular.js for beginners
Angular.js for beginners
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
 
WordPress Plugin Development 201
WordPress Plugin Development 201WordPress Plugin Development 201
WordPress Plugin Development 201
 
Getting started with MariaDB and Python
Getting started with MariaDB and PythonGetting started with MariaDB and Python
Getting started with MariaDB and Python
 

More from Alessandro Molina

PyCon Ireland 2022 - PyArrow full stack.pdf
PyCon Ireland 2022 - PyArrow full stack.pdfPyCon Ireland 2022 - PyArrow full stack.pdf
PyCon Ireland 2022 - PyArrow full stack.pdfAlessandro Molina
 
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsEP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsAlessandro Molina
 
EuroPython 2015 - Storing files for the web is not as straightforward as you ...
EuroPython 2015 - Storing files for the web is not as straightforward as you ...EuroPython 2015 - Storing files for the web is not as straightforward as you ...
EuroPython 2015 - Storing files for the web is not as straightforward as you ...Alessandro Molina
 
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESAlessandro Molina
 
PyConIT6 - Messing up with pymongo for fun and profit
PyConIT6 - Messing up with pymongo for fun and profitPyConIT6 - Messing up with pymongo for fun and profit
PyConIT6 - Messing up with pymongo for fun and profitAlessandro Molina
 
PyConFR 2014 - DEPOT, Story of a file.write() gone wrong
PyConFR 2014 - DEPOT, Story of a file.write() gone wrongPyConFR 2014 - DEPOT, Story of a file.write() gone wrong
PyConFR 2014 - DEPOT, Story of a file.write() gone wrongAlessandro Molina
 
PyConUK 2014 - PostMortem Debugging and Web Development Updated
PyConUK 2014 - PostMortem Debugging and Web Development UpdatedPyConUK 2014 - PostMortem Debugging and Web Development Updated
PyConUK 2014 - PostMortem Debugging and Web Development UpdatedAlessandro Molina
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Alessandro Molina
 
Post-Mortem Debugging and Web Development
Post-Mortem Debugging and Web DevelopmentPost-Mortem Debugging and Web Development
Post-Mortem Debugging and Web DevelopmentAlessandro Molina
 
MongoTorino 2013 - BSON Mad Science for fun and profit
MongoTorino 2013 - BSON Mad Science for fun and profitMongoTorino 2013 - BSON Mad Science for fun and profit
MongoTorino 2013 - BSON Mad Science for fun and profitAlessandro Molina
 
PyConUK2013 - Validated documents on MongoDB with Ming
PyConUK2013 - Validated documents on MongoDB with MingPyConUK2013 - Validated documents on MongoDB with Ming
PyConUK2013 - Validated documents on MongoDB with MingAlessandro Molina
 
PyGrunn2013 High Performance Web Applications with TurboGears
PyGrunn2013  High Performance Web Applications with TurboGearsPyGrunn2013  High Performance Web Applications with TurboGears
PyGrunn2013 High Performance Web Applications with TurboGearsAlessandro Molina
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Alessandro Molina
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
From SQLAlchemy to Ming with TurboGears2
From SQLAlchemy to Ming with TurboGears2From SQLAlchemy to Ming with TurboGears2
From SQLAlchemy to Ming with TurboGears2Alessandro Molina
 

More from Alessandro Molina (15)

PyCon Ireland 2022 - PyArrow full stack.pdf
PyCon Ireland 2022 - PyArrow full stack.pdfPyCon Ireland 2022 - PyArrow full stack.pdf
PyCon Ireland 2022 - PyArrow full stack.pdf
 
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsEP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
 
EuroPython 2015 - Storing files for the web is not as straightforward as you ...
EuroPython 2015 - Storing files for the web is not as straightforward as you ...EuroPython 2015 - Storing files for the web is not as straightforward as you ...
EuroPython 2015 - Storing files for the web is not as straightforward as you ...
 
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
 
PyConIT6 - Messing up with pymongo for fun and profit
PyConIT6 - Messing up with pymongo for fun and profitPyConIT6 - Messing up with pymongo for fun and profit
PyConIT6 - Messing up with pymongo for fun and profit
 
PyConFR 2014 - DEPOT, Story of a file.write() gone wrong
PyConFR 2014 - DEPOT, Story of a file.write() gone wrongPyConFR 2014 - DEPOT, Story of a file.write() gone wrong
PyConFR 2014 - DEPOT, Story of a file.write() gone wrong
 
PyConUK 2014 - PostMortem Debugging and Web Development Updated
PyConUK 2014 - PostMortem Debugging and Web Development UpdatedPyConUK 2014 - PostMortem Debugging and Web Development Updated
PyConUK 2014 - PostMortem Debugging and Web Development Updated
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2
 
Post-Mortem Debugging and Web Development
Post-Mortem Debugging and Web DevelopmentPost-Mortem Debugging and Web Development
Post-Mortem Debugging and Web Development
 
MongoTorino 2013 - BSON Mad Science for fun and profit
MongoTorino 2013 - BSON Mad Science for fun and profitMongoTorino 2013 - BSON Mad Science for fun and profit
MongoTorino 2013 - BSON Mad Science for fun and profit
 
PyConUK2013 - Validated documents on MongoDB with Ming
PyConUK2013 - Validated documents on MongoDB with MingPyConUK2013 - Validated documents on MongoDB with Ming
PyConUK2013 - Validated documents on MongoDB with Ming
 
PyGrunn2013 High Performance Web Applications with TurboGears
PyGrunn2013  High Performance Web Applications with TurboGearsPyGrunn2013  High Performance Web Applications with TurboGears
PyGrunn2013 High Performance Web Applications with TurboGears
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
From SQLAlchemy to Ming with TurboGears2
From SQLAlchemy to Ming with TurboGears2From SQLAlchemy to Ming with TurboGears2
From SQLAlchemy to Ming with TurboGears2
 

Recently uploaded

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 

Recently uploaded (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 

EuroPython 2013 - Python3 TurboGears Training

  • 1. WEB APPLICATIONS ON PYTHON3 AND PYTHON2 WITH TURBOGEARS Alessandro Molina @__amol__ amol@turbogears.org
  • 2. Who am I ● CTO @ Axant.it mostly Python company (with some iOS and Android) ● TurboGears2 development team member ● MongoDB fan and Ming ODM contributor ● Skeptic developer always looking for a better solution
  • 3. What's going to come ● Side by Side Python2 and Python3 ● TurboGears on both ● ObjectDispatch, serving our pages ● Template Engines ● Gearbox toolkit ● What Python2 has that Python3 doesn't: authentication, widgets, i18n, admin
  • 4. What you think your web app is
  • 5. What your web app is for real
  • 6. Some missing pieces ● Not all underlying pieces are available on Python3, yet ● Know when you need to stick to Python2, it will save you a lot of problems ● Think of moving to Python3 sooner than later, it will save you a lot of problems ● Python3 is a better Python, for real!
  • 7. Why TurboGears ● Full stack framework, most of the features are builtin and available both on Py2 and Py3 ● Minimal mode, really fast and simple for API servers and small apps ● Non opinionated, use your favourite template engine or database
  • 8. Multiple Python Environments ● pythonbrew: a Python installation manager ○ Might want to try pythonz, fork of pythonbrew ● Have your Python2.x and 3.x installations side by side ● Start with Python3.2 at least, most libraries have been ported only to python 3.2 and newer.
  • 9. Installing PythonBrew ● Download & Install Pythonbrew: ○ curl -kL http://xrl.us/pythonbrewinstall | bash ● Enabled it in your .bashrc ○ source $HOME/.pythonbrew/etc/bashrc ● List installed interpreters: ○ $ pythonbrew list ● Install Python 3.3 ○ $ pythonbrew install 3.3.0
  • 10. Setup Python2 environment ● Create an environment for your Python2 webapp: ○ $ virtualenv --distribute --no-site-packages py2 ● Depending on your virtualenv version and system --distribute and --no-site- packages might be the default.
  • 11. Our Python3 environment ● Switch to Python3 ○ $ pythonbrew use Python-3.3.0 ● Install virtualenv: ○ $ pip install virtualenv ● Create Python3 environment: ○ $ virtualenv py3 ● Recover your standard Python: ○ $ pythonbrew off
  • 12. Switch env not interpreter ● Work with Python2 ○ $ source py2/bin/activate ● Work with Python3 ○ $ source py3/bin/activate ● Quit current active environment ○ $ deactivate
  • 13. Installing TurboGears2 ● Enable Python3 ○ $ source py3/bin/activate ● Install tg.devtools ○ $ pip install -f http://tg.gy/230 tg.devtools ● You should get TurboGears2-2.3.0b2 ● Documentation ○ http://turbogears.readthedocs.org/en/tg2.3.0b2/ ○ Don't forget version and trailing slash!
  • 14. Out first Python3 app ● edit app.py ● TurboGears minimal mode, much like microframeworks from wsgiref.simple_server import make_server from tg import expose, TGController, AppConfig class RootController(TGController): @expose() def index(self): return "<h1>Hello World</h1>" config = AppConfig(minimal=True, root_controller=RootController()) print("Serving on port 8080...") httpd = make_server('', 8080, config.make_wsgi_app()) httpd.serve_forever()
  • 15. Object Dispatch ● Routing happens on your controller method names and parameters ● Regular expressions can get messy, never write one anymore ○ unless your need it: tgext.routes ● Easy to get to the controller that handles an url just by looking at the url
  • 16. Object Dispatch URL CONTROLLER /index RootController.index / RootController.index /blog/3 BlogEntryController.index (post = 3) /blog/update?post=3 BlogEntryController.update (post = 3) /about RootController.about /more/1/2/3 RootController.more (args[0]=1, args[1]=2, args[3]=3) /more?data=5 RootController.more (kw['data']=5) class BlogEntryController (BaseController): @expose() def index(self, post): return 'HI' @expose() def edit(self, post): return 'HI' @expose() def update(self, post): return 'HI' class RootController(BaseController): blog = BlogEntryController() @expose() def index(self): return 'HI' @expose() def about(self): return 'HI' @expose() def more(self, *args, **kw): return 'HI'
  • 17. Template Engine agnostic ● Doesn't enforce any template language bound to your controllers ● Genshi, Jinja, Mako and Kajiki officially supported ● Genshi is strongly suggested due to the need of a lingua franca for puggable applications
  • 18. Templates out of the box TYPE NAME URL Markup + Streamed Genshi http://genshi.edgewall.org/ Text + Compiled Mako http://www.makotemplates.org/ Text + Compiled Jinja http://http://jinja.pocoo.org/ Markup + Compiled Kajiki http://kajiki.pythonisito.com/
  • 19. Add a Template ● Install Genshi: ○ $ pip install genshi ● Register it as a renderer available to the framework: ○ base_config.renderers = ['genshi'] ● Expose it in controllers: ○ @expose('template.html')
  • 20. Hello Template from wsgiref.simple_server import make_server from tg import expose, TGController, AppConfig class RootController(TGController): @expose('index.html') def index(self): return dict() config = AppConfig(minimal=True, root_controller=RootController()) config.renderers = ['genshi'] print("Serving on port 8080...") httpd = make_server('', 8080, config.make_wsgi_app()) httpd.serve_forever() <html xmlns="http://www.w5.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/"> <head> <title>Hello World</title> </head> <body> <h1>Hello World</h1> </body> </html> ● index should now expose index.html template and return dict()
  • 21. Hello $user from wsgiref.simple_server import make_server from tg import expose, TGController, AppConfig class RootController(TGController): @expose('index.html') def index(self): return dict(user='World') config = AppConfig(minimal=True, root_controller=RootController()) config.renderers = ['genshi'] print("Serving on port 8080...") httpd = make_server('', 8080, config.make_wsgi_app()) httpd.serve_forever() <html xmlns="http://www.w5.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/"> <head> <title>Hello World</title> </head> <body> <h1>Hello ${user}</h1> </body> </html> ● Every entry in the returned dictionary will be available inside the exposed template as a variable
  • 22. from request import data from wsgiref.simple_server import make_server from tg import expose, TGController, AppConfig class RootController(TGController): @expose('index.html') def index(self, user='World', **kw): return dict(user=user) config = AppConfig(minimal=True, root_controller=RootController()) config.renderers = ['genshi'] print("Serving on port 8080...") httpd = make_server('', 8080, config.make_wsgi_app()) httpd.serve_forever() ● All arguments available in your URL will be passed as method parameters
  • 23. Going Full Stack ● TurboGears minimal mode provides a quick way to be productive. ● Full stack mode provides an already configured environment and more features
  • 24. What is Full Stack ● ORM and Transaction Manager ● Authentication and Identification ● Interactive Debugger and Error Reporting ● PasteDeploy compatible configuration ● Static Files ● Session and Caching ● Widgets and Admin (on Python2)
  • 25. Creating a Full Stack application ● Full stack applications are created through the gearbox toolkit ○ $ gearbox quickstart --skip-tw myapp ○ --skip-tw is required due to forms generation library not being available on Python3 yet. ● Full stack applications are packages: can be installed and updated to deploy
  • 27. Install the quickstarted app ● To use the app you need to install it: ○ $ pip install -e . ● Installing also brings in dependencies the app requires ● Now run your application ○ $ gearbox serve --reload
  • 28. A lot is there now ● Point your browser to http://localhost: 8080 and see TurboGears in action ● Quite a lot is there now! ● Have a look around ● App pages explain the app itself
  • 29. Authentication ● Click the login link in the upper-right corner ○ username: manager ○ password: managepass ● Crash! ● Database has not been initialized ○ You now know what the interactive debugger looks like!
  • 30. Authentication, #2 try ● Create database and basic entities ○ $ gearbox setup-app ○ By default sqlite: devdata.db ● Click the login link in the upper-right corner ○ username: manager ○ password: managepass ● Woah! Welcome back manager!
  • 31. Authorization ● Go to http://localhost:8080/secc ○ Secure controller here ● Logout ● Go to http://localhost:8080/secc ○ Only for people with "manage" permission
  • 32. Users and Permissions ● Default users are created in the application setup script (setup-app) ○ Have a look at websetup/bootstrap.py ● Default models are provided by the quickstart command for User, Group and Permission ○ Have a look at models/auth.py
  • 33. Predicates and Authorization ● Turbogears checks for authorization requiring predicates bound to controllers or methods ● http://turbogears.readthedocs. org/en/tg2.3.0 @expose('prova.templates.index') @require(predicates.has_permission('manage', msg=l_('Only for managers'))) def manage_permission_only(self, **kw): """Illustrate how a page for managers only works.""" return dict(page='managers stuff')
  • 35. Accessing Models ● TurboGears relies on SQLAlchemy for SQL based databases and on Ming for MongoDB databases ○ Both are first citizens of the TurboGears Admin ○ Both are supported out of the box ○ Run quickstart --ming to have MongoDB support ○ Run quickstart --nosa to disable database at all ○ gearbox help quickstart
  • 36. Accessing Models ● TurboGears relies on SQLAlchemy for SQL based databases and on Ming for MongoDB databases ○ Both are first citizens of the TurboGears Admin ○ Both are supported out of the box ○ Run quickstart --ming to have MongoDB support ○ Run quickstart --nosa to disable database at all ○ gearbox help quickstart
  • 37. Create, Read, Update, Delete ● Create ○ DBSession.add(Page(name='index')) ● Read ○ page = DBSession.query(Page).filter_by(name='index').one() ● Update ○ page.data = 'This is an empty page' ● Delete ○ DBSession.delete(page)
  • 38. Wiki20 Tutorial ● TurboGears documentation provides a great Wiki in 20 minutes Tutorial ○ http://turbogears.readthedocs.org/en/tg2.3.0 b2/turbogears/wiki20.html#wiki-model ● Just skip up to the Wiki Model section, we already know the previous parts
  • 41. Back to Python2 ● This is as far as you can get using Python3 ● Some features not available there ○ i18n utilities ○ Widgets ○ MongoDB ○ TurboGears Admin
  • 42. Moving to Widgets and Forms ● Doing forms is a tedious task ● Validating data users write is a mess ● Let's use widgets and forms ○ Generates HTML for us ○ Validates input ○ Keeps track of values in case of errors ○ Reports errors to users
  • 43. Enable forms ● Switch back to Python2 ○ $ source py2/bin/activate ● Enable forms in your project ○ edit config/app_cfg.py ○ base_config.use_toscawidgets2 = True ● Install ○ Add tw2.forms to setup.py install_requires ○ pip install -e .
  • 44. Writing Widgets and Validation from tg import validate import tw2.core as twc import tw2.forms as twf class PageForm(twf.TableForm): pagename = twf.HiddenField(validator=twc.Validator(required=True)) data = twf.TextArea(validator=twc.Validator(required=True)) action = lurl('/save') class RootController(BaseController): @expose() @validate(PageForm, error_handler=edit) def save(self, pagename, data): page = DBSession.query(Page).filter_by(pagename=pagename).one() page.data = data flash("Page successfully updated!") return redirect("/" + pagename)
  • 45. Let's translate ● TurboGears detects language of the user and translates text in templates and controllers accordigly ● Translation itself is available on both Python2 and Python3 ● String collection is only available on Python2
  • 46. Collect text ● Install Babel ○ $ pip install babel ● Template content is automatically collected and translated ● Text in controllers must be wrapped with l_() or _() to make them translatable ● Wrap your flash messages
  • 47. Perform collection ● Walkthrough on i18n ○ http://turbogears.readthedocs.org/en/tg2.3.0 b2/turbogears/i18n.html ● Utility commands ○ python setup.py extract_messages ○ python setup.py init_catalog -l it ○ poedit i18n/it/LC_MESSAGES/myproj.po ○ python setup.py compile_catalog
  • 48. TurboGears Admin ● A lot of effort has been spent in ○ writing forms ○ validating data ○ editing pages ● Still a lot to do ○ How do I delete a page? ○ How do I search for a page?
  • 49. Admin does that for you
  • 50. Enabling the Admin ● Automatically done if you quickstarted without --skip-tw option ● Enable manually as we started on Py3 ○ $ pip install tgext.admin ○ Add admin controller from tgext.admin.tgadminconfig import TGAdminConfig from tgext.admin.controller import AdminController class RootController(BaseController): admin = AdminController(model, DBSession, config_type=TGAdminConfig)
  • 51. Rapid Prototyping ● TurboGears admin is based on tgext.crud, a powerfull rapid prototyping tool ● Have a look at the admin tutorial ○ http://turbogears.readthedocs.org/en/tg2.3.0 b2/turbogears/wikier/index.html ● Avoid pushing the admin too far ○ Custom solutions are cleaner than a too much customized admin
  • 52. Admin is great for REST ● REST api for free ● For real, try to put .json after your pages list ○ /admin/pages.json ● Supports a full featured REST api ○ Meaningful error codes ○ Conditional PUT ● You might want to use tgext.crud directly to build rest services
  • 53. Look for ready made plugins ● tgext.pluggable enables pluggable applications ● The cogbin is a collection of existing extensions and pluggable apps ○ http://turbogears.org/cogbin.html ● Features like Facebook auth, blogging, registration and so on available on cogbin
  • 54. The DebugBar ● Great plugin available is the DebugBar ○ pip install tgext.pluggable ○ pip install tgext.debugbar ● Enable debugbar ○ config/app_cfg.py ○ from tgext.pluggable import plug ○ plug(base_config, 'tgext.debugbar')
  • 57. Want to support MongoDB ● Try passing --ming to gearbox quickstart ● Full featured admin and tgext.crud as on SQLAlchemy ● Ming ODM has similar syntax ● Ming provides Unit of Work pattern like SQLAlchemy ○ transaction manager missing, pay attention
  • 58. Want to support MongoDB ● Full featured admin and tgext.crud as on SQLAlchemy ● DebugBar works also with Ming ○ now with cool hightlighting of map-reduce javascript code too!