SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
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

Contenu connexe

Similaire à 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
 

Similaire à 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
 

Dernier

Dernier (20)

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, ...
 
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...
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
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
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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
 
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
 
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...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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)
 
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...
 

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