SlideShare a Scribd company logo
1 of 20
Download to read offline
Micro Django
or Lightweigth
Background
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
Django Micro?
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)
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__,
...
)
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_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)
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.
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.
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):
...
OMG ORM! Successfully!
if not settings.configured:
settings.configure(
...
MIGRATION_MODULES ={'__main__': 'migrations'},
INSTALLED_APPS =(
...
'__main__'
),
)
...
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
...
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()
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})
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})
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})
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):
...
Да
Нет
Ссылки
Вопросы???
Доклад 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

More Related Content

What's hot

Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Tsuyoshi Yamamoto
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Evgeny Nikitin
 
New features in Performance Schema 5.7 in action
New features in Performance Schema 5.7 in actionNew features in Performance Schema 5.7 in action
New features in Performance Schema 5.7 in actionSveta Smirnova
 
テストデータどうしてますか?
テストデータどうしてますか?テストデータどうしてますか?
テストデータどうしてますか?Yuki Shibazaki
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 
groovy databases
groovy databasesgroovy databases
groovy databasesPaul King
 
Testing orm based code
Testing orm based codeTesting orm based code
Testing orm based codeViktor Turskyi
 
Using Perl Stored Procedures for MariaDB
Using Perl Stored Procedures for MariaDBUsing Perl Stored Procedures for MariaDB
Using Perl Stored Procedures for MariaDBAntony T Curtis
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스PgDay.Seoul
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace PatternDiego Fleury
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsRebecca Murphey
 
PostgreSQL (2) by Aswin
PostgreSQL (2) by AswinPostgreSQL (2) by Aswin
PostgreSQL (2) by AswinAgate Studio
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196Mahmoud Samir Fayed
 

What's hot (20)

Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014
 
New features in Performance Schema 5.7 in action
New features in Performance Schema 5.7 in actionNew features in Performance Schema 5.7 in action
New features in Performance Schema 5.7 in action
 
テストデータどうしてますか?
テストデータどうしてますか?テストデータどうしてますか?
テストデータどうしてますか?
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
Sequelize
SequelizeSequelize
Sequelize
 
Swing database(mysql)
Swing database(mysql)Swing database(mysql)
Swing database(mysql)
 
Testing orm based code
Testing orm based codeTesting orm based code
Testing orm based code
 
Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
 
Using Perl Stored Procedures for MariaDB
Using Perl Stored Procedures for MariaDBUsing Perl Stored Procedures for MariaDB
Using Perl Stored Procedures for MariaDB
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
 
Msql
Msql Msql
Msql
 
Beyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS AppsBeyond the DOM: Sane Structure for JS Apps
Beyond the DOM: Sane Structure for JS Apps
 
PostgreSQL (2) by Aswin
PostgreSQL (2) by AswinPostgreSQL (2) by Aswin
PostgreSQL (2) by Aswin
 
Batch processing Demo
Batch processing DemoBatch processing Demo
Batch processing Demo
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196
 

Similar to Micro(Lightweight) Django

Behind the curtain - How Django handles a request
Behind the curtain - How Django handles a requestBehind the curtain - How Django handles a request
Behind the curtain - How Django handles a requestDaniel Hepper
 
Hello click click boom
Hello click click boomHello click click boom
Hello click click boomsymbian_mgl
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и DjangoMoscowDjango
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserHoward Lewis Ship
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1DjangoCon2008
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance DjangoDjangoCon2008
 
Welcome, Java 15! (Japanese)
Welcome, Java 15! (Japanese)Welcome, Java 15! (Japanese)
Welcome, Java 15! (Japanese)Logico
 
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docxOrdering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docxhopeaustin33688
 
rsyslog v8: more than just syslog!
rsyslog v8: more than just syslog!rsyslog v8: more than just syslog!
rsyslog v8: more than just syslog!Yury Bushmelev
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYCMike Dirolf
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to CeleryIdan Gazit
 

Similar to Micro(Lightweight) Django (20)

Behind the curtain - How Django handles a request
Behind the curtain - How Django handles a requestBehind the curtain - How Django handles a request
Behind the curtain - How Django handles a request
 
What's new in Django 1.2?
What's new in Django 1.2?What's new in Django 1.2?
What's new in Django 1.2?
 
Hello click click boom
Hello click click boomHello click click boom
Hello click click boom
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
Welcome, Java 15! (Japanese)
Welcome, Java 15! (Japanese)Welcome, Java 15! (Japanese)
Welcome, Java 15! (Japanese)
 
Geo django
Geo djangoGeo django
Geo django
 
Django Show
Django ShowDjango Show
Django Show
 
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docxOrdering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
 
rsyslog v8: more than just syslog!
rsyslog v8: more than just syslog!rsyslog v8: more than just syslog!
rsyslog v8: more than just syslog!
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Lecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptLecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptesrabilgic2
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 

Recently uploaded (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Lecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptLecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).ppt
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 

Micro(Lightweight) Django

  • 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
  • 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. 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. Structureless urlconf urlpatterns = ( url(r'^$', lambda r: JsonResponse({ 'App': 'Simple’})), )
  • 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. 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. 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. 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. OMG ORM! Successfully! if not settings.configured: settings.configure( ... MIGRATION_MODULES ={'__main__': 'migrations'}, INSTALLED_APPS =( ... '__main__' ), ) ...
  • 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. 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. 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. 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. 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. 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): ...
  • 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