SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Patterns for building large
  Pyramid applications


                   Carlos de la Guardia
Pyramid is a very flexible framework

”A la carte”, use-only-what-you-need features. You can
  start small and grow your application as needed.
No persistence back end enforced.
Ability to use multiple templating languages.
Many pluggable points and extensibility mechanisms.
We love that and are proud about this.
But for new users, sometimes flexibility means too
 many options.
Please tell me what to do!
Decisions, decisions, decisions

Pyramid tries to help you decide in some ways:
   Scaffolds make some decisions for you.
   Everything is documented so you can make informed
     choices.
   Some third party packages make yet more decisions.
The scope of your project can also be a factor that
  influences how you layout your project and what tools
   you use.
Knowing how others do things can also help decide.
Some suggestions

Project layout.
Tips for choosing a persistence mechanism.
Assembling your toolkit.
What is traversal and do I need it?
View configuration.
Deployment.
Extensible applications.
KARL

Some of these suggestions come from my experience
  working as a member of KARL's development team.
KARL is an open source web system for collaboration,
 organizational intranets, and knowledge management.
Used by many international organizations, such as
  OXFAM GB, OSF, and more.
5000+ users (no anonymous access).
More than 75,000 Pages of content.
Nearly 100,000 lines of code
http://karlproject.org
Project layout

Pyramid does not enforce any layout.
Small or 'one-of' applications can simply use a single
 file or a few files on the same directory.
For small to medium size applications, all Pyramid
  scaffolds suggest the same layout.
