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

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 

Recently uploaded (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 

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