Python

Темы для изучения

  • Pip

  • Conda/Virtualenv

  • Djabgo

  • Django Admin

  • Django REST Framework

  • manage.py - shell, runserver, makemigrations, migrate, dbshell, createsuperuser

  • Debugging

  • Logging

  • Login & registration, JWT

  • Form/ModelForm

  • Production

  • Декомпозиция моделей, views

  • Metaprogramming. Динамическое создание классов DynamicClass = type('DynamicClass', (), {'spam': 'eggs'})

  • RTTI получаем информацию к внутренней структуре класса

  • Generators

  • Functions: callable, len, str, repr

  • Properties: __getitem__, __setitem__, __call__, __init__, __get__, __set__, __dict__, __str__ , __len__, __iter__

  • Декораторы (обертки) @decorate

  • Partial objects

  • Descriptors

  • Exceptions

  • None

  • Wsgi

  • Flask/Flask-AppBuilder

  • PEP8

  • Celery, a distributed task queue

  • Twisted - an event-driven networking engine written in Python and licensed under the open source

  • Percona Server for MySQL is a free, fully compatible, enhanced, and open source drop-in replacement for any MySQL database. It provides superior performance, scalability, and instrumentation.

//декларации внутри класса выполняются немедленно

class NormalClass: ... print('Loading NormalClass') ... spam = 'eggs' ... print('Done loading')

//динамическое создание класса

DynamicClass = type('DynamicClass', (), {'spam': 'eggs'})

//metaclass - класс который создает другие классы (metaprogramming динамич создание классов во время выполнения) //получаем информацию к внутренней структуре класса

class MetaClass(type): ... def __init__(cls, name, bases, attrs): ... print('Defining %s' % cls) ... print('Name: %s' % name) ... print('Bases: %s' % (bases,)) ... print('Attributes:') ... for (name, value) in attrs.items(): ... print(' %s: %r' % (name, value))

// empty class body

class SubClass(RealClass): # Notice there's no metaclass here. ... pass

// declarative syntax

class Contact(models.Model): """ Contact information provided when sending messages to the owner of the site. """ name = models.CharField(max_length=255) email = models.EmailField()

from django.db import models class Contact(models.Model): name = models.CharField(max_length=255) email = models.EmailField()

//в декларативном синтаксисе питон не гаранирует порядок выполнения, поэтому можно сделать свой класс аттрубута который бы отслеживал последовательность создания

class BaseAttribute(object): creation_counter = 1 def __init__(self): self.creation_counter = BaseAttribute.creation_counter BaseAttribute.creation_counter += 1

//__call__ когда объект используется как функция, например times = Multiplier(2) и затем times(5)

class Multiplier(object): ... def __init__(self, factor): ... self.factor = factor ... def __call__(self, value): ... return value * self.factor

// проверка может ли объект использовать как функция

b = Basic() callable(b)

// словари dictionaries

class CaseInsensitiveDict(dict): ... def __init__(self, **kwargs): ... for key, value in kwargs.items(): ... self[key.lower()] = value ... def __contains__(self, key): ... return super(CaseInsensitiveDict, self).__contains__(key.lower()) ... def __getitem__(self, key): ... return super(CaseInsensitiveDict, self).__getitem__(key.lower()) ... def __setitem__(self, key, value): ... super(CaseInsensitiveDict, self).__setitem__(key.lower(), value)

... d = CaseInsensitiveDict(SpAm='eggs') print('spam' in d) d['sPaM'] = 'burger'

//итераторы

class Fibonacci(object): ... def __init__(self, count): ... self.count = count ... def __iter__(self): ... a, b = 0, 1 ... for x in range(self.count): ... if x < 2: ... yield x ... else: ... c = a + b ... yield c ... a, b = b, c ... for x in Fibonacci(5): print(x)

//stop iteration

raise StopIteration

//new name for next

