Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.
Micro Django
or Lightweigth
Background
Django vs Flaskbottle
~14K
★★★★
★★★★
★★★★
★★
~13K
★★★★
★★★★
★★★★
★
ORM poo !!!
Templates poo !!!
38 Mb (25 Mb contrib)
70K...
Django Micro?
Structureless
manage.py
if __name__ == "__main__":
os.environ.setdefault( "DJANGO_SETTINGS_MODULE" , "settings")
from djan...
Structureless
Загрузка setting(https://docs.djangoproject.com/en/1.8/topics/settings/#using-settings-without-setting-djang...
Structureless
urlconf
urlpatterns = (
url(r'^$', lambda r: JsonResponse({ 'App': 'Simple’})),
)
Simple app
import os
import sys
from django.conf import settings
...
if not settings.configured:
settings.configure(
ROOT_...
OMG ORM! Failed!
Traceback:..
...
django.core.exceptions.ImproperlyConfigured: Unable to detect the app label
for model "T...
OMG ORM! Failed!
INSTALLED_APPS =(
...
'__main__'
),
Traceback:..
...
django.core.exceptions.ImproperlyConfigured: Unable ...
OMG ORM! Failed!
execute_from_command_line -> django.setup()
if not settings.configured:
settings.configure(
...
)
from dj...
OMG ORM! Successfully!
if not settings.configured:
settings.configure(
...
MIGRATION_MODULES ={'__main__': 'migrations'},
...
Through AppConfig
class App(AppConfig):
label = APP_LABEL
app = App('name', sys.modules[__name__])
...
INSTALLED_APPS=(
ap...
Through sys.modules
PyCon 2015 David Beazley - Modules and Packages
from types import ModuleType
import django
class Setti...
Freedom (- Django ORM)
...
from sqlite3 import dbapi2 as sqlite3
def get_db():
rv = sqlite3.connect('tasks.db', check_same...
SQLAlchemy
from sqlalchemy import create_engine
...
engine = create_engine('sqlite:///tasks.db', convert_unicode=True)
db_...
Peewee
import peewee
db = peewee.SqliteDatabase('tasks.db')
class Task(peewee.Model):
...
def view(request):
tasks = Task....
Route decorator
@app.route(r'^tasks/$', methods=['GET'])
def _all(request):
...
@app.route(r'^tasks/$', methods=['POST'])
...
Да
Нет
Ссылки
Вопросы???
Доклад Django Minus Django - http://www.youtube.com/watch?v=aFRH-oHcbn8
Мой репозиторий с примерами - ht...
Sie haben dieses Dokument abgeschlossen.
Lade die Datei herunter und lese sie offline.
Nächste SlideShare
Нагрузочное тестирование с помощью locust.io
Weiter
Nächste SlideShare
Нагрузочное тестирование с помощью locust.io
Weiter
Herunterladen, um offline zu lesen und im Vollbildmodus anzuzeigen.

Teilen

Micro(Lightweight) Django

Herunterladen, um offline zu lesen

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

Ähnliche Bücher

Kostenlos mit einer 30-tägigen Testversion von Scribd

Alle anzeigen

Ähnliche Hörbücher

Kostenlos mit einer 30-tägigen Testversion von Scribd

Alle anzeigen

Micro(Lightweight) Django

  1. 1. Micro Django or Lightweigth
  2. 2. Background
  3. 3. 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 andapp context
  4. 4. Django Micro?
  5. 5. 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)
  6. 6. Structureless Загрузка setting(https://docs.djangoproject.com/en/1.8/topics/settings/#using-settings-without-setting-django-settings-module) if not settings.configured: settings.configure( DEBUG=DEBUG, SECRET_KEY =SECRET_KEY, ROOT_URLCONF =__name__, ... )
  7. 7. Structureless urlconf urlpatterns = ( url(r'^$', lambda r: JsonResponse({ 'App': 'Simple’})), )
  8. 8. 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)
  9. 9. 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.
  10. 10. 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.
  11. 11. 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): ...
  12. 12. OMG ORM! Successfully! if not settings.configured: settings.configure( ... MIGRATION_MODULES ={'__main__': 'migrations'}, INSTALLED_APPS =( ... '__main__' ), ) ...
  13. 13. 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 ...
  14. 14. 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()
  15. 15. 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})
  16. 16. 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})
  17. 17. 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})
  18. 18. Route decorator @app.route(r'^tasks/$', methods=['GET']) def _all(request): ... @app.route(r'^tasks/$', methods=['POST']) @app.route(r'^tasks/add/$', methods=['POST']) def add(request): ...
  19. 19. Да Нет
  20. 20. Ссылки Вопросы??? Доклад 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
  • Zoom.Quiet

    Apr. 26, 2017

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

Aufrufe

Aufrufe insgesamt

5.820

Auf Slideshare

0

Aus Einbettungen

0

Anzahl der Einbettungen

4.840

Befehle

Downloads

11

Geteilt

0

Kommentare

0

Likes

1

×