Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Hunting For Treasure In Django
Search
Seb
May 28, 2015
Technology
200
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Hunting For Treasure In Django
Seb
May 28, 2015
Transcript
41 slides
Hunting for Treasure in Django Sebastian Vetter @elbaschid
Who Am I?
Sebastian • Django & Python Developer • Backend Engineer @
Mobify • github/twitter: elbaschid
What's The Treasure?
Awesome Django Features • Forms, • Views, • Models, •
the ORM, or • other commonly used APIs.
But They Are Boring
Real Treasure
What Does That Mean? • Useful pieces of Django code.
• Considered public API. • Documentation is available (sort of). • Mainly used within Django itself.
My Hunting Strategy • Digging through the Django source. •
Hanging out with Funkybob. • Learning from other great people.
What I'll Do • Show a few "hidden" treasures. •
Explain what they do. • Look at examples.
cached_property
Where is it useful? • Time or compute heavy properties
on a class. • Synchronous calls to remote servers. • Used more than once, e.g. code & template.
What does it do? • It's a decorator. • Caches
the return value. • Lives as long as the instance.
It looks like this class MyObject(object): @cached_property def compute_heavy_method(self): ...
return result
Imagine A Color API class Color(object): def __init__(self, hex): self.hex
= hex def _request_colour_name(self, hex): print "Requesting #{}".format(hex) rsp = requests.get(API_ENDPOINT.format(hex)) return rsp.json()[0].get("title") @property def name(self): return self._request_colour_name(self.hex)
Here's the problem • Using the name attribute will call
the API • Every time!
Here's the problem >>> c = Color('ffffff') >>> c.name Requesting
#ffffff white >>> c.name Requesting #ffffff white
Possible solution @property def name(self): if self._name is None: self._name
= self._request_colour_name(self.hex) return self._name
Or you can use cached_property from django.utils.functional import cached_property @cached_property
def name(self): return self._request_colour_name(self.hex)
Using the cached property >>> c = Color('ffffff') >>> c.name
Requesting #ffffff white >>> c.name white
Isn't That Great
All you Need To Know from django.utils.functional import cached_property •
Only cached for the lifetime of the instance. • Be careful with querysets. • Django docs • Source
import_string
Where is it useful? • Make a class or function
configurable. • Allow loading class/function from string.
What does it do? • Takes dotted path to a
class or function. • Loads it. • Returns the class or function object.
It looks like this from django.utils.module_loading import import_string get_func =
import_string('requests.get') print get_func # <function requests.api.get> get_func('https://google.ca') # <Response [200]>
# settings.py UPLOAD_VALIDATION_PIPELINE = [ 'my_project.uploads.validators.is_tarball', 'my_project.uploads.validators.has_readme_file', 'my_project.uploads.validators.has_no_!']
All you Need To Know from django.utils.module_loading import import_string •
Imports a class or function from a dotted path. • Django docs • Source
lazy and lazy_property
Where is it useful? • Accessing settings at parse time,
e.g. class attributes. • Translating strings outside of a view. • Translations in the settings module.
Here's a problem class UserSignupView(CreateView): ... success_url = reverse('signup-confirmed')
How can we fix it? from django.utils.functional import lazy class
UserSignupView(CreateView): ... success_url = lazy(reverse('signup-confirmed'), unicode)
Lazy Django • The Settings object is lazy. • Several
helpers have lazy siblings: • reverse_lazy • ugettext_lazy • Not sure what lazy_property is useful for.
All you Need To Know from django.utils.functional import lazy from
django.utils.functional import SimpleLazyObject • Imports a class or function from a dotted path. • Django docs • Source
RequestFactory
Where Is It Useful? • Testing request related code. •
Mocking will be too much work. • Using the test client doesn't make sense.
Create GET Request from django.test import RequestFactory request = RequestFactory().get('/some/path')
# with a query string query_params = {"token": "secret-token"} request = RequestFactory().get('/some/path', data=query_params)
Create POST Request from django.test import RequestFactory post_params = {'username':'testuser',
'password':'supersecret'} request = RequestFactory().post('/login', data=post_params)
All you Need To Know from django.test import RequestFactory •
Creates a fake request for given URL. • Can handle all HTTP methods. • Will save you some mocking work. • Django docs • Source
The Treasure Is Yours
Thanks! Questions? • www.roadsi.de • @elbaschid • github.com/elbaschid Slides: https://speakerdeck.com/elbaschid
More Decks by Seb
See All by Seb
Double Click - Continue Building Better CLIs
elbaschid
0
510
I Can Be A Speaker, So Can You
elbaschid
0
350
Click - PyCaribbean 2017 - Puerto Rico
elbaschid
0
480
Conferencing - Engineering Meeting
elbaschid
1
59
Show & Tell - PyCon US 2016 Summary
elbaschid
1
120
Click: A Pleasure To Write, A Pleasure To Use
elbaschid
0
710
Hunting for Treasure in Django
elbaschid
1
760
Moby & The Beanstalk
elbaschid
1
570
Docker In Production - A War Story
elbaschid
1
330
Other Decks in Technology
See All in Technology
Kiro を使うコツ (頼み方、覚えさせ方、任せ方) | 目指せ Kiro マスター 09
inariku
PRO
3
170
Go初心者のクラウドエンジニアが、デプロイを通して旨味を知っていく話
ryudai
1
230
Context Ontology Accelerator 入門 (業務データの意味を、AI エージェントに渡す)
inariku
PRO
3
690
MCPでネットワーク障害調査を自動化する前に直すべき3つのこと
yama3133
0
430
BALLAS Technology Deck
ballas_inc
0
680
並列度を下げたら速くなった — go build の重複コンパイルを実測で見る
tomoaki25
2
1.3k
Kiro Web 入門 (サインインから、頼み方、PR の受け取り、クラウドの決まりまで) | 目指せ Kiro マスター 04
inariku
PRO
2
130
20261113_JAWS_Osaka
takuyay0ne
0
530
お風呂場をサーバルームにしよう
yusuke427
0
200
落とし穴にハマってわかった 開発生産性を測るときに気をつけたいこと
munakata
3
240
高品質と高スピードを支える品質のシフトレフトのアプローチ
goyoki
4
1.4k
長い仕事を任せる (Workflows、クラウドセッション、Kiro Web) | 目指せ Kiro マスター 10
inariku
PRO
3
210
Featured
See All Featured
Designing Powerful Visuals for Engaging Learning
tmiket
1
660
エンジニアに許された特別な時間の終わり
watany
109
250k
YesSQL, Process and Tooling at Scale
rocio
174
15k
How to train your dragon (web standard)
notwaldorf
96
6.9k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
1.1k
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
6
930
[RailsConf 2023] Rails as a piece of cake
palkan
59
7.1k
Fantastic passwords and where to find them - at NoRuKo
philnash
53
4k
Organizational Design Perspectives: An Ontology of Organizational Design Elements
kimpetersen
PRO
1
880
KATA
mclloyd
PRO
35
16k
The Limits of Empathy - UXLibs8
cassininazir
2
780
Done Done
chrislema
187
17k