Merken

Demystifying Mixins with Django

Zitierlink des Filmsegments
Embed Code

Automatisierte Medienanalyse

Beta
Erkannte Entitäten
Sprachtranskript
that it be but everyone I'm really excited to to be a juror by from this year and I'm really glad so many of you made it to the stop because it's friday so yeah cool so the mystifying makes sense with Django is somewhat of an opinionated talking is going to be about understanding what are makes sense and how they were and how to create your own makes sense in the context of Django framework and I'll be glad to answer all your questions by the end of this talk so my name is Ana and the simplest way to get in touch with me is my Twitter I work at potato and I absolutely love saying the
sentence but seriously potatoes an amazing company where we create all sorts of absolute GenGO and not only let's dive right in
sense are controlled way of adding functionality to class but makes sense are not
special language constructs this means there is no special keyword in Python point to some constant and say 0 this is a makes sense In fact Nixon's
just ordinary Python classes take a look at this short example it is a class called some and it has 1 method that does nothing will this is a useless makes and for obvious reasons let me draw your attention to 1 important bit over here our little makes him inherits from object and only from object if we are using new style Python classes so the take away from here is that makes sense or preferably not derived classes
mixes offer modularity and that's the main reason we want to use want to use them well so when we want to reuse that particular feature in a lot of different classes especially when this feature doesn't belong in any of the existing and that's why it makes sense should be narrow in scope in other words have 1 single responsibility they're not meant to be extended and they're not meant to be instantiated I
mentioned makes sense are good in creating modular designs so let's take a closer look at this the coupling constant imagine that we have an encapsulated that has 4 color coded features orange blue green and yellow so far so good imagine over time that your project grows bigger and we create new classes that encapsulate their own features at this point this code smells it's ugly there's something wrong with all those 4 classes because this yellow feature appears in all 4 of them and that someone copy-pasted so what we need to do in this case is to extract the yellow features and put it in a separate encapsulated so that the current and future classes can benefit from our newly created makes sense
and here comes the question how do we actually do that well in Python and not only the concept of makes sense is implemented using multiple inheritance and when we talk about multiple inheritance in Python the order of inheritance matters here's how we can
use and make sense say we have a class full that inherits from base full and some mixing you might think especially according to some naming conventions that base full acts as a base class and some makes sense is indeed a nevertheless we should be reading this code in the following manner some is a base class extended by peaceful extended by phone this might not be a problem if some mixing and base for not sharing extending or overriding any of the existing methods but if you're conscious that some mixing will be extending the method of of base for you should reverse the order will that looks much better to me an easy way to remember Python inheritance order is with is with 1 single arrows that goes all the way from right to left when you start chaining makes sense to be especially careful about your order so who has a hard about this I think like Django framework django someone from someone young man not man and grows in popularity think and that who has ever use class-based views that's more like a lot of people but if you didn't know some problems or give a short intro relation so here's a sniff that snippets of now here's a snippet from the official gender the condition it is a class this view that inherits from tinplate you and a templating view helps us render editing played that's all it does and all it asks for my is to configure the name of the team played class using Django is 1 typical use case where makes sense use where it makes sense to a very natural and so we're interested in plugging in over there and make sense yeah we know 2 things right now we know what are makes sense and how to use them so let's go ahead and write our own 1st makes sense a common use case
in web development is to protect some of our pages so we want to enforce our end users to authenticate before accessing the page was created makes that will check if the user is authenticated 1st thing we do which is a good class name login required mixing it inherits from object and replace it inside some our views about Wi-Fi although it might be placed almost anywhere we would like to check if the user is authenticated before we start processing the request you might know that or might not know that but 1 of the 1st methods to be called when processing the request is dispatched we use the same signature of the dispatch method is in the base view class and now it's time to do the proper checks so if you take a look at the lines 8 and 9 we say that the user is not authenticated raise a permission tonight exceptions and since we don't write any other and there is no way to out import packages let's go ahead and specify and the line number 2 that we import permission deny from jingle core exception 1 last thing to do is to handle the use case when the user is actually authenticated and we want to allow him or her to access the ultimate pH therefore it was called the Superman on dispatch and resume the work of the base method I lived up to you to provide Dobson tasks please do that so going back to our about you with plug-in login required makes and tell them it for works just like that not all the anonymous users are not allowed to trespass to the land of the super secret information of the about you that's all there is required to protect the view it's the very trivial example and very simplified but it demonstrates the mixing in here's how we described graphically our latest usage of a mixing the about you inheritable fronting played you and from London required makes sense and if you ever decide how well I wanna detailed view instead instead of a templated you will no problem and if you didn't see would help change on the slide is basically I have swapped the team played you with the detailed view and that's a good thing right because minimum effort is required to use a different view with no additional cost and this looks simple at least I hope it does to you does it yeah so I'm pretty sure how need of those makes sense but what if there is a different way there are tons of different ways but there aren't necessarily good for the best so this made me think how would I do it another way I might check of the user is authenticated right my be right in my view but that's a stupid idea for obvious reasons so I came up with this as you'll see also there stupid idea so I extended the played view and created a new class called login required complete view of stars to remind me of some abstract to factory the effect I and I made about view to inherit from it doesn't look that bad at the moment but it actually does because every single other view the number of which I extrapolating infinity if you want to have an old Czech will be extended the same way that's exactly the same problem we have discussed at the beginning we didn't solve anything which is continued to copy paste the Old Czech everywhere now take a look again
at this diagram it's elegant and simple all right so we
all agree that makes sense are fantastic how about looking a bit more insight
class-based views and some common class these views methods if we want to add a to a class based you using a makes sense we sometimes need to know a bit about the jangling journals was a request hits the team played you 1 of the 1st methods to be called is dispatch we have this 1 it figures out which is to be in which HTTP method to call is a big gap is at a cost so it is useful to override dispatched to provide a very early on before anything else happens to the request for example check if the user is logged in or has permission the next method get context data is also sometimes useful to be over it it passes keyword arguments to the team played context and so it is a way to add extra context to the views next 1 get tinplate names is a method called by render to response police all team plate names so it can be extended to add more flexibility in to the template names if you have a different mechanism of identifying those in your Django project so by now you probably should be angrily asking me how do I know all that because all I showed you was the simple example with the team play viewing it will need but this other lean know all of this will I be ingredient so here are some ways how you can learn more about the jingle class-based used so my personal approach is to go to jump right into the source code and it's easy to get your head around Django source code because it has docstrings and it's pretty well structured and but then of course there's a different approach you can start with jangled accommodation to read a bit more about the base classes of class-based views and not by accident Jango users makes sense to build the class views and you can read about them this you're out again I highly recommend to take a look at the Django class-based views and makes its source code because if you can't really run your hand your head around all those makes sense Django provides an example how to get started this will website C that called that UK is an awesome resource it aggregation 1 single place all the class-based used their math that's where they come from their hierarchy diagrams and source code so is really get and well structure a major go through all of this login required makes encode but in real life probably you don't bother implementing your own login required unless you really need to have a specific use case basically because you have jingle braces jingle braces is a package that aggregate's common makes sense that you will need in your project and they're structured in 3 categories x stars form and other makes sense if you have been using Django for some time you're probably familiar with those decorated what is required user passes task and permission required will I wish we had something similar in Django for class-based used well good news everyone
In Django 1 . 9 will get login required makes him user passes dust mixing and permission required makes sense yeah according to the road map the final 1 . 9 version will be ready to be released sometime in December and those free makes sense that shadow the original GenGO decorators where written during this year's Django Europe sprints in the evening after he gave the school talk so that's pretty cool someone was listening to the talk while I was babbling on the stage now let's get
a bit more evil and how about and some runtime magic so what I wanna do I wanna plug-ins behavior to my classes in the time dynamically I personally never had a use case where I would need that word let's try just for fun let me tell you a
story this is just a mixing and the mixing assumes that we have a name attribute and what it does is 1 ordinary print statement 0 yeah so you can see this is a python 2 and now let's introduce Mr. mass got and its name attribute 1 extra Class 1 attribute fairly simple now we entered the land of me to bring to life some of our classes so my number 12 we create an instance of the mask and his name is double the next line is the magic it modifies the basis of the mascot class and as the cute makes into it where mixing it dynamically then we tried to call the be huge method from the cute mixing on previously instantiated object and
what makes they meet the local I
emphasize that this works in Python to and we are also using old-style classes are not inheriting from object so bases was mutable back background spooky story the how about now how about if we are using Python free or we have new style classes isn't much of a difference in code well the print function is the print is a function let's see what we can do well we can't screw up as much as with Python 2 because base is is immutable but we can change the Dunja class attribute on an instance that we have called among and create a new type that includes the cute mixing and then make use of the the VQ and this will work
if you ever do that please make sure you do this for a very good reason and please provide plenty of documentation explaining the why and I have warned you
be careful when you decide to use makes sense because with great power comes great responsibility be aware of incompatible makes sense chaining too many makes sense and over doing makes sense has making it a nightmare to figure out these ecution flow same as we advise gains 100 lines long views functions and tons of decorators on your functions we also advise against class news that requires 6 makes sense to work you're probably doing something wrong and placing too much logic into your view layer for controller early so let's
recap what we have learned so far makes sense in Python are classes and should have 1 single responsibility semantically we think about makes sense as some blood in reusable functionality although mixes are makes in using inheritance they're not creating subtyping relations this means they don't adhere to lease scoffed principle from solid Liskov of principal says the following instances of base class can be replaced with instances of derived classes and it will make sense this statement doesn't hold for makes sense and that's why we say that makes sense are not creating a sub-typing relation I
hope I convinced you that mixes are pretty and use it to create therefore I strongly encourage you to go back to your views and start trading make sense to clean up your code thank you that you so if you want to
have again and you get any questions but get 1 to start with anyway and you say is 6 makes sense this too much for you but what about 3 of them this is the OK it depends on your use case and normally normally you would have liked to make sense is quite OK because you probably need a login required and then it has permission quite a common use case maybe you have an extra 1 is still going to be fine but you know the harder it gets to figure out where did you request flows so In this case I think they're kind of like the couple because you log in you know what is doing and has permission they both work with the dispatching then have an extra mixing that changes something in your contacts might be OK so free is still and full might be pushing it back contain more questions yes so back and what if you want to combine the functionality of sorrow maximum so what sort of the common would you like extending mixing Cluster mixing Saul composition composite minx incident of 1 they make soon I would always favor composition over inheritance I but I have seen use cases where mixands were actually extended so if you look into the source code of Django grace as they have 1 kind of base and so the have a base makes for a beer excess makes sense that is doing some of the basic stuff and then all the others they inherit so you can do that that's pretty valid but just be careful yeah 0 combining them by composition uh I'm not sure how would you do that so can't really give you more questions everyone's hungry but the latest serving food and now we might have to wait a minute anyway hi s think the talk at 1st found there was the the the greater of lectures and with the penalty use the greater harmony you can use and you can use also the going for processing is a very different from makes because small find the class that but there is this because most of animal moment I was thinking how is iteration within metaclasses and the and what it's good to you mix inform what a well would you use metaclasses for yes is I haven't use classes for creating sense so I can't freely so can I echo your question how would you use classes if you're creating makes sense for was you genetic set of using the unmixing now for having smaller the methods of which to a class like easy having metaclasses in the final decision on the final those classes are really with global on or more broad numbers of methods for the use of something maybe I'm confident around in this class and yeah I don't know much about meta classes so that may also problem yeah so definitely should take a look at this talk a learner actually about metaclasses but I'm not sure that the meta classes you can do the same stuff so at yeah definitely you can have some of your functionality separated into model classes that's what basically Django is doing so we have a metaclasses for us a set of functionality and then we have extra placed into it makes sense but I gotta try maybe I can put all this code into metaclasses and it will work no no no OK no think just and it the thanks for the talk and army since also used in are also popular in other contexts and dangled if you have any of the additional models which are outside of the jingle Quora components so if you're doing models you don't have makes sense obviously but if you are so we have that tinplate linear interview view layer and the model there so the view layer is the only place where I could see makes sense but then again have extra logic extra modules where you can use makes sense for your ordinary Python our structure so I can't give an exact his case but you might have been the needs to use makes sense but there that that's going to be already outside of Django thanks actually the connected at something and this 1 and if the new forms it's quite common today makes into like and date because all these weird things to influence thinking and more questions right to maybe we can do to you mentioned the these thank you and can theft
Maschinenschreiben
Twitter <Softwareplattform>
Kontextbezogenes System
Framework <Informatik>
Konstruktor <Informatik>
Lineares Funktional
Punkt
Betrag <Mathematik>
Rechter Winkel
Gamecontroller
Formale Sprache
Klasse <Mathematik>
Quick-Sort
Computeranimation
Chipkarte
Bit
Subtraktion
Klasse <Mathematik>
Einfache Genauigkeit
Objektklasse
Computeranimation
Einfache Genauigkeit
Objekt <Kategorie>
Methodenbank
Softwaretest
Endogene Variable
Wort <Informatik>
Methodenbank
Multiplikation
Punkt
Green-Funktion
Klasse <Mathematik>
Vererbungshierarchie
Projektive Ebene
Kantenfärbung
Ordnung <Mathematik>
Ordnung <Mathematik>
Code
Subtraktion
Momentenproblem
Extrempunkt
Klasse <Mathematik>
Zahlenbereich
Extrempunkt
Login
Service provider
Framework <Informatik>
Code
Computeranimation
Homepage
Task
Metropolitan area network
Speicherabzug
Vererbungshierarchie
Mixed Reality
Zeitrichtung
Gerade
Metropolitan area network
Soundverarbeitung
Vervollständigung <Mathematik>
Sichtenkonzept
Logarithmus
Vererbungshierarchie
Güte der Anpassung
Relativitätstheorie
Ausnahmebehandlung
Objektklasse
Elektronische Unterschrift
Unendlichkeit
Rechenschieber
Rechter Winkel
Geschlecht <Mathematik>
Konditionszahl
Web-Designer
Speicherabzug
Faktor <Algebra>
Information
Ordnung <Mathematik>
Bit
Mathematisierung
Klasse <Mathematik>
Hierarchische Struktur
Login
Task
Bildschirmmaske
Reelle Zahl
Endogene Variable
Vererbungshierarchie
Volumenvisualisierung
Datenstruktur
Schreib-Lese-Kopf
Umwandlungsenthalpie
Parametersystem
Kraftfahrzeugmechatroniker
Videospiel
Sichtenkonzept
Kategorie <Mathematik>
Güte der Anpassung
Zwei
Ähnlichkeitsgeometrie
Quellcode
Kontextbezogenes System
Diagramm
Ruhmasse
Projektive Ebene
Decodierung
Bit
Klasse <Mathematik>
Versionsverwaltung
Mixed Reality
Rechenzeit
Abschattung
Plug in
Wort <Informatik>
Login
Computeranimation
Videospiel
Befehl <Informatik>
Klasse <Mathematik>
Hochdruck
Zahlenbereich
Ruhmasse
Objektklasse
Computeranimation
Verdeckungsrechnung
Basisvektor
Mixed Reality
Gerade
Attributierte Grammatik
Instantiierung
Lineares Funktional
Subtraktion
Datentyp
Freeware
Güte der Anpassung
Klasse <Mathematik>
Hochdruck
Objektklasse
Service provider
Code
Computeranimation
Objekt <Kategorie>
Datentyp
Mixed Reality
Stützpunkt <Mathematik>
Attributierte Grammatik
Instantiierung
Stereometrie
Lineares Funktional
Befehl <Informatik>
Sichtenkonzept
Relativitätstheorie
Klasse <Mathematik>
Kontextbezogenes System
Datenfluss
Mathematische Logik
Computeranimation
Einfache Genauigkeit
Hauptideal
Endogene Variable
Gamecontroller
Vererbungshierarchie
Leistung <Physik>
Binäre Relation
Gerade
Leistung <Physik>
Instantiierung
Prozess <Physik>
Momentenproblem
Extrempunkt
Klasse <Mathematik>
Iteration
Zahlenbereich
Login
Mathematische Logik
Inzidenzalgebra
Code
Computeranimation
Fehlertoleranz
Informationsmodellierung
Bildschirmmaske
Code
Mixed Reality
Vererbungshierarchie
Zusammenhängender Graph
Datenstruktur
Lineares Funktional
Sichtenkonzept
Quellcode
Kontextbezogenes System
Modul
Quick-Sort
Meta-Tag
Entscheidungstheorie
Linearisierung
Menge

