SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

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 friend
kikoalonsob
 
Magicke metody v Pythonu
Magicke metody v PythonuMagicke metody v Pythonu
Magicke metody v Pythonu
Jirka Vejrazka
 
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
Codecamp Romania
 

Mais procurados (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
 

Semelhante a I regret nothing

From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
Advanced python
Advanced pythonAdvanced python
Advanced python
EU Edge
 
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
Luis Curo Salvatierra
 

Semelhante 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

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
panagenda
 
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
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
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
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

I regret nothing

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