SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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 a 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 a 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
 

Último

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Último (20)

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

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'