Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Micro(Lightweight) Django

Micro(Lightweight) Django

Дмитрий Крюков

Мы привыкли к тому, что джанга это фулстек фреймворк, который диктует нам достаточно четкую проектную структуру, однако мы же всё же попробуем разрушить этот миф. Поиздеваемся над Django? Превратим его во бутылеподобный фреймворк (Flask, Bottle)? Даешь велосипеды!!!

Moscow Python Meetup

May 25, 2015
Tweet

More Decks by Moscow Python Meetup

Other Decks in Programming

Transcript

  1. Django vs Flaskbottle ~14K ★★★★ ★★★★ ★★★★ ★★ ~13K ★★★★

    ★★★★ ★★★★ ★ ORM poo !!! Templates poo !!! 38 Mb (25 Mb contrib) 70K SLOC 1.4 + 1.8 + 1.8 Mb (7.5 orm) 6 + 9 + 10 K SLOC (+ 50 orm request and app context
  2. Structureless manage.py if __name__ == "__main__": os.environ.setdefault( "DJANGO_SETTINGS_MODULE" , "settings")

    from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
  3. Simple app import os import sys from django.conf import settings

    ... if not settings.configured: settings.configure( ROOT_URLCONF =__name__, ... ) urlpatterns = (url(r'^$', lambda r: JsonResponse({ 'A simple app must be' : 'simple'})),) if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
  4. OMG ORM! Failed! Traceback:.. ... django.core.exceptions.ImproperlyConfigured: Unable to detect the

    app label for model "Task." Ensure that its module, "__main__", is located inside an installed app.
  5. OMG ORM! Failed! INSTALLED_APPS =( ... '__main__' ), Traceback:.. ...

    django.core.exceptions.ImproperlyConfigured: Unable to detect the app label for model "Task." Ensure that its module, "__main__", is located inside an installed app.
  6. OMG ORM! Failed! execute_from_command_line -> django.setup() if not settings.configured: settings.configure(

    ... ) from django.apps import apps apps.populate(settings.INSTALLED_APPS) class Model(models.Model): ...
  7. Through AppConfig class App(AppConfig): label = APP_LABEL app = App('name',

    sys.modules[__name__]) ... INSTALLED_APPS=( app ), ... class Task(models.Model): class Meta: app_label = APP_LABEL ...
  8. Through sys.modules PyCon 2015 David Beazley - Modules and Packages

    from types import ModuleType import django class Settings(ModuleType): DEBUG = False ... sys.modules['settings'] = Settings os.environ.setdefault( "DJANGO_SETTINGS_MODULE" , "settings") django.setup()
  9. Freedom (- Django ORM) ... from sqlite3 import dbapi2 as

    sqlite3 def get_db(): rv = sqlite3.connect('tasks.db', check_same_thread=False) rv.row_factory = sqlite3.Row return rv def view(request): db = get_db() cur = db.execute('SELECT * FROM task WHERE task.session_id=$1 order by id desc', [request.session.session_key, ]) tasks = cur.fetchall() return JsonResponse({task['id']: {'body': task['body'], 'title': task['title'], 'active': task['is_active']} for task in tasks})
  10. SQLAlchemy from sqlalchemy import create_engine ... engine = create_engine('sqlite:///tasks.db', convert_unicode=True)

    db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) class Task(Base): __tablename__ = 'task' ... def view(request): tasks = Task.query.filter(Task.session_id == request.session.session_key) return JsonResponse({task.id: {'body': task.body, 'title': task.title, 'active': task.is_active} for task in tasks})
  11. Peewee import peewee db = peewee.SqliteDatabase('tasks.db') class Task(peewee.Model): ... def

    view(request): tasks = Task.select().where(Task.session_id == request.session.session_key) return JsonResponse({task.id: {'body': task.body, 'title': task.title, 'active': task.is_active} for task in tasks})
  12. Ссылки Вопросы??? Доклад Django Minus Django - http://www.youtube.com/watch?v=aFRH-oHcbn8 Мой репозиторий

    с примерами - https://goo.gl/6q6IRP importd - https://goo.gl/SwzhLL Доклад Егора Назаркина - Flask: Гордость и предубеждение - https://goo.gl/i3Hv5E Обсуждение в блоге Ивана Сагалаева (маниакальный веблог) - http://goo.gl/Vh497y settings.configure - https://goo.gl/WfyTSE Benchmarks - http://goo.gl/pBpmmj, http://goo.gl/C8TFz5 PyCon 2015 David Beazley - Modules and Packages - http://www.youtube.com/watch?v=0oTh1CXRaQ0