SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
Friday, March 30, 12
What is Brubeck?
                       • A Mongrel2 Handler
                       • A Web Framework and Django
                        •  Influenced by Flask,Tornado

                       • A pipeline of coroutines
                       • Some coded opinions and a few libraries
                        •  Backend agnostic
                        •   Database agnostic
                        •   No spaghetti code



Friday, March 30, 12
What is a “Mongrel2”?
                       • A Mongrel2 is an asynchronous web server
                       • Delegatesthat part to external handlers
                                    handling
                         • We build
                         •   They communicate across 2 ZeroMQ sockets
                             •   Less processing than HTTP

                       • Language agnostic JSON or tnetstring
                         • Simple messaging via
                         •   ZeroMQ is language agnostic, thus so is Mongrel2



Friday, March 30, 12
Mongrel2 + A Handler
                                     Mongrel 2

                           Push / Pull                 Pub / Sub




                                         Handler
                                           Handler
                                             Handler



Friday, March 30, 12
What is a Mongrel2 Handler?

                       • Processes messages from Mongrel2
                         • Essentially, a Zed specific WSGI
                             •   There has been some dissent: Y U NO USE WSGI?

                       • Responds in HTTP
                       • A ZeroMQ sockets are language agnostic
                           language opinion
                         •
                         •   Zed chose Lua when he built Tir
                         •   I liked his model, but I like Python too
                         •   Lots of languages now supported



Friday, March 30, 12
Mongrel2 + Brubecks
                                    Mongrel 2

                          Push / Pull                 Pub / Sub




                                        Handler
                                          Handler
                                            Brubeck



Friday, March 30, 12
Pipeline of coroutines
                                   Each request creates 3


                       • Preprocessing
                        • Maps URL to handler

                       • Request Handlingwrite
                        • This is the part you

                       • Postprocessingresponse
                        • Sends an HTTP



Friday, March 30, 12
Hello world Take five!

                       class DemoHandler(WebMessageHandler):
                           def get(self):
                               self.set_body('Take five!')
                               return self.render()

                       urls = [('^/brubeck', DemoHandler)]




Friday, March 30, 12
Hello world Take five!
                   class DemoHandler(WebMessageHandler):
                       def get(self):
                           self.set_body('Take five!')
                           return self.render()

                   urls = [('^/brubeck', DemoHandler)]


            @app.add_route('^/brubeck', method='GET')
            def foo(application, message):
                body = 'Take five!'
                return http_response(body, 200, 'OK', {})




Friday, March 30, 12
Brubeck: routing
                                 Went with the usual style

                   class NameHandler(WebMessageHandler):
                       def get(self, name):
                           ...

                   def name_handler(application, message, name):
                       ...

                   urls = [(r'^/class/(w+)$', NameHandler),
                           (r'^/fun/(?Pw+)$', name_handler)]



           •       https://github.com/j2labs/brubeck/blob/master/demos/demo_urlargs.py



Friday, March 30, 12
Brubeck: templates
                       Supports: Jinja2, Mako,Tornado or Mustache
        from brubeck.templating import Jinja2Rendering

        class DemoHandler(WebMessageHandler, Jinja2Rendering):
            def get(self):
                context = {
                    'name': 'J2 D2',
                }
                return self.render_template('success.html', **context)




           •       https://github.com/j2labs/brubeck/blob/master/demos/demo_jinja2.py
           •       https://github.com/j2labs/brubeck/blob/master/demos/demo_mustache.py



Friday, March 30, 12
Brubeck: auth (pt 1)
               •       Simple example, using `web_authenticated` decorator:

        class DemoHandler(..., UserHandlingMixin):
            @web_authenticated
            def get(self):
                context = {
                    'name': self.current_user.username,
                }
                return self.render_template('some.html', **context)


           •       Also supports secure cookies
           •       Routes users to login template
           •       https://github.com/j2labs/brubeck/blob/master/demos/demo_login.py



Friday, March 30, 12
Brubeck: auth (pt 2)
         class BaseHandler(..., UserHandlingMixin):
             def get_current_user(self):
                 user = None
                 secret=self.application.cookie_secret
                 user_id = self.get_cookie('user_id', secret=secret)
                 if user_id:
                     return load_user(self.db_conn, username=user_id)
                 else:
                     username = self.get_argument('username')
                     password = self.get_argument('password')
                     if username:
                         user = load_user(self.db_conn, username=username)
                 if not user or not user.check_password(password):
                     return
                 return user