class FibonacciIterator(object): def __next__(self): ... next = __next__ #python3 name is next() by default

//generators - похожи на итераторы //sequence - набор объектов

//встроенная функция len() и ее реализация __len__(self) //проперти __getitem__(self) and __setitem__(self, value)

//переменное кол-во аргументов функции

def multiply(*args): ... total = 1 ... for arg in args: ... total *= arg ... return total ... multiply(2, 3) multiply(2, 3, 4, 5, 6)

//пара ключ значение в аргументах

def accept(**kwargs): ... for keyword, value in kwargs.items(): ... print("%s -> %r" % (keyword, value)) ... accept(foo='bar', spam='eggs')

//аргументы • Required arguments • Optional arguments • Excess positional arguments • Excess keyword arguments kwargs = {'b': 8, 'c': 9}

def complex_function(a, b=None, *c, **d):

//декораторы (обертки)

def decorate(func): ... print('Decorating %s...' % func.__name__) ... def wrapped(*args, **kwargs): ... print("Called wrapped function with args:", args) ... return func(*args, **kwargs) ... print('done!') ... return wrapped ... @decorate ... def test(a, b): ... return a + b

//partial object //descriptors

import datetime class CurrentDate(object): def __get__(self, instance, owner): return datetime.date.today() def __set__(self, instance, value): raise NotImplementedError("Can't change the current date.")

class Example(object): date = CurrentDate()

e = Example() e.date datetime.date(2008, 11, 24) e.date = datetime.date.today() # доступ к полю класса

//константа None

//

class Descriptor(object): ... def __init__(self, name): ... self.name = name ... def __get__(self, instance, owner): ... return instance.__dict__[self.name] ... def __set__(self, instance, value): ... instance.__dict__[self.name] = value ... class TestObject(object): attr = Descriptor('attr') ... >>>test = TestObject() >>>test.attr = 6 >>>test.attr 6

//переопределение toString()

def __str__(self): return '{} ({})'.format(self.title, self.year)

\ - перенос строки

//multiline comment

""" mmm """

//создать переменную класса

self.bucketlist_name = "Write world class code"

str(o) // вызов __str__(self) repr(o) //внутренее представление объекта (RTTI)

//выключить проверку для view

@csrf_exempt def snippet_list(request): pass

try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404)

Дополнительные источники

  • Книга по Python. Pro Python 3: Features and Tools for Professional Development

  • Асинхронное программирование https://habr.com/ru/company/ruvds/blog/475246/

  • 26 полезных приёмов и хитростей Python https://tproger.ru/translations/an-a-z-of-python-tricks/

  • http://www.youtube.com/watch?v=xKtv8_9HJNA&list=SP26BA8B9FC33789FF

  • ORM - sqlAlchemy http://www.sqlalchemy.org/

  • JSON message pack http://msgpack.org/

  • tornado/other lightweight frameworks http://www.tornadoweb.org/ WebServer

  • http://www.simeonfranklin.com/python-fundamentals/

  • http://www.simeonfranklin.com/python-fundamentals.pdf

  • http://docs.python.org/3/

  • http://docs.python.org/3/library/index.html

  • http://www.simeonfranklin.com/pro-django-class/

  • Flask + Jinja frameworks http://flask.pocoo.org/

  • Scrapy frame work - scraping using python

  • pep8 http://www.python.org/dev/peps/pep-0008/

  • обзор web фреймворков http://www.infoworld.com/d/application-development/pillars-python-six-python-web-frameworks-compared-169442?page=0,0

  • http://wiki.python.org/moin/WebFrameworks

  • http://www.pythondiary.com/blog/Feb.14,2012/too-many-micro-webframeworks.html

  • http://blog.fruiapps.com/2012/05/Choose-your-Python-Web-Framework-the-Hard-Way

  • blogs http://www.pythondiary.com/blog/

  • success stories http://www.revolunet.com/static/django-success-stories/#1

Last updated