SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Python for Web
                                by Alex Radchenko and Yegor Nazarkin,
                                                www.mediasapiens.co




twitter: @dixon_che, @nimnull
Who we are?
              Web solutions

                                         Flexible
      Pythonic
                       Development
           Neat                        OpenSource
                  E-commerce
                                     Mobile
Why .py?
Project grows
Why .py?
Become complicated
Why .py?
Deadlines!
Why .py?
Conception suddenly changed!
Why .py?
Result
Why .py?
  Or in JAVA world        tones of X
                                           ML
            ads
         hre g
h    of t izin
  ell on
  syn chr




      modules                                   ning
       repo?                            ve rsio
                          l ibra ries
                     no
Why .py?
   A bit of PHP?     Built-in and library APIs are
                                                   a
                     disorganized mess
          c ti ons
S QL inje
                                                       core bugs



not transitive




                                                       silent e rrors
Why .py?
Python is a very new language; in fact it was released by its
designer, Guido Van Rossum, in February 1991 while working
for CWI also known as Stichting Mathematisch Centrum.


•Interpreted, interactive, object-oriented
•It incorporates modules, exceptions, dynamic data types
and classes.
•Extensible in C or C++.
•Portable across all major hardware and software platforms.
Why .py?
Zen
      Language designed for readability and productivity of the
      end-up developer

Modules
      http://pypi.python.org

Huge community
      https://github.com/languages/Python
Why .py?                                  Explicit is better than implicit.
                                             Beautiful is better than ugly.
                                                 Flat is better than nested.
                                                             Readability counts.

 class Mediator(object):
     def __init__(self):
         self.signals = {}

     def signal(self, signal_name, *args, **kwargs):
         for handler in self.signals.get(signal_name, []):
             handler(*args, **kwargs)

     def connect(self, signal_name, receiver):
         handlers = self.signals.setdefault(signal_name, [])
         handlers.append(receiver)

     def disconnect(self, signal_name, receiver):
         self.signals[signal_name].remove(receiver)




                                                               The Zen of Python
Why .py?                                  Explicit is better than implicit?
                                             Beautiful is better than ugly?
                                                 Flat is better than nested?
 class Mediator {
   private boolean slotFull = false;
   private int number;
                                                       Readability counts?
   public synchronized void storeMessage(int num) {
     while (slotFull == true) {
       try {
         wait();
       }
       catch (InterruptedException e) { }
     }
     slotFull = true;
     number = num;
     notifyAll();
   }
   public synchronized int retrieveMessage() {
     // no message to retrieve
     while (slotFull == false)
       try {
         wait();
       }
       catch (InterruptedException e) { }
     slotFull = false;
     notifyAll();
     return number;
   }
 }


                                                         Does the Java have a Zen?
Why .py?
Good old spaghetti async style
   init: function(msg, obj) {
       chrome.pageAction.show(tabId);
       me.api.authorize(function() {
           me.api.checkDoc(msg.doc,
               function(data) {
                   obj.get(msg);
                   me.api.realtime.getUpdates({
                       tabId: tabId,
                       ids: [msg.doc.id],
                       callbackOk: function(data) {
                           if (data.event == 'connected') {
                                obj.get(msg);
                           }
                           port.postMessage({_action: 'update', data: data});
                       },
                       callbackError: function(data) {
                           obj.get(msg);
                       }
                   });
               },
               function(data) {
                   console.warn('Bad document', data.responseText);
               }
           );
       });
   },
Why .py?
And how we see the same things
     @tornado.web.asynchronous
     @gen.engine
     def get(self, user_id=None):
         if user_id is not None:
             user = yield gen.Task(User.get, user_id)
             self.set_secure_cookie('uid', unicode(user._id))
             response = user.as_dict()
         else:
             count = yield gen.Task(User.objects.count)
             if not count:
                 yield gen.Task(User.create({'nickname': "John Doe"}).save)
             users = yield gen.Task(User.objects.find, None)
             response = [u.as_dict() for u in users]
         self.write(json_encode(response))
         self.finish()
Why .py?                          Need functional?

                      stripped_list = [line.strip() for line in line_list
List comprehensions                    if line != ""]



Generators            def generate_ints(N):
                          for i in range(N):
                              yield i

                      val = (yield i)