Friday, March 30, 12
Brubeck: user
               •       This what a Brubeck user model looks like

        class User(Document):
            username = StringField(max_length=30, required=True)
            password = StringField(max_length=128)
            is_active = BooleanField(default=False)
            last_login = LongField(default=curtime)
            date_joined = LongField(default=curtime)
            ...



           •       Uses UUID for id field
           •       Could use Mongo’s ObjectID if you prefer that
           •       https://github.com/j2labs/brubeck/blob/master/brubeck/models.py



Friday, March 30, 12
Brubeck: data validation
               •       Validation is easy

       >>> from brubeck.models import User
       >>> u = User(username='jd', is_active=True)
       >>> u.set_password('foo')
       >>> u.validate()
       >>> u.username = True
       >>> u.validate()
       Traceback (most recent call last):
       ...
       dictshield.base.ShieldException: Invalid value - username:True




Friday, March 30, 12
Databaseless modeling
               •       This what a Brubeck user looks like as Python


                       >>>   user_instance.to_python()
                       {
                             '_types': ['User'],
                             '_cls': 'User',
                             'username': u'jd',
                             'is_active': False,
                             'last_login': 1311718487532L,
                             'password': u'bcrypt|||salt|||hash',
                             'date_joined': 1311718487532L
                       }




Friday, March 30, 12
Databaseless modeling
                       •   Persistence details are up to you



             # Mongo
             >>> db.users.save(u.to_python())

             # Riak
             >>> user = bucket.new('user_key', data=u.to_python())
             >>> user.store()

             # Memcached
             >>> mc["user_key"] = u.to_json()




Friday, March 30, 12
Brubeck: autoapi
                       Automatic REST APIs from data models (!!)
                                  (Ben Beecher++)

              •        Define a DictShield document (our model)

              •        Define a QuerySet - Implements persistence
                   •    Dictionary based queryset is provided
                   •    Redis, Mongo and MySQL on the way
              •        Subclass AutoAPIBase
                   •    Attach your model as `model`
                   •    Attach your queryset as `queries`

              •        Register API for model in a Brubeck instance

Friday, March 30, 12
Brubeck: autoapi
                                        A Todo API
                       # Define Todo model
                       class Todo(Document):
                           completed = BooleanField(default=False)
                           deleted = BooleanField(default=False)
                           archived = BooleanField(default=False)
                           title = StringField(required=True)
                           ...

                       # Add fields to handler
                       class TodosAPI(AutoAPIBase):
                           queries = DictQueryset(db_conn={})
                           model = Todo

                       # Register with Brubeck instance
                       app.register_api(TodosAPI)


Friday, March 30, 12
Brubeck: autoapi
                $ curl -f 
                    -X POST 
                    -H "content-type: application/json" 
                    -d '{"text": "Watch more bsg", "order": 1}' 
                    http://localhost:6767/todo/

                {
                           "_cls": "Todo",
                           "_id": "111b4bb7-55f5-441b-ba25-c7a4fd99442c",
                           "_types": [
                               "Todo"
                           ],
                           "done": false,
                           "order": 1,
                           "text": "Watch more bsg"
                }