Metadaten

Formale Metadaten

Titel Demystifying Mixins with Django
Serientitel EuroPython 2015
Teil 08
Anzahl der Teile 173
Autor Balica, Ana
Lizenz CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 3.0 Unported:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben
DOI 10.5446/20072
Herausgeber EuroPython
Erscheinungsjahr 2015
Sprache Englisch
Produktionsort Bilbao, Euskadi, Spain

Technische Metadaten

Dauer 24:22

Inhaltliche Metadaten

Fachgebiet Informatik
Abstract Ana Balica - Demystifying Mixins with Django Mixins are a great way to keep an application decoupled. This talk is about building mixins and dissecting what's behing the mixin "magic" and that, in fact, there is no magic involved at all. The main focus will be on Django framework while digging into mixins. When using Django class-based views, mixins feel very natural. **Goal**: by the end of this talk, every developer should be confident about creating his or her own custom mixins. **Prerequisites:** - basic understanding of OOP principles and their application in Python - Django web framework Generally mixins in Python are pretty straight-forward, easy to create and use. Nevertheless a lot of developers stay away from them. I think attendees of this talk will be interested to learn that mixins are not that complex and their benefit is tremendous.
Schlagwörter EuroPython Conference
EP 2015
EuroPython 2015

Ähnliche Filme

Loading...