Built-ins             map(upper, ['sentence', 'fragment'])

                      [upper(s) for s in ['sentence', 'fragment']]




                      filter(is_even, range(10))

                      [x for x in range(10) if is_even(x)]



                      total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
Why .py?              Decorators

           from functools import wraps

           def my_decorator(func):

               @wraps(func)
               def wrapper(*args, **kwargs):
                   # we can do smth with arguments
                   print “args:”, args
                   response = func(*args, **kwargs)
                   # end with the method result too
               return wrapper


           @my_decorator
           def func1(arg1):
               return "inside func1()", arg1


           >>>print func1(‘test’)

           “args: [‘test’]”
           “inside func1() test”
Why .py?               Descriptor’s magic

           An object attribute with "binding behavior", one whose
           attribute access has been overridden by methods in the
           descriptor protocol.
           class RevealAccess(object):


               def __init__(self, initval=None, name='var'):
                   self.val = initval
                   self.name = name

               def __get__(self, obj, objtype):
                   print 'Retrieving', self.name
                   return self.val

               def __set__(self, obj, val):
                   print 'Updating' , self.name
                   self.val = val

           class MyClass(object):
               x = RevealAccess(10, 'var "x"')
               y = 5

           >>> m = MyClass()
           >>> m.x
           Retrieving var "x"
           10
Why .py?                                    Metaclasses

                              Metaclasses are deeper magic than 99% of users should
                              ever worry about. If you wonder whether you need them,
                              you don't (the people who actually need them know with
                              certainty that they need them, and don't need an
                              explanation about why)
                                                                           Tim Peters

  class Singleton(type):
      instance = None
      def __call__(cls, *args, **kw):
          if cls.instance is None:
              cls.instance = super(Singleton, cls).__call__(*args, **kw)
          return cls.instance


   class Foo(object):
       __metaclass__ = Singleton
Why .py?                              Need an IDE?


 Convenient way:                     Hacker’s choices are:
 PyCharm                             VIM
 NinjaIDE                            Emacs
 WingIDE

               Hipster’s choice:
               Sublime Text (written in python, actually)
Why .py?


     But the C is much more faster!
Why .py?

       Stop! The main problem sounds like:
             the development speed,
              developer’s motivation



Have we just mentioned that the most critical parts could be written in C/C++?
The Web
The Web in the details
Fast prototyping
The Web in the details
OMG! WTF? It handles loading!
The Web in the details
The Freedom of Choice:

  •   General approach on request/response processing
  •   Reusable modules/parts
  •   Template engines
  •   ORM (RDBMS, noSQL)
  •   Caching backends
  •   Messages queue APIs (ZMQ, RabbitMQ)
  •   Localization out of the box
  •   Great documentation! Testing frameworks
  •   Debugging and profiling
The Web in the details
Batteries:

       nimnull@fox-laptop:~$ easy_install <battery name>
The Web in the details
Logic-less templates:

  •   Django Template Engine
  •   Tornado Template Engine
  •   Jinja2
  •   Mako
  •   Genshi


  • Inheritance
  • Extending
  • Compiled to the Python
The Web in the details
DB storage backends:

  • General approach of DBAPI for RDBMS
  • Arguments escaping, type checks
  • noSQL (if you expect it)

  •   SQLAlchemy (postgres, mysql, oracle, mssql)
  •   MongoKit
  •   Mongoengine
  •   CouchDbKit
The Web in the details
Asynchronous:

  • Tornado
  • twisted.web
  • gevent

  • epoll (linux), kqueue (BSD)
  • Spaghetti? No Way! (Promise/Deffered)
Success story, bro
  Pinterest                  Disqus         Quora

              Spotify       Instagram       Bitbucket

       OpenStack
                                    FriendFeed
                        Dropbox
UA Community
 http://citypy.org/           http://ua.pycon.org/

                        Kyiv
                      Kharkiv
                        Lviv
                     Donetsk
                Odessa (py.drinkups)
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
Andrey Breslav
 