Friday, March 30, 12
Todos: backbone.js
                       AutoAPI works great with backbone.js
                            ( https://github.com/j2labs/todos )




Friday, March 30, 12
Questions ??
               Brubeck: http://brubeck.io
               Code:    https://github.com/j2labs/brubeck

               Mongrel2: http://mongrel.org
               DictShield: https://github.com/j2labs/dictshield

               Gevent: http://gevent.org
               Eventlet: http://eventlet.net



Friday, March 30, 12

Mais conteúdo relacionado

Semelhante a Brubeck

Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
Dvir Volk
 
44 con slides
44 con slides44 con slides
44 con slides
geeksec80
 

Semelhante a Brubeck (20)

Brubeck: The Lightning Talk
Brubeck: The Lightning TalkBrubeck: The Lightning Talk
Brubeck: The Lightning Talk
 
When to use Node? Lessons learned
When to use Node? Lessons learnedWhen to use Node? Lessons learned
When to use Node? Lessons learned
 
node.js in production: Reflections on three years of riding the unicorn
node.js in production: Reflections on three years of riding the unicornnode.js in production: Reflections on three years of riding the unicorn
node.js in production: Reflections on three years of riding the unicorn
 
Js memory
Js memoryJs memory
Js memory
 
Advanced Performance Tuning in Ext GWT
Advanced Performance Tuning in Ext GWTAdvanced Performance Tuning in Ext GWT
Advanced Performance Tuning in Ext GWT
 
Cryptography Attacks and Applications
Cryptography Attacks and ApplicationsCryptography Attacks and Applications
Cryptography Attacks and Applications
 
OSDC 2017 | Mgmt Config: Autonomous systems by James Shubin
OSDC 2017 | Mgmt Config: Autonomous systems by James ShubinOSDC 2017 | Mgmt Config: Autonomous systems by James Shubin
OSDC 2017 | Mgmt Config: Autonomous systems by James Shubin
 
OSDC 2017 - James Shubin - MGMT config autonomous systems
OSDC 2017 - James Shubin - MGMT config autonomous systemsOSDC 2017 - James Shubin - MGMT config autonomous systems
OSDC 2017 - James Shubin - MGMT config autonomous systems
 
2009年终总结(张庆城)
2009年终总结(张庆城)2009年终总结(张庆城)
2009年终总结(张庆城)
 
Mojo+presentation+1
Mojo+presentation+1Mojo+presentation+1
Mojo+presentation+1
 
Leveraging zeromq for node.js
Leveraging zeromq for node.jsLeveraging zeromq for node.js
Leveraging zeromq for node.js
 
44CON 2013 - Browser bug hunting - Memoirs of a last man standing - Atte Kett...
44CON 2013 - Browser bug hunting - Memoirs of a last man standing - Atte Kett...44CON 2013 - Browser bug hunting - Memoirs of a last man standing - Atte Kett...
44CON 2013 - Browser bug hunting - Memoirs of a last man standing - Atte Kett...
 
5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB
 
MongoDB.pdf
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
 
(not= DSL macros)
(not= DSL macros)(not= DSL macros)
(not= DSL macros)
 
Grails 2.0 Update
Grails 2.0 UpdateGrails 2.0 Update
Grails 2.0 Update
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
 
Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live Applications
 
44 con slides
44 con slides44 con slides
44 con slides
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

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...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 

Brubeck

  • 2. What is Brubeck? • A Mongrel2 Handler • A Web Framework and Django • Influenced by Flask,Tornado • A pipeline of coroutines • Some coded opinions and a few libraries • Backend agnostic • Database agnostic • No spaghetti code Friday, March 30, 12
  • 3. What is a “Mongrel2”? • A Mongrel2 is an asynchronous web server • Delegatesthat part to external handlers handling • We build • They communicate across 2 ZeroMQ sockets • Less processing than HTTP • Language agnostic JSON or tnetstring • Simple messaging via • ZeroMQ is language agnostic, thus so is Mongrel2 Friday, March 30, 12
  • 4. Mongrel2 + A Handler Mongrel 2 Push / Pull Pub / Sub Handler Handler Handler Friday, March 30, 12
  • 5. What is a Mongrel2 Handler? • Processes messages from Mongrel2 • Essentially, a Zed specific WSGI • There has been some dissent: Y U NO USE WSGI? • Responds in HTTP • A ZeroMQ sockets are language agnostic language opinion • • Zed chose Lua when he built Tir • I liked his model, but I like Python too • Lots of languages now supported Friday, March 30, 12
  • 6. Mongrel2 + Brubecks Mongrel 2 Push / Pull Pub / Sub Handler Handler Brubeck Friday, March 30, 12
  • 7. Pipeline of coroutines Each request creates 3 • Preprocessing • Maps URL to handler • Request Handlingwrite • This is the part you • Postprocessingresponse • Sends an HTTP Friday, March 30, 12
  • 8. Hello world Take five! class DemoHandler(WebMessageHandler):     def get(self):         self.set_body('Take five!')         return self.render() urls = [('^/brubeck', DemoHandler)] Friday, March 30, 12
  • 9. Hello world Take five! class DemoHandler(WebMessageHandler):     def get(self):         self.set_body('Take five!')         return self.render() urls = [('^/brubeck', DemoHandler)] @app.add_route('^/brubeck', method='GET') def foo(application, message):     body = 'Take five!'     return http_response(body, 200, 'OK', {}) Friday, March 30, 12
  • 10. Brubeck: routing Went with the usual style class NameHandler(WebMessageHandler):     def get(self, name):         ... def name_handler(application, message, name):     ... urls = [(r'^/class/(w+)$', NameHandler),         (r'^/fun/(?Pw+)$', name_handler)] • https://github.com/j2labs/brubeck/blob/master/demos/demo_urlargs.py Friday, March 30, 12
  • 11. Brubeck: templates Supports: Jinja2, Mako,Tornado or Mustache from brubeck.templating import Jinja2Rendering class DemoHandler(WebMessageHandler, Jinja2Rendering):     def get(self):         context = {             'name': 'J2 D2',         }         return self.render_template('success.html', **context) • https://github.com/j2labs/brubeck/blob/master/demos/demo_jinja2.py • https://github.com/j2labs/brubeck/blob/master/demos/demo_mustache.py Friday, March 30, 12
  • 12. Brubeck: auth (pt 1) • Simple example, using `web_authenticated` decorator: class DemoHandler(..., UserHandlingMixin): @web_authenticated def get(self):         context = {             'name': self.current_user.username,         }         return self.render_template('some.html', **context) • Also supports secure cookies • Routes users to login template • https://github.com/j2labs/brubeck/blob/master/demos/demo_login.py Friday, March 30, 12
  • 13. Brubeck: auth (pt 2) class BaseHandler(..., UserHandlingMixin):     def get_current_user(self):         user = None secret=self.application.cookie_secret         user_id = self.get_cookie('user_id', secret=secret)         if user_id:             return load_user(self.db_conn, username=user_id)         else:             username = self.get_argument('username')             password = self.get_argument('password')             if username:                 user = load_user(self.db_conn, username=username)         if not user or not user.check_password(password):             return         return user Friday, March 30, 12
  • 14. Brubeck: user • This what a Brubeck user model looks like class User(Document):     username = StringField(max_length=30, required=True)     password = StringField(max_length=128)     is_active = BooleanField(default=False)     last_login = LongField(default=curtime)     date_joined = LongField(default=curtime)     ... • Uses UUID for id field • Could use Mongo’s ObjectID if you prefer that • https://github.com/j2labs/brubeck/blob/master/brubeck/models.py Friday, March 30, 12
  • 15. Brubeck: data validation • Validation is easy >>> from brubeck.models import User >>> u = User(username='jd', is_active=True) >>> u.set_password('foo') >>> u.validate() >>> u.username = True >>> u.validate() Traceback (most recent call last): ... dictshield.base.ShieldException: Invalid value - username:True Friday, March 30, 12
  • 16. Databaseless modeling • This what a Brubeck user looks like as Python >>> user_instance.to_python() {     '_types': ['User'],     '_cls': 'User',     'username': u'jd',     'is_active': False,     'last_login': 1311718487532L,     'password': u'bcrypt|||salt|||hash',     'date_joined': 1311718487532L } Friday, March 30, 12
  • 17. Databaseless modeling • Persistence details are up to you # Mongo >>> db.users.save(u.to_python()) # Riak >>> user = bucket.new('user_key', data=u.to_python()) >>> user.store() # Memcached >>> mc["user_key"] = u.to_json() Friday, March 30, 12
  • 18. Brubeck: autoapi Automatic REST APIs from data models (!!) (Ben Beecher++) • Define a DictShield document (our model) • Define a QuerySet - Implements persistence • Dictionary based queryset is provided • Redis, Mongo and MySQL on the way • Subclass AutoAPIBase • Attach your model as `model` • Attach your queryset as `queries` • Register API for model in a Brubeck instance Friday, March 30, 12
  • 19. Brubeck: autoapi A Todo API # Define Todo model class Todo(Document):     completed = BooleanField(default=False)     deleted = BooleanField(default=False)     archived = BooleanField(default=False)     title = StringField(required=True)     ... # Add fields to handler class TodosAPI(AutoAPIBase):     queries = DictQueryset(db_conn={})     model = Todo # Register with Brubeck instance app.register_api(TodosAPI) Friday, March 30, 12
  • 20. Brubeck: autoapi $ curl -f -X POST -H "content-type: application/json" -d '{"text": "Watch more bsg", "order": 1}' http://localhost:6767/todo/ {     "_cls": "Todo",     "_id": "111b4bb7-55f5-441b-ba25-c7a4fd99442c",     "_types": [         "Todo"     ],     "done": false,     "order": 1,     "text": "Watch more bsg" } Friday, March 30, 12
  • 21. Todos: backbone.js AutoAPI works great with backbone.js ( https://github.com/j2labs/todos ) Friday, March 30, 12
  • 22. Questions ?? Brubeck: http://brubeck.io Code: https://github.com/j2labs/brubeck Mongrel2: http://mongrel.org DictShield: https://github.com/j2labs/dictshield Gevent: http://gevent.org Eventlet: http://eventlet.net Friday, March 30, 12