обзор Python

979 views

Published on

Quick introduction to the sugar features of the python language and it's abilities to build the web

Published in: Technology

обзор Python

  1. 1. Python for Web by Alex Radchenko and Yegor Nazarkin, www.mediasapiens.cotwitter: @dixon_che, @nimnull
  2. 2. Who we are? Web solutions Flexible Pythonic Development Neat OpenSource E-commerce Mobile
  3. 3. Why .py?Project grows
  4. 4. Why .py?Become complicated
  5. 5. Why .py?Deadlines!
  6. 6. Why .py?Conception suddenly changed!
  7. 7. Why .py?Result
  8. 8. Why .py? Or in JAVA world tones of X ML ads hre gh of t izin ell on syn chr modules ning repo? ve rsio l ibra ries no
  9. 9. Why .py? A bit of PHP? Built-in and library APIs are a disorganized mess c ti onsS QL inje core bugsnot transitive silent e rrors
  10. 10. Why .py?Python is a very new language; in fact it was released by itsdesigner, Guido Van Rossum, in February 1991 while workingfor CWI also known as Stichting Mathematisch Centrum.•Interpreted, interactive, object-oriented•It incorporates modules, exceptions, dynamic data typesand classes.•Extensible in C or C++.•Portable across all major hardware and software platforms.
  11. 11. Why .py?Zen Language designed for readability and productivity of the end-up developerModules http://pypi.python.orgHuge community https://github.com/languages/Python
  12. 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. 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. 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. 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. 16. Why .py? Need functional? stripped_list = [line.strip() for line in line_listList 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. 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. 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. 19. Why .py? Metaclasses Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you dont (the people who actually need them know with certainty that they need them, and dont 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. 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. 21. Why .py? But the C is much more faster!
  22. 22. Why .py? Stop! The main problem sounds like: the development speed, developer’s motivationHave we just mentioned that the most critical parts could be written in C/C++?
  23. 23. The Web
  24. 24. The Web in the detailsFast prototyping
  25. 25. The Web in the detailsOMG! WTF? It handles loading!
  26. 26. The Web in the detailsThe 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. 27. The Web in the detailsBatteries: nimnull@fox-laptop:~$ easy_install <battery name>
  28. 28. The Web in the detailsLogic-less templates: • Django Template Engine • Tornado Template Engine • Jinja2 • Mako • Genshi • Inheritance • Extending • Compiled to the Python
  29. 29. The Web in the detailsDB 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. 30. The Web in the detailsAsynchronous: • Tornado • twisted.web • gevent • epoll (linux), kqueue (BSD) • Spaghetti? No Way! (Promise/Deffered)
  31. 31. Success story, bro Pinterest Disqus Quora Spotify Instagram Bitbucket OpenStack FriendFeed Dropbox
  32. 32. UA Community http://citypy.org/ http://ua.pycon.org/ Kyiv Kharkiv Lviv Donetsk Odessa (py.drinkups)
  33. 33. Questions?

×