SlideShare a Scribd company logo
1 of 39
Priorities on
          model.save()
device = Device.objects.get(sn=‘1234567890’)
          device.barcode = ‘46262’
                device.save()
from django.db import models as db

class Device(db.Model):
    name = db.CharField(verbose_name=_("name"), max_length=255)
    parent = db.ForeignKey('self', verbose_name=_("parent device"),
        on_delete=db.SET_NULL,
        null=True, blank=True, default=None, related_name="child_set")
    model = db.ForeignKey(DeviceModel, verbose_name=_("model"),
        null=True, blank=True, default=None, related_name="device_set",
        on_delete=db.SET_NULL)
    sn = db.CharField(verbose_name=_("serial number"), max_length=255,
        unique=True, null=True, blank=True, default=None)
    barcode = db.CharField(verbose_name=_("barcode"), max_length=255,
        unique=True, null=True, blank=True, default=None)
    remarks = db.TextField(verbose_name=_("remarks"),
        help_text=_("Additional information."),
        blank=True, default="")
    boot_firmware = db.CharField(verbose_name=_("boot firmware"),
        null=True, blank=True, max_length=255)
    hard_firmware = db.CharField(verbose_name=_("hardware firmware"),
            null=True, blank=True, max_length=255)
# ...
SNMP
            plugin
   Puppet             SSH
   plugin            plugin


Manual
 data       Device            …
 entry
Loss of information

12:01          12:02          12:37


SNMP           Puppet         SNMP
  • Device        • Device      • Device
    has             has           has
    a CPU1          a Xeon        a CPU1
                    E5645 @
                    2.4 GHz
device.save(priority=plugin.priority)

 12:01        P=   12:02     P=   12:37      P=
              10             20              10

SNMP               Puppet         SNMP
   • Device           • Device      • Attribute
     has                has           change
     a CPU1             a Xeon        ignored
                        E5645 @     • Device
                        2.4 GHz       still has
                                      a Xeon
                                      E5645 @
                                      2.4 GHz
Manual data entry by a human
            user



          P=
          100
           0
from django.db import models as db

class Device(db.Model):
    name = db.CharField(verbose_name=_("name"), max_length=255)
    parent = db.ForeignKey('self', verbose_name=_("parent device"),
        on_delete=db.SET_NULL,
        null=True, blank=True, default=None, related_name="child_set")
    model = db.ForeignKey(DeviceModel, verbose_name=_("model"),
        null=True, blank=True, default=None, related_name="device_set",
        on_delete=db.SET_NULL)
    sn = db.CharField(verbose_name=_("serial number"), max_length=255,
        unique=True, null=True, blank=True, default=None)
    barcode = db.CharField(verbose_name=_("barcode"), max_length=255,
        unique=True, null=True, blank=True, default=None)
    remarks = db.TextField(verbose_name=_("remarks"),
        help_text=_("Additional information."),
        blank=True, default="")
    boot_firmware = db.CharField(verbose_name=_("boot firmware"),
        null=True, blank=True, max_length=255)
    hard_firmware = db.CharField(verbose_name=_("hardware firmware"),
            null=True, blank=True, max_length=255)
# ...
Multiple inheritance
class Article(Localized, Titled, Slugged,
        Categorized, Taggable, AbstractArticle,
        TimeTrackable, EditorTrackable,
        Publishable, Commentable,
DisplayCounter,
        HasShowContent):

   class Meta:
       verbose_name = _("article")
       verbose_name_plural = _("articles")
class EditorTrackable(db.Model):
    created_by = db.ForeignKey(
        EDITOR_TRACKABLE_MODEL,
        verbose_name=_("created by"),
        null=True, blank=True, default=None,
        related_name='+', on_delete=db.SET_NULL,
        limit_choices_to={'is_staff’
            if EDITOR_TRACKABLE_MODEL is User
            else 'user__is_staff': True})
    modified_by = db.ForeignKey(
        EDITOR_TRACKABLE_MODEL,
        verbose_name=_("modified by"),
        null=True, blank=True, default=None,
        related_name='+', on_delete=db.SET_NULL,
        limit_choices_to={'is_staff’
            if EDITOR_TRACKABLE_MODEL is User
            else 'user__is_staff': True})
