SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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?
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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'