Was ist angesagt? (20)

Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Grammarware Memes
Grammarware MemesGrammarware Memes
Grammarware Memes
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
Metaprogramming in julia
Metaprogramming in juliaMetaprogramming in julia
Metaprogramming in julia
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Using Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard IIUsing Python3 to Build a Cloud Computing Service for my Superboard II
Using Python3 to Build a Cloud Computing Service for my Superboard II
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded Python
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better Java
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Learn How to Master Solr1 4
Learn How to Master Solr1 4Learn How to Master Solr1 4
Learn How to Master Solr1 4
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
Advance python
Advance pythonAdvance python
Advance python
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 

Andere mochten auch (7)

GAE - плюсы/минусы/подводные камни
GAE - плюсы/минусы/подводные камниGAE - плюсы/минусы/подводные камни
GAE - плюсы/минусы/подводные камни
 
Inter-process data exchange in Python
Inter-process data exchange in PythonInter-process data exchange in Python
Inter-process data exchange in Python
 
Chaplin.js in real life
Chaplin.js in real lifeChaplin.js in real life
Chaplin.js in real life
 
Rest in flask
Rest in flaskRest in flask
Rest in flask
 
Flask, rest and data
Flask, rest and dataFlask, rest and data
Flask, rest and data
 
Flask, гордость и предубеждение
Flask, гордость и предубеждениеFlask, гордость и предубеждение
Flask, гордость и предубеждение
 
Kharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backendKharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backend
 

Ähnlich wie обзор Python

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
Garth Gilmour
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 

Ähnlich wie обзор Python (20)

Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Java
JavaJava
Java
 
The Joy Of Ruby
The Joy Of RubyThe Joy Of Ruby
The Joy Of Ruby
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Oop java
Oop javaOop java
Oop java
 
Python for dummies
Python for dummiesPython for dummies
Python for dummies
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedIn
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptx
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Python basic
Python basicPython basic
Python basic
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
From Java to Python: beating the Stockholm syndrome
From Java to Python: beating the Stockholm syndromeFrom Java to Python: beating the Stockholm syndrome
From Java to Python: beating the Stockholm syndrome
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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...
 
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
 
"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 ...
 
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
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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)
 
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...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