Scaffold layout
MyProject/
|-- CHANGES.txt
|-- development.ini
|-- MANIFEST.in
|-- myproject
| |-- __init__.py
| |-- static
| | |-- favicon.ico
| | |-- logo.png
| | `-- pylons.css
| |-- templates
| | `-- mytemplate.pt
| |-- tests.py
| `-- views.py
|-- production.ini
|-- README.txt
|-- setup.cfg
`-- setup.py
Larger project layout
MyLargerProject/
|-- CHANGES.txt, etc.
|-- mylargerproject
| |-- __init__.py
| |-- static
| | `-- project.css
| |-- templates
| | `-- mytemplate.pt
| |-- models
| | |-- somemodel.py
| | `-- othermodel.py
| |-- someotherpackage
| | `-- somestuff.py
| |-- views
| | |-- someview.py
| | `-- otherview.py
| |-- tests
| | `-- test_something.py
`-- setup.py, etc.
Do I have to use python packaging?

Love it or hate it, it's what we have.
You probably want your distributions on PyPi.
Plus, packaging tools are being improved right now by
  people at this conference.
Assembling your toolkit

Persistence back end:
   SQLAlchemy.
   Other ORMs.
   Direct db driver connection.
   MongoDB (pyramid_mongodb).
   ZODB (Pyramid_zodbconn).
   Multiple transactional backends? Use pyramid_tm.
What tools are you familiar with?
The most important question is how does your data look
  like?
Assembling your toolkit

Templating language:
  Chameleon.
  Mako.
  Jinja2 (pyramid_jinja2).
  Other.
Forms:
  pyramid_deform.
  pyramid_formalchemy.
  pyramid_formish.
  pyramid_simpleform.
Assembling your toolkit

Authentication:
   Write your own with Pyramid's out of the box facilites.
   pyramid-openid.
   pyramid_basicauth.
   pyramid_who.
   Velruse.
Development:
   pyramid_debugtoolbar (a must).
   buildout.
URLDispatch and traversal

Pyramid offers two mechanisms for finding views
  associated with your data.
URLDispatch is the classic, route-based mechanism.
 URLDispatch is great for table-like data.
Traversal allows you to create a tree of resources, each
  of which can be addressed by one or more URLs. It's
  great for tree-like data (think filesystem).
It's also a perfect fit for arbitrarily extendable sites and
   sites that require very granular security.
Like with relational backends, the key to choosing is
  how your data will look like.
View configuration

Use declarative configuration.
   Lets framework configuration statements live next to the
     code they configure.
   Pyramid's view configuration decorators are inert. They don't
     change the view's input or output.
   They have to be activated from the main configuration with
     scan().
Use renderers.
   Easy to change implementation.
   Facilitates testing.
View configuration

Use predicates:
   In Pyramid, a single route can correspond to one or more views.
      Predicates allow the view finding mechanism to find the correct
      view.
   route_name='home'
   request_method=POST
   xhr=True
   Lots of others, plus custom predicates.
Easy HTTP caching:
   @view_config(http_cache=3600) # 60 minutes
   Pyramid will add appropriate Cache-Control and Expires headers
     to responses generated when this view is invoked.
View configuration

Many applications have similar view data that needs to
 be passed to the renderers every time:
   You can generate that information on every view.
   You can have a method or class that generates a dictionary
     with the common values.
   You can make your views methods of a single class with a
     common initialization.
   If you don't have alergic reactions to any mention of a
      particular forbidden 'Z' word, there are other ways.
View configuration

Class method views example:
 from pyramid.response import Response
 from pyramid.view import view_config

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

   @view_config(route_name='view_one')
   def view_one(self):
     return Response('one')

   @view_config(route_name='view_two')
   def view_two(self):
     return Response('two')
Extensibility

Requirements depend on kind of project.
Pyramid provides some easy to use mechanisms that
  allow you to compose or extend applications.
  Strong, extensible configuration mechanism with conflict
    detection and the ability to add directives.
  Structured includes.
  Asset specifications.
  Tweens (Pyramid specific middleware).
  ZCA-based overriding mechanisms.
Extensibility

Asset specification example:
my.package:static/baz.css

  identifies the file named baz.css in the static subdirectory of the
  my.package Python package.

Using asset overriding:
  config.override_asset(
      to_override='some.package:templates/mytemplate.pt',
      override_with='another.package:othertemplates/anothertemplate.pt')

  config.override_asset(to_override='some.package',
      override_with='another.package')
Test, test, test

What do you call 100% coverage? A good start.
Unit tests. Make sure that nothing breaks.
Functional tests. Make sure it does what it's supposed
  to do.
Tools:
   Nose
   Coverage
   WebTest
   Selenium
   Use whatever you want, just test.
Document

If possible, use documentation to guide application
   design.
Write or sketch how things should work before
 implementing them.
Share with the team to get input, understanding.
Tools:
   Class or method doc strings.
   Sphinx.
   Balsamiq.
Deployment with buildout

Buildout is a Python system for assembling applications
 from multiple parts in a repeatable manner.
Recipes are used to define what each part of the
 buildout will install and/or setup. There are many
 available recipes on PyPI.
A buildout can have different configurations. For
  example, deployment and production.
Buildout can be used to setup a Pyramid application
 and it's dependencies easily.
Deployment with buildout

Sample buildout:
  [buildout]
  parts =
     myapp
     mkrelease

  Develop = src/mypackage

  index = http://example.github.com/myapp/staging/index/

  [myapp]
  recipe = zc.recipe.egg
  eggs =
     pyramid_debugtoolbar
     nose
     mypackage
  interpreter = py
Deployment with supervisor

Supervisor is a client/server system that allows its users
 to monitor and control a number of processes on
 UNIX-like operating systems.
We can use supervisor to control our pyramid
 applications, either alone or together with other
 applications or services.
A very easy way to configure it is to simply add the
  supervisor egg to our buildout and include a
  configuration file
Deployment with supervisor
[inet_http_server]
port=127.0.0.1:9001

[supervisord]
logfile=%(here)s/var/supervisord.log
logfile_maxbytes=50MB
logfile_backups=10
loglevel=info
pidfile=%(here)s/var/supervisord.pid

[rpcinterface:supervisor]
supervisor.rpcinterface_factory =
supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=http://127.0.0.1:9001

[program:core]
command = %(here)s/bin/paster serve %(here)s/src/inav2_core/development.ini
redirect_stderr = true
Deployment with nginx
More information at:
http://docs.pylonsproject.org/projects/pyramid_cookbook/dev/deployment/nginx.html

upstream myapp-site {
    server 127.0.0.1:5000;
    server 127.0.0.1:5001;
}
server {
    server_name example.com;
    access_log /home/example/env/access.log;
    location / {
         proxy_set_header        Host $host;
         proxy_set_header        X-Real-IP $remote_addr;
         proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header        X-Forwarded-Proto $scheme;
         proxy_connect_timeout   60s;
         proxy_send_timeout      90s;
         proxy_read_timeout      90s;
         proxy_buffering         off;
         proxy_pass http://myapp-site;
         proxy_redirect          off;
    }
}
Deployment with mod_wsgi
We need to create an app that will call our application with configuration.
Then we set up apache to call this app.

More information at:
http://docs.pylonsproject.org/projects/pyramid/1.2/tutorials/modwsgi/index.html

#pyramid.wsgi
from pyramid.paster import get_app
application = get_app('/mydir/modwsgi/env/myapp/production.ini', 'main')

#apache.conf
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=cguardia group=staff threads=4 
   python-path=/mydir/modwsgi/env/lib/python2.6/site-packages
WSGIScriptAlias /myapp /mydir/modwsgi/env/pyramid.wsgi
<Directory /mydir/modwsgi/env>
  WSGIProcessGroup pyramid
  Order allow,deny
  Allow from all
</Directory>
Thanks!

@cguardia on Twitter and IRC.
Join us at the #pyramid IRC channel for encouragement
  and support.
There's also the Pyramid mailing lists at Google
  Groups:

  http://groups.google.com/group/pylons-devel

Weitere ähnliche Inhalte

Was ist angesagt?

"Eclipse Application Development" at GNUnify 07
"Eclipse Application Development" at GNUnify 07"Eclipse Application Development" at GNUnify 07
"Eclipse Application Development" at GNUnify 07KetanPadegaonkar
 
Chicago Code Camp 2014 TFS Care and Feeding
Chicago Code Camp 2014   TFS Care and FeedingChicago Code Camp 2014   TFS Care and Feeding
Chicago Code Camp 2014 TFS Care and FeedingAngela Dugan
 
Factors to consider when starting a brand-new requirements management project...
Factors to consider when starting a brand-new requirements management project...Factors to consider when starting a brand-new requirements management project...
Factors to consider when starting a brand-new requirements management project...IBM Rational software
 
Automated software testing
Automated software testingAutomated software testing
Automated software testingMD ISLAM
 
Functional and Non-functional Test automation
Functional and Non-functional Test automationFunctional and Non-functional Test automation
Functional and Non-functional Test automationDr Ganesh Iyer
 
Software Architecture vs design
Software Architecture vs design Software Architecture vs design
Software Architecture vs design Arslan Anwar
 
L2 l3 l4 software process models
L2 l3 l4  software process modelsL2 l3 l4  software process models
L2 l3 l4 software process modelsRushdi Shams
 
Introduction to Aspect Oriented Software Development
Introduction to Aspect Oriented Software DevelopmentIntroduction to Aspect Oriented Software Development
Introduction to Aspect Oriented Software Developmentmukhtarhudaya
 
[Devopsdays2021] Roll Your Product with Kaizen Culture
[Devopsdays2021] Roll Your Product with Kaizen Culture[Devopsdays2021] Roll Your Product with Kaizen Culture
[Devopsdays2021] Roll Your Product with Kaizen CultureWoohyeok Kim
 
D22 portlet development with open source frameworks
D22 portlet development with open source frameworksD22 portlet development with open source frameworks
D22 portlet development with open source frameworksSunil Patil
 
The Power of Enterprise Java Frameworks
The Power of Enterprise Java FrameworksThe Power of Enterprise Java Frameworks
The Power of Enterprise Java FrameworksClarence Ho
 
Software engineering تلخيص
Software engineering تلخيصSoftware engineering تلخيص
Software engineering تلخيصARWA ALSAIF
 
Mainframe DevOps: A Zowe CLI-enabled Roadmap
Mainframe DevOps: A Zowe CLI-enabled RoadmapMainframe DevOps: A Zowe CLI-enabled Roadmap
Mainframe DevOps: A Zowe CLI-enabled RoadmapDevOps.com
 
Software Testing Process
Software Testing ProcessSoftware Testing Process
Software Testing Processguest1f2740
 
+Software development methodologies
+Software development methodologies+Software development methodologies
+Software development methodologieswalid sassi
 
Using Agile Processes on Documentum Projects
Using Agile Processes on Documentum ProjectsUsing Agile Processes on Documentum Projects
Using Agile Processes on Documentum Projectsmufflerdog
 
Choosing right-automation-tool
Choosing right-automation-toolChoosing right-automation-tool
Choosing right-automation-toolBabuDevanandam
 
Modules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module SystemModules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module SystemTim Ellison
 

Was ist angesagt? (20)

"Eclipse Application Development" at GNUnify 07
"Eclipse Application Development" at GNUnify 07"Eclipse Application Development" at GNUnify 07
"Eclipse Application Development" at GNUnify 07
 
Chicago Code Camp 2014 TFS Care and Feeding
Chicago Code Camp 2014   TFS Care and FeedingChicago Code Camp 2014   TFS Care and Feeding
Chicago Code Camp 2014 TFS Care and Feeding
 
Factors to consider when starting a brand-new requirements management project...
Factors to consider when starting a brand-new requirements management project...Factors to consider when starting a brand-new requirements management project...
Factors to consider when starting a brand-new requirements management project...
 
Automated software testing
Automated software testingAutomated software testing
Automated software testing
 
Functional and Non-functional Test automation
Functional and Non-functional Test automationFunctional and Non-functional Test automation
Functional and Non-functional Test automation
 
Software Architecture vs design
Software Architecture vs design Software Architecture vs design
Software Architecture vs design
 
L2 l3 l4 software process models
L2 l3 l4  software process modelsL2 l3 l4  software process models
L2 l3 l4 software process models
 
Introduction to Aspect Oriented Software Development
Introduction to Aspect Oriented Software DevelopmentIntroduction to Aspect Oriented Software Development
Introduction to Aspect Oriented Software Development
 
[Devopsdays2021] Roll Your Product with Kaizen Culture
[Devopsdays2021] Roll Your Product with Kaizen Culture[Devopsdays2021] Roll Your Product with Kaizen Culture
[Devopsdays2021] Roll Your Product with Kaizen Culture
 
D22 portlet development with open source frameworks
D22 portlet development with open source frameworksD22 portlet development with open source frameworks
D22 portlet development with open source frameworks
 
The Power of Enterprise Java Frameworks
The Power of Enterprise Java FrameworksThe Power of Enterprise Java Frameworks
The Power of Enterprise Java Frameworks
 
Software engineering تلخيص
Software engineering تلخيصSoftware engineering تلخيص
Software engineering تلخيص
 
Mainframe DevOps: A Zowe CLI-enabled Roadmap
Mainframe DevOps: A Zowe CLI-enabled RoadmapMainframe DevOps: A Zowe CLI-enabled Roadmap
Mainframe DevOps: A Zowe CLI-enabled Roadmap
 
Software Testing Process
Software Testing ProcessSoftware Testing Process
Software Testing Process
 
+Software development methodologies
+Software development methodologies+Software development methodologies
+Software development methodologies
 
Priyanka_CV
Priyanka_CVPriyanka_CV
Priyanka_CV
 
Using Agile Processes on Documentum Projects
Using Agile Processes on Documentum ProjectsUsing Agile Processes on Documentum Projects
Using Agile Processes on Documentum Projects
 
Choosing right-automation-tool
Choosing right-automation-toolChoosing right-automation-tool
Choosing right-automation-tool
 
Modules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module SystemModules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module System
 
.NET Developer
.NET Developer.NET Developer
.NET Developer
 

Ähnlich wie Pyramid patterns

Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and MaintenanceJazkarta, Inc.
 
Strategies and Tips for Building Enterprise Drupal Applications - PNWDS 2013
Strategies and Tips for Building Enterprise Drupal Applications - PNWDS 2013Strategies and Tips for Building Enterprise Drupal Applications - PNWDS 2013
Strategies and Tips for Building Enterprise Drupal Applications - PNWDS 2013Mack Hardy
 
How to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkHow to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkRapidValue
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگوrailsbootcamp
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015Pushkar Chivate
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!David Gibbons
 
ZZ BC#7.5 asp.net mvc practice and guideline refresh!
ZZ BC#7.5 asp.net mvc practice  and guideline refresh! ZZ BC#7.5 asp.net mvc practice  and guideline refresh!
ZZ BC#7.5 asp.net mvc practice and guideline refresh! Chalermpon Areepong
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture IntroductionHaiqi Chen
 
Datasheet was pluginforrd
Datasheet was pluginforrdDatasheet was pluginforrd
Datasheet was pluginforrdMidVision
 
Drupal performance and scalability
Drupal performance and scalabilityDrupal performance and scalability
Drupal performance and scalabilityTwinbit
 
Cloudsim_openstack_aws_lastunit_bsccs_cloud computing
Cloudsim_openstack_aws_lastunit_bsccs_cloud computingCloudsim_openstack_aws_lastunit_bsccs_cloud computing
Cloudsim_openstack_aws_lastunit_bsccs_cloud computingMrSameerSTathare
 
7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script TaskPramod Singla
 
Managing Your Runtime With P2
Managing Your Runtime With P2Managing Your Runtime With P2
Managing Your Runtime With P2Pascal Rapicault
 

Ähnlich wie Pyramid patterns (20)

Pyramid deployment
Pyramid deploymentPyramid deployment
Pyramid deployment
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
 
Strategies and Tips for Building Enterprise Drupal Applications - PNWDS 2013
Strategies and Tips for Building Enterprise Drupal Applications - PNWDS 2013Strategies and Tips for Building Enterprise Drupal Applications - PNWDS 2013
Strategies and Tips for Building Enterprise Drupal Applications - PNWDS 2013
 
How to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkHow to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular Framework
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
Pyramid tutorial
Pyramid tutorialPyramid tutorial
Pyramid tutorial
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
ZZ BC#7.5 asp.net mvc practice and guideline refresh!
ZZ BC#7.5 asp.net mvc practice  and guideline refresh! ZZ BC#7.5 asp.net mvc practice  and guideline refresh!
ZZ BC#7.5 asp.net mvc practice and guideline refresh!
 
sveltekit-en.pdf
sveltekit-en.pdfsveltekit-en.pdf
sveltekit-en.pdf
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 
Datasheet was pluginforrd
Datasheet was pluginforrdDatasheet was pluginforrd
Datasheet was pluginforrd
 
Azure from scratch part 4
Azure from scratch part 4Azure from scratch part 4
Azure from scratch part 4
 
Django
DjangoDjango
Django
 
Drupal performance and scalability
Drupal performance and scalabilityDrupal performance and scalability
Drupal performance and scalability
 
Cloudsim_openstack_aws_lastunit_bsccs_cloud computing
Cloudsim_openstack_aws_lastunit_bsccs_cloud computingCloudsim_openstack_aws_lastunit_bsccs_cloud computing
Cloudsim_openstack_aws_lastunit_bsccs_cloud computing
 
7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task
 
Managing Your Runtime With P2
Managing Your Runtime With P2Managing Your Runtime With P2
Managing Your Runtime With P2
 
oracle
oracleoracle
oracle
 
Google Cloud Platform
Google Cloud Platform Google Cloud Platform
Google Cloud Platform
 

Mehr von Carlos de la Guardia

Introduction to the transaction package
Introduction to the transaction packageIntroduction to the transaction package
Introduction to the transaction packageCarlos de la Guardia
 
Pyramid as a base for higher level frameworks
Pyramid as a base for higher level frameworksPyramid as a base for higher level frameworks
Pyramid as a base for higher level frameworksCarlos de la Guardia
 
A winning combination: Plone as CMS and your favorite Python web framework as...
A winning combination: Plone as CMS and your favorite Python web framework as...A winning combination: Plone as CMS and your favorite Python web framework as...
A winning combination: Plone as CMS and your favorite Python web framework as...Carlos de la Guardia
 
Turning Plone into a dynamic site factory
Turning Plone into a dynamic site factoryTurning Plone into a dynamic site factory
Turning Plone into a dynamic site factoryCarlos de la Guardia
 

Mehr von Carlos de la Guardia (8)

Introduction to the transaction package
Introduction to the transaction packageIntroduction to the transaction package
Introduction to the transaction package
 
Pyramid as a base for higher level frameworks
Pyramid as a base for higher level frameworksPyramid as a base for higher level frameworks
Pyramid as a base for higher level frameworks
 
Pyramid faq
Pyramid faqPyramid faq
Pyramid faq
 
ZODB Tips and Tricks
ZODB Tips and TricksZODB Tips and Tricks
ZODB Tips and Tricks
 
Python intro for Plone users
Python intro for Plone usersPython intro for Plone users
Python intro for Plone users
 
A winning combination: Plone as CMS and your favorite Python web framework as...
A winning combination: Plone as CMS and your favorite Python web framework as...A winning combination: Plone as CMS and your favorite Python web framework as...
A winning combination: Plone as CMS and your favorite Python web framework as...
 
World Plone Day 2008 Mexico
World Plone Day 2008 MexicoWorld Plone Day 2008 Mexico
World Plone Day 2008 Mexico
 
Turning Plone into a dynamic site factory
Turning Plone into a dynamic site factoryTurning Plone into a dynamic site factory
Turning Plone into a dynamic site factory
 

Kürzlich hochgeladen

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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
 
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
 
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
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
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
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
[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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
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)
 
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
 
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?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
[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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Pyramid patterns

  • 1. Patterns for building large Pyramid applications Carlos de la Guardia
  • 2. Pyramid is a very flexible framework ”A la carte”, use-only-what-you-need features. You can start small and grow your application as needed. No persistence back end enforced. Ability to use multiple templating languages. Many pluggable points and extensibility mechanisms. We love that and are proud about this. But for new users, sometimes flexibility means too many options.
  • 3. Please tell me what to do!
  • 4. Decisions, decisions, decisions Pyramid tries to help you decide in some ways: Scaffolds make some decisions for you. Everything is documented so you can make informed choices. Some third party packages make yet more decisions. The scope of your project can also be a factor that influences how you layout your project and what tools you use. Knowing how others do things can also help decide.
  • 5. Some suggestions Project layout. Tips for choosing a persistence mechanism. Assembling your toolkit. What is traversal and do I need it? View configuration. Deployment. Extensible applications.
  • 6. KARL Some of these suggestions come from my experience working as a member of KARL's development team. KARL is an open source web system for collaboration, organizational intranets, and knowledge management. Used by many international organizations, such as OXFAM GB, OSF, and more. 5000+ users (no anonymous access). More than 75,000 Pages of content. Nearly 100,000 lines of code http://karlproject.org
  • 7. Project layout Pyramid does not enforce any layout. Small or 'one-of' applications can simply use a single file or a few files on the same directory. For small to medium size applications, all Pyramid scaffolds suggest the same layout.
  • 8. Scaffold layout MyProject/ |-- CHANGES.txt |-- development.ini |-- MANIFEST.in |-- myproject | |-- __init__.py | |-- static | | |-- favicon.ico | | |-- logo.png | | `-- pylons.css | |-- templates | | `-- mytemplate.pt | |-- tests.py | `-- views.py |-- production.ini |-- README.txt |-- setup.cfg `-- setup.py
  • 9. Larger project layout MyLargerProject/ |-- CHANGES.txt, etc. |-- mylargerproject | |-- __init__.py | |-- static | | `-- project.css | |-- templates | | `-- mytemplate.pt | |-- models | | |-- somemodel.py | | `-- othermodel.py | |-- someotherpackage | | `-- somestuff.py | |-- views | | |-- someview.py | | `-- otherview.py | |-- tests | | `-- test_something.py `-- setup.py, etc.
  • 10. Do I have to use python packaging? Love it or hate it, it's what we have. You probably want your distributions on PyPi. Plus, packaging tools are being improved right now by people at this conference.
  • 11. Assembling your toolkit Persistence back end: SQLAlchemy. Other ORMs. Direct db driver connection. MongoDB (pyramid_mongodb). ZODB (Pyramid_zodbconn). Multiple transactional backends? Use pyramid_tm. What tools are you familiar with? The most important question is how does your data look like?
  • 12. Assembling your toolkit Templating language: Chameleon. Mako. Jinja2 (pyramid_jinja2). Other. Forms: pyramid_deform. pyramid_formalchemy. pyramid_formish. pyramid_simpleform.
  • 13. Assembling your toolkit Authentication: Write your own with Pyramid's out of the box facilites. pyramid-openid. pyramid_basicauth. pyramid_who. Velruse. Development: pyramid_debugtoolbar (a must). buildout.
  • 14. URLDispatch and traversal Pyramid offers two mechanisms for finding views associated with your data. URLDispatch is the classic, route-based mechanism. URLDispatch is great for table-like data. Traversal allows you to create a tree of resources, each of which can be addressed by one or more URLs. It's great for tree-like data (think filesystem). It's also a perfect fit for arbitrarily extendable sites and sites that require very granular security. Like with relational backends, the key to choosing is how your data will look like.
  • 15. View configuration Use declarative configuration. Lets framework configuration statements live next to the code they configure. Pyramid's view configuration decorators are inert. They don't change the view's input or output. They have to be activated from the main configuration with scan(). Use renderers. Easy to change implementation. Facilitates testing.
  • 16. View configuration Use predicates: In Pyramid, a single route can correspond to one or more views. Predicates allow the view finding mechanism to find the correct view. route_name='home' request_method=POST xhr=True Lots of others, plus custom predicates. Easy HTTP caching: @view_config(http_cache=3600) # 60 minutes Pyramid will add appropriate Cache-Control and Expires headers to responses generated when this view is invoked.
  • 17. View configuration Many applications have similar view data that needs to be passed to the renderers every time: You can generate that information on every view. You can have a method or class that generates a dictionary with the common values. You can make your views methods of a single class with a common initialization. If you don't have alergic reactions to any mention of a particular forbidden 'Z' word, there are other ways.
  • 18. View configuration Class method views example: from pyramid.response import Response from pyramid.view import view_config class Aview(object): def __init__(self, request): self.request = request @view_config(route_name='view_one') def view_one(self): return Response('one') @view_config(route_name='view_two') def view_two(self): return Response('two')
  • 19. Extensibility Requirements depend on kind of project. Pyramid provides some easy to use mechanisms that allow you to compose or extend applications. Strong, extensible configuration mechanism with conflict detection and the ability to add directives. Structured includes. Asset specifications. Tweens (Pyramid specific middleware). ZCA-based overriding mechanisms.
  • 20. Extensibility Asset specification example: my.package:static/baz.css identifies the file named baz.css in the static subdirectory of the my.package Python package. Using asset overriding: config.override_asset( to_override='some.package:templates/mytemplate.pt', override_with='another.package:othertemplates/anothertemplate.pt') config.override_asset(to_override='some.package', override_with='another.package')
  • 21. Test, test, test What do you call 100% coverage? A good start. Unit tests. Make sure that nothing breaks. Functional tests. Make sure it does what it's supposed to do. Tools: Nose Coverage WebTest Selenium Use whatever you want, just test.
  • 22. Document If possible, use documentation to guide application design. Write or sketch how things should work before implementing them. Share with the team to get input, understanding. Tools: Class or method doc strings. Sphinx. Balsamiq.
  • 23. Deployment with buildout Buildout is a Python system for assembling applications from multiple parts in a repeatable manner. Recipes are used to define what each part of the buildout will install and/or setup. There are many available recipes on PyPI. A buildout can have different configurations. For example, deployment and production. Buildout can be used to setup a Pyramid application and it's dependencies easily.
  • 24. Deployment with buildout Sample buildout: [buildout] parts = myapp mkrelease Develop = src/mypackage index = http://example.github.com/myapp/staging/index/ [myapp] recipe = zc.recipe.egg eggs = pyramid_debugtoolbar nose mypackage interpreter = py
  • 25. Deployment with supervisor Supervisor is a client/server system that allows its users to monitor and control a number of processes on UNIX-like operating systems. We can use supervisor to control our pyramid applications, either alone or together with other applications or services. A very easy way to configure it is to simply add the supervisor egg to our buildout and include a configuration file
  • 26. Deployment with supervisor [inet_http_server] port=127.0.0.1:9001 [supervisord] logfile=%(here)s/var/supervisord.log logfile_maxbytes=50MB logfile_backups=10 loglevel=info pidfile=%(here)s/var/supervisord.pid [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=http://127.0.0.1:9001 [program:core] command = %(here)s/bin/paster serve %(here)s/src/inav2_core/development.ini redirect_stderr = true
  • 27. Deployment with nginx More information at: http://docs.pylonsproject.org/projects/pyramid_cookbook/dev/deployment/nginx.html upstream myapp-site { server 127.0.0.1:5000; server 127.0.0.1:5001; } server { server_name example.com; access_log /home/example/env/access.log; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 60s; proxy_send_timeout 90s; proxy_read_timeout 90s; proxy_buffering off; proxy_pass http://myapp-site; proxy_redirect off; } }
  • 28. Deployment with mod_wsgi We need to create an app that will call our application with configuration. Then we set up apache to call this app. More information at: http://docs.pylonsproject.org/projects/pyramid/1.2/tutorials/modwsgi/index.html #pyramid.wsgi from pyramid.paster import get_app application = get_app('/mydir/modwsgi/env/myapp/production.ini', 'main') #apache.conf WSGIApplicationGroup %{GLOBAL} WSGIPassAuthorization On WSGIDaemonProcess pyramid user=cguardia group=staff threads=4 python-path=/mydir/modwsgi/env/lib/python2.6/site-packages WSGIScriptAlias /myapp /mydir/modwsgi/env/pyramid.wsgi <Directory /mydir/modwsgi/env> WSGIProcessGroup pyramid Order allow,deny Allow from all </Directory>
  • 29. Thanks! @cguardia on Twitter and IRC. Join us at the #pyramid IRC channel for encouragement and support. There's also the Pyramid mailing lists at Google Groups: http://groups.google.com/group/pylons-devel