SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere Àhnliche Inhalte

Was ist angesagt?

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
 
Phactory
PhactoryPhactory
Phactorychriskite
 
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
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12Stephan Hochdörfer
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORMAlex Gaynor
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database apiViswanath Polaki
 
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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With StyleGabriele Lana
 
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
 
DataMapper
DataMapperDataMapper
DataMapperYehuda Katz
 
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
 

Ähnlich wie 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
 

KĂŒrzlich hochgeladen

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

KĂŒrzlich hochgeladen (20)

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

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'