обзор Python

  • 1. Python for Web by Alex Radchenko and Yegor Nazarkin, www.mediasapiens.co twitter: @dixon_che, @nimnull
  • 2. Who we are? Web solutions Flexible Pythonic Development Neat OpenSource E-commerce Mobile
  • 8. Why .py? Or in JAVA world tones of X ML ads hre g h of t izin ell on syn chr modules ning repo? ve rsio l ibra ries no
  • 9. Why .py? A bit of PHP? Built-in and library APIs are a disorganized mess c ti ons S QL inje core bugs not transitive silent e rrors
  • 10. Why .py? Python is a very new language; in fact it was released by its designer, Guido Van Rossum, in February 1991 while working for CWI also known as Stichting Mathematisch Centrum. •Interpreted, interactive, object-oriented •It incorporates modules, exceptions, dynamic data types and classes. •Extensible in C or C++. •Portable across all major hardware and software platforms.
  • 11. Why .py? Zen Language designed for readability and productivity of the end-up developer Modules http://pypi.python.org Huge community https://github.com/languages/Python
  • 12. Why .py? Explicit is better than implicit. Beautiful is better than ugly. Flat is better than nested. Readability counts. class Mediator(object): def __init__(self): self.signals = {} def signal(self, signal_name, *args, **kwargs): for handler in self.signals.get(signal_name, []): handler(*args, **kwargs) def connect(self, signal_name, receiver): handlers = self.signals.setdefault(signal_name, []) handlers.append(receiver) def disconnect(self, signal_name, receiver): self.signals[signal_name].remove(receiver) The Zen of Python
  • 13. Why .py? Explicit is better than implicit? Beautiful is better than ugly? Flat is better than nested? class Mediator { private boolean slotFull = false; private int number; Readability counts? public synchronized void storeMessage(int num) { while (slotFull == true) { try { wait(); } catch (InterruptedException e) { } } slotFull = true; number = num; notifyAll(); } public synchronized int retrieveMessage() { // no message to retrieve while (slotFull == false) try { wait(); } catch (InterruptedException e) { } slotFull = false; notifyAll(); return number; } } Does the Java have a Zen?
  • 14. Why .py? Good old spaghetti async style init: function(msg, obj) { chrome.pageAction.show(tabId); me.api.authorize(function() { me.api.checkDoc(msg.doc, function(data) { obj.get(msg); me.api.realtime.getUpdates({ tabId: tabId, ids: [msg.doc.id], callbackOk: function(data) { if (data.event == 'connected') { obj.get(msg); } port.postMessage({_action: 'update', data: data}); }, callbackError: function(data) { obj.get(msg); } }); }, function(data) { console.warn('Bad document', data.responseText); } ); }); },
  • 15. Why .py? And how we see the same things @tornado.web.asynchronous @gen.engine def get(self, user_id=None): if user_id is not None: user = yield gen.Task(User.get, user_id) self.set_secure_cookie('uid', unicode(user._id)) response = user.as_dict() else: count = yield gen.Task(User.objects.count) if not count: yield gen.Task(User.create({'nickname': "John Doe"}).save) users = yield gen.Task(User.objects.find, None) response = [u.as_dict() for u in users] self.write(json_encode(response)) self.finish()
  • 16. Why .py? Need functional? stripped_list = [line.strip() for line in line_list List comprehensions if line != ""] Generators def generate_ints(N): for i in range(N): yield i val = (yield i) Built-ins map(upper, ['sentence', 'fragment']) [upper(s) for s in ['sentence', 'fragment']] filter(is_even, range(10)) [x for x in range(10) if is_even(x)] total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
  • 17. Why .py? Decorators from functools import wraps def my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): # we can do smth with arguments print “args:”, args response = func(*args, **kwargs) # end with the method result too return wrapper @my_decorator def func1(arg1): return "inside func1()", arg1 >>>print func1(‘test’) “args: [‘test’]” “inside func1() test”
  • 18. Why .py? Descriptor’s magic An object attribute with "binding behavior", one whose attribute access has been overridden by methods in the descriptor protocol. class RevealAccess(object): def __init__(self, initval=None, name='var'): self.val = initval self.name = name def __get__(self, obj, objtype): print 'Retrieving', self.name return self.val def __set__(self, obj, val): print 'Updating' , self.name self.val = val class MyClass(object): x = RevealAccess(10, 'var "x"') y = 5 >>> m = MyClass() >>> m.x Retrieving var "x" 10
  • 19. Why .py? Metaclasses Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why) Tim Peters class Singleton(type):     instance = None     def __call__(cls, *args, **kw):         if cls.instance is None:             cls.instance = super(Singleton, cls).__call__(*args, **kw)         return cls.instance  class Foo(object):      __metaclass__ = Singleton
  • 20. Why .py? Need an IDE? Convenient way: Hacker’s choices are: PyCharm VIM NinjaIDE Emacs WingIDE Hipster’s choice: Sublime Text (written in python, actually)
  • 21. Why .py? But the C is much more faster!
  • 22. Why .py? Stop! The main problem sounds like: the development speed, developer’s motivation Have we just mentioned that the most critical parts could be written in C/C++?
  • 24. The Web in the details Fast prototyping
  • 25. The Web in the details OMG! WTF? It handles loading!
  • 26. The Web in the details The Freedom of Choice: • General approach on request/response processing • Reusable modules/parts • Template engines • ORM (RDBMS, noSQL) • Caching backends • Messages queue APIs (ZMQ, RabbitMQ) • Localization out of the box • Great documentation! Testing frameworks • Debugging and profiling
  • 27. The Web in the details Batteries: nimnull@fox-laptop:~$ easy_install <battery name>
  • 28. The Web in the details Logic-less templates: • Django Template Engine • Tornado Template Engine • Jinja2 • Mako • Genshi • Inheritance • Extending • Compiled to the Python
  • 29. The Web in the details DB storage backends: • General approach of DBAPI for RDBMS • Arguments escaping, type checks • noSQL (if you expect it) • SQLAlchemy (postgres, mysql, oracle, mssql) • MongoKit • Mongoengine • CouchDbKit
  • 30. The Web in the details Asynchronous: • Tornado • twisted.web • gevent • epoll (linux), kqueue (BSD) • Spaghetti? No Way! (Promise/Deffered)
  • 31. Success story, bro Pinterest Disqus Quora Spotify Instagram Bitbucket OpenStack FriendFeed Dropbox
  • 32. UA Community http://citypy.org/ http://ua.pycon.org/ Kyiv Kharkiv Lviv Donetsk Odessa (py.drinkups)
  • 33.