class EditorTrackable(db.Model):
    created_by = db.ForeignKey(
        EDITOR_TRACKABLE_MODEL,
        verbose_name=_("created by"),
        null=True, blank=True, default=None,
        related_name='+', on_delete=db.SET_NULL,
        limit_choices_to={'is_staff’
            if EDITOR_TRACKABLE_MODEL is User
            else 'user__is_staff': True})
    modified_by = db.ForeignKey(
        EDITOR_TRACKABLE_MODEL,
        verbose_name=_("modified by"),
        null=True, blank=True, default=None,
        related_name='+', on_delete=db.SET_NULL,
        limit_choices_to={'is_staff’
            if EDITOR_TRACKABLE_MODEL is User
            else 'user__is_staff': True})
Monkey patching
Traceback (most recent call last):
  ...
TypeError: save() got an unexpected keyword
argument 'priority'
from django.db import models

models.Model._lck_save = models.Model.save

models.Model.save = (lambda self,
    force_insert=False, force_update=False,
    using=None, *args, **kwargs:
        self._lck_save(force_insert,
            force_update, using)
)
Null
data['INFRA2']['MANAGERS']['MANAGER'][0]['POWERLEVEL']
# bad solution 1
if 'INFRA2' in d:
  if 'MANAGERS' in d['INFRA2’]:
    if 'MANAGER' in d['INFRA2']['MANAGERS']:
      if len(d['INFRA2']['MANAGERS']):
        if 'POWERLEVEL' in d['INFRA2']['MANAGERS']
            ['MANAGER'][0]:
          return d['INFRA2']['MANAGERS']['MANAGER']
              [0]['POWERLEVEL’]
return None

# bad solution 2
data.get('INFRA2', {}).get('MANAGERS',
  {}).get('MANAGER', {}).get(0, []).get('POWERLEVEL’)

# bad solution 3
try:
    return data['INFRA2']['MANAGERS']['MANAGER'][0]
      ['POWERLEVEL']
except (KeyError, IndexError):
    return None
>>> from null import Null
>>> Null.any_attribute
Null
>>> Null['any_key’]
Null
>>> Null[123]
Null
>>> Null.any_method()
Null
>>> bool(Null)
False

# solution 4
>>> from null import nullify
>>> data = nullify(data)
>>> data['INFRA2']['MANAGERS']['MANAGER'][0]
     ['POWERLEVEL’]
Null
locals()
def messages(request):
    template='messages/list.html'
    user = request.user
    message_list = Message.objects.filter(
        owner=user)
    return render_to_response(
        template,
        {'message_list': message_list,
         'user': user},
        context_instance=RequestContext(request))
def messages(request):
    template='messages/list.html'
    user = request.user
    message_list = Message.objects.filter(
        owner=user)
    return render_to_response(
        template,
        {'message_list': message_list,
         'user': user},
        context_instance=RequestContext(request))



@view
def messages(request):
    template = 'messages/list.html’
    user = request.user
    message_list = Message.objects.filter(
        owner=user)
    return locals()
Class context

GENDER_MALE = 0
GENDER_FEMALE = 1
GENDER_NOT_SPECIFIED = 2
GENDER_CHOICES = (
    (GENDER_MALE, _('male')),
    (GENDER_FEMALE, _('female')),
    (GENDER_NOT_SPECIFIED, _('not specified')),
)

class User(db.Model):
    gender = db.IntegerField(_("gender"),
        choices=GENDER_CHOICES)
Class context

class Gender(Choices):

    male = Choice(_("male"))
    female = Choice(_("female"))
    not_specified = Choice(_("not specified"))

class User(db.Model):
    gender = ChoiceField(_("gender"), choices=Gender,
            default=Gender.not_specified)
Class context

class Gender(Choices):
    _ = Choices.Choice
    male = _("male")
    female = _("female")
    not_specified = _("not specified")

class User(db.Model):
    gender = ChoiceField(_("gender"), choices=Gender,
            default=Gender.not_specified)
Operators

class User(db.Model):
    gender = ChoiceField(_("gender"), choices=Gender,
            default=Gender.not_specified)

   def greet(self):
       if self.gender == Gender.male:
           return "Hi, boy.”
       elif self.gender == Gender.female:
           return "Hello, girl.”
       else:
           return "Hey there, user!"
Operators

class Gender(Choices):
    male = _("male") << {'hello': 'Hi, boy.’}
    female = _("female") << {'hello': 'Hello, girl.’}
    not_specified = _("not specified") << {
            'hello': 'Hey there, user!’}

class User(models.Model):
    gender = ChoiceField(choices=Gender,
            default=Gender.not_specified)

   def greet(self):
       return self.gender.hello
I can do this all day
Conditional fields/methods

class ArticlePage(DisplayCounter, HasShowContent):
    article = db.ForeignKey(Article,
            verbose_name=_("article"))
    page_number = db.PositiveIntegerField(
            verbose_name=_("page number"),
            default=None, null=True, blank=True)
    #...

   if settings.CUSTOMER_PAID_FOR_PRINTING_SUPPORT:
       def print(self):
           ...
Injecting context by
               execfile
# settings.py
from lck.django import current_dir_support
execfile(current_dir_support)

# ...
STATIC_ROOT = CURRENT_DIR + 'static'
I regret nothing
I regret nothing

More Related Content

What's hot

Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friendkikoalonsob
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF Luc Bors
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?Maksym Hopei
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Magicke metody v Pythonu
Magicke metody v PythonuMagicke metody v Pythonu
Magicke metody v PythonuJirka Vejrazka
 
What's new in Doctrine
What's new in DoctrineWhat's new in Doctrine
What's new in DoctrineJonathan Wage
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapHoward Lewis Ship
 
Recent Changes to jQuery's Internals
Recent Changes to jQuery's InternalsRecent Changes to jQuery's Internals
Recent Changes to jQuery's Internalsjeresig
 

What's hot (20)

Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Functional es6
Functional es6Functional es6
Functional es6
 
Phactory
PhactoryPhactory
Phactory
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Magicke metody v Pythonu
Magicke metody v PythonuMagicke metody v Pythonu
Magicke metody v Pythonu
 
What's new in Doctrine
What's new in DoctrineWhat's new in Doctrine
What's new in Doctrine
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
 
Recent Changes to jQuery's Internals
Recent Changes to jQuery's InternalsRecent Changes to jQuery's Internals
Recent Changes to jQuery's Internals
 
Laravel
LaravelLaravel
Laravel
 

Similar to I regret nothing

Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Тестирование и 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
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
テストデータどうしてますか?
テストデータどうしてますか?テストデータどうしてますか?
テストデータどうしてますか?Yuki Shibazaki
 
Advanced python
Advanced pythonAdvanced python
Advanced pythonEU Edge
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In PyEric ShangKuan
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperGary Hockin
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your CodeDrupalDay
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialjbellis
 

Similar to I regret nothing (20)

Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
 
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
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
テストデータどうしてますか?
テストデータどうしてますか?テストデータどうしてますか?
テストデータどうしてますか?
 
Advanced python
Advanced pythonAdvanced python
Advanced python
 
DataMapper
DataMapperDataMapper
DataMapper
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
 

Recently uploaded

Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FIDO Alliance
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandIES VE
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsLeah Henrickson
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfFIDO Alliance
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfFIDO Alliance
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPTiSEO AI
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Patrick Viafore
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?Paolo Missier
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 

Recently uploaded (20)

Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 

I regret nothing

  • 1.
  • 2. Priorities on model.save() device = Device.objects.get(sn=‘1234567890’) device.barcode = ‘46262’ device.save()
  • 3. from django.db import models as db class Device(db.Model): name = db.CharField(verbose_name=_("name"), max_length=255) parent = db.ForeignKey('self', verbose_name=_("parent device"), on_delete=db.SET_NULL, null=True, blank=True, default=None, related_name="child_set") model = db.ForeignKey(DeviceModel, verbose_name=_("model"), null=True, blank=True, default=None, related_name="device_set", on_delete=db.SET_NULL) sn = db.CharField(verbose_name=_("serial number"), max_length=255, unique=True, null=True, blank=True, default=None) barcode = db.CharField(verbose_name=_("barcode"), max_length=255, unique=True, null=True, blank=True, default=None) remarks = db.TextField(verbose_name=_("remarks"), help_text=_("Additional information."), blank=True, default="") boot_firmware = db.CharField(verbose_name=_("boot firmware"), null=True, blank=True, max_length=255) hard_firmware = db.CharField(verbose_name=_("hardware firmware"), null=True, blank=True, max_length=255) # ...
  • 4. SNMP plugin Puppet SSH plugin plugin Manual data Device … entry
  • 5. Loss of information 12:01 12:02 12:37 SNMP Puppet SNMP • Device • Device • Device has has has a CPU1 a Xeon a CPU1 E5645 @ 2.4 GHz
  • 6. device.save(priority=plugin.priority) 12:01 P= 12:02 P= 12:37 P= 10 20 10 SNMP Puppet SNMP • Device • Device • Attribute has has change a CPU1 a Xeon ignored E5645 @ • Device 2.4 GHz still has a Xeon E5645 @ 2.4 GHz
  • 7. Manual data entry by a human user P= 100 0
  • 8.
  • 9. from django.db import models as db class Device(db.Model): name = db.CharField(verbose_name=_("name"), max_length=255) parent = db.ForeignKey('self', verbose_name=_("parent device"), on_delete=db.SET_NULL, null=True, blank=True, default=None, related_name="child_set") model = db.ForeignKey(DeviceModel, verbose_name=_("model"), null=True, blank=True, default=None, related_name="device_set", on_delete=db.SET_NULL) sn = db.CharField(verbose_name=_("serial number"), max_length=255, unique=True, null=True, blank=True, default=None) barcode = db.CharField(verbose_name=_("barcode"), max_length=255, unique=True, null=True, blank=True, default=None) remarks = db.TextField(verbose_name=_("remarks"), help_text=_("Additional information."), blank=True, default="") boot_firmware = db.CharField(verbose_name=_("boot firmware"), null=True, blank=True, max_length=255) hard_firmware = db.CharField(verbose_name=_("hardware firmware"), null=True, blank=True, max_length=255) # ...
  • 10.
  • 12. class Article(Localized, Titled, Slugged, Categorized, Taggable, AbstractArticle, TimeTrackable, EditorTrackable, Publishable, Commentable, DisplayCounter, HasShowContent): class Meta: verbose_name = _("article") verbose_name_plural = _("articles")
  • 13. class EditorTrackable(db.Model): created_by = db.ForeignKey( EDITOR_TRACKABLE_MODEL, verbose_name=_("created by"), null=True, blank=True, default=None, related_name='+', on_delete=db.SET_NULL, limit_choices_to={'is_staff’ if EDITOR_TRACKABLE_MODEL is User else 'user__is_staff': True}) modified_by = db.ForeignKey( EDITOR_TRACKABLE_MODEL, verbose_name=_("modified by"), null=True, blank=True, default=None, related_name='+', on_delete=db.SET_NULL, limit_choices_to={'is_staff’ if EDITOR_TRACKABLE_MODEL is User else 'user__is_staff': True})
  • 14.
  • 15. class EditorTrackable(db.Model): created_by = db.ForeignKey( EDITOR_TRACKABLE_MODEL, verbose_name=_("created by"), null=True, blank=True, default=None, related_name='+', on_delete=db.SET_NULL, limit_choices_to={'is_staff’ if EDITOR_TRACKABLE_MODEL is User else 'user__is_staff': True}) modified_by = db.ForeignKey( EDITOR_TRACKABLE_MODEL, verbose_name=_("modified by"), null=True, blank=True, default=None, related_name='+', on_delete=db.SET_NULL, limit_choices_to={'is_staff’ if EDITOR_TRACKABLE_MODEL is User else 'user__is_staff': True})
  • 16.
  • 17. Monkey patching Traceback (most recent call last): ... TypeError: save() got an unexpected keyword argument 'priority'
  • 18. from django.db import models models.Model._lck_save = models.Model.save models.Model.save = (lambda self, force_insert=False, force_update=False, using=None, *args, **kwargs: self._lck_save(force_insert, force_update, using) )
  • 19.
  • 21. # bad solution 1 if 'INFRA2' in d: if 'MANAGERS' in d['INFRA2’]: if 'MANAGER' in d['INFRA2']['MANAGERS']: if len(d['INFRA2']['MANAGERS']): if 'POWERLEVEL' in d['INFRA2']['MANAGERS'] ['MANAGER'][0]: return d['INFRA2']['MANAGERS']['MANAGER'] [0]['POWERLEVEL’] return None # bad solution 2 data.get('INFRA2', {}).get('MANAGERS', {}).get('MANAGER', {}).get(0, []).get('POWERLEVEL’) # bad solution 3 try: return data['INFRA2']['MANAGERS']['MANAGER'][0] ['POWERLEVEL'] except (KeyError, IndexError): return None
  • 22. >>> from null import Null >>> Null.any_attribute Null >>> Null['any_key’] Null >>> Null[123] Null >>> Null.any_method() Null >>> bool(Null) False # solution 4 >>> from null import nullify >>> data = nullify(data) >>> data['INFRA2']['MANAGERS']['MANAGER'][0] ['POWERLEVEL’] Null
  • 23.
  • 25. def messages(request): template='messages/list.html' user = request.user message_list = Message.objects.filter( owner=user) return render_to_response( template, {'message_list': message_list, 'user': user}, context_instance=RequestContext(request))
  • 26. def messages(request): template='messages/list.html' user = request.user message_list = Message.objects.filter( owner=user) return render_to_response( template, {'message_list': message_list, 'user': user}, context_instance=RequestContext(request)) @view def messages(request): template = 'messages/list.html’ user = request.user message_list = Message.objects.filter( owner=user) return locals()
  • 27.
  • 28. Class context GENDER_MALE = 0 GENDER_FEMALE = 1 GENDER_NOT_SPECIFIED = 2 GENDER_CHOICES = ( (GENDER_MALE, _('male')), (GENDER_FEMALE, _('female')), (GENDER_NOT_SPECIFIED, _('not specified')), ) class User(db.Model): gender = db.IntegerField(_("gender"), choices=GENDER_CHOICES)
  • 29. Class context class Gender(Choices): male = Choice(_("male")) female = Choice(_("female")) not_specified = Choice(_("not specified")) class User(db.Model): gender = ChoiceField(_("gender"), choices=Gender, default=Gender.not_specified)
  • 30. Class context class Gender(Choices): _ = Choices.Choice male = _("male") female = _("female") not_specified = _("not specified") class User(db.Model): gender = ChoiceField(_("gender"), choices=Gender, default=Gender.not_specified)
  • 31.
  • 32. Operators class User(db.Model): gender = ChoiceField(_("gender"), choices=Gender, default=Gender.not_specified) def greet(self): if self.gender == Gender.male: return "Hi, boy.” elif self.gender == Gender.female: return "Hello, girl.” else: return "Hey there, user!"
  • 33. Operators class Gender(Choices): male = _("male") << {'hello': 'Hi, boy.’} female = _("female") << {'hello': 'Hello, girl.’} not_specified = _("not specified") << { 'hello': 'Hey there, user!’} class User(models.Model): gender = ChoiceField(choices=Gender, default=Gender.not_specified) def greet(self): return self.gender.hello
  • 34.
  • 35. I can do this all day
  • 36. Conditional fields/methods class ArticlePage(DisplayCounter, HasShowContent): article = db.ForeignKey(Article, verbose_name=_("article")) page_number = db.PositiveIntegerField( verbose_name=_("page number"), default=None, null=True, blank=True) #... if settings.CUSTOMER_PAID_FOR_PRINTING_SUPPORT: def print(self): ...
  • 37. Injecting context by execfile # settings.py from lck.django import current_dir_support execfile(current_dir_support) # ... STATIC_ROOT = CURRENT_DIR + 'static'