検索 - みる会図書館

検索対象: Two Scoops of Django Best Practices for Django 1.8

Two Scoops of Django Best Practices for Django 1.8から 525件ヒットしました。

Two Scoops of Django Best Practices for Django 1.8


73.3. ・ ん / ″ P ル 化 g 襯 ア / 雇 ぉ TIP: The Zen of Python At the command line, do the following: python —c import this' What you'll see is the Zen グ 2 ん 〃 , an eloquently-expressed set of guiding principles for the design of the Python programming language ・ 13.3 Limit Processing in TempIates lhe less processing you try to do in your templates, the better. lhis is particularly a problem when it comes tO queries and iteration performed in the template layer. \Mhenever you iterate over a queryset in a template, ask yourself the f()llowlng questions: ① How large is the queryset? Looping over gigantic querysets in your templates is almost always a bad idea. ② How large are the objects being retrieved? Are 砠 the fields needed in this template? 3 During each iteration ofthe loop, how much processing occurs? If any warning bells go 0 伍 in your head, then there's probably a better way to rewrite your WARNING: Why Not Just Cache? template code. 773 a 30-second commercial during the Super Bow1. "Free pints of ice cream for the first million Suspend your disbelief for a moment and pretend that the nutty duo behind Two Scoops ran Let's no 、 explore some examples oftemplate code that can be rewritten more effciently.. some quick run time analysi s, and refactoring. You can save yourselfa 10t ofworkby mentally tracing through your template code, doing you cache, you should first try to attack the root of the problem. Sometimes you can Just cache away your template inefflciencies. %at's fine, but before

Two Scoops of Django Best Practices for Django 1.8


C み 孕 7. ・ Coding S り ん EXAMPLE 1.4 patterns url(regex=t&add/$ ー view=views. add—topping, name='add—toppingt) , Note that we are referring to the name argument 0f u rl ( ) here, not the actual URL typed into the browser. Dashes in actual URLs are fine (). g. regex= ・ ådd-toppi ng/$ ・ ). 1.6.3 Use Underscores in TempIate 引 0 ( k Names Rather Than Dashes the same reasons as using underscores in pattern names, 、 recommend using un¯ derscores when defining names oftemplate blocks: in this case they're more PYthonic and more editor-friendly. 1.7 Choose JS, HTML, and CSS StyIe Guides JavaScript StyIe Guides UnIike python which has one official style guide, there is no official JavaScript style guide. ln- stead, a number of unoffcial JS style guides have been created by various individuals and/or compames: idiomatic. js: Principles ofWriting Consistent, ldiomatic JavaScript https://github. com/rwaldron/idiomatic . js/ Pragmatic. js code style guidelines https: //github. com/madrobby/pragmatic ・ js AirbnbJavaScript Style Guide https: //github. com/ai rbnb/javascript Node.js StyIe Guide https: //github. com/fetixge/node-style-guide Code Conventions for the JavaScript Programming Language http://javascript . crockford . com/code. htmt 70

Two Scoops of Django Best Practices for Django 1.8


C 4 ア / 7. ・ 0 ″ 4 〃 ノ / 加 D 厩 4 ん 化 カ げ Fortunately, through query expressions Django provides a way to make this more eff1Cient and race—condition free: EXAMPLE 7 ・ 4 from django. db. modets import from modets . customers import Customer customers = Customer. objects. fitter(scoops—ordered——gt=F('store—visits つ ) What this does is use the database itself to perform the comparison. Under the hood, Django is running something that probably 100k like: EXAMPLE 7.5 SELECT ☆ from customers_customer where scoops—ordered > store—visits ( ~ le Expressions should be in your t00 旧 t. Flhey increase the performance and stability of projects ・ https://docs. djangoproject . com/en/l. 8/ref/models/expressions/ 7.4.2 Database Functions ln Django 1.8 we were given the ability tO easily use common database functions such as UP¯ LENGTH() , and SUBSTR(). OfaII the LOWER() , COALESCE() , CONCAT() , PER ( ) , advanced query t001S provided by Django, these are our favorites. For that matter' it's one ofour favorite things about the 1.8 release. 、 Mhy? ① Very easy to use, either on new projects or existing projects. ② Database functions 砠 ow us to move some ofthe logic 伝 om Python to the database. FIhis can be a performance bOOSter, as processing data in Python is not as fast as processing data in a datab ase. ② Database functions are implemented differently per database, but Django's ORM abstracts this away. Code we write using them on PostgreSQJ. , will work on MYSQJJ or SQLite3. 6

Two Scoops of Django Best Practices for Django 1.8


EXAMPLE IO. 工 2 { # templates/ftavors/—ftavor—search. htmt # } { % comment % } Usage: { % include "ftavors/—flavor—search. htmt" % } { % endcomment % } く form action=tt{% urt "flavor_listtt % } ” method=!'GET"> く input name='lq'! / > <button type="submit">search く /button> </form> TIP: Specify the Form Target in Search Fo 「 ms We so take care to specify the URL in the form action, because we've found that search forms are often included ⅲ several pages. This is why we prefix them with and create them in such a way as tO be included in other templates. Once we get past overriding the Li stVi ew ー s get-que ryset ( ) method, the rest of this ex- ample is just a simple HTML form. We like this kind of simplicity. 10.6 Using Just django. views. generic. View lt's entirely possible to build a project Just using dj ango ・ vi ews. gene ri c. Vi ew for all the views. lt's not as extreme as one might think. For example, ifwe 100k at the official Django docu- mentations introduction tO class-based views (http: //2scoops. C0/1.8—using—cbvs), we can see the approach is very close tO hOW function-based views are written. ln fact, we high- lighted this two chapters ago in subsection 8 ユ 督 Ⅲ Simplest Views' because it's important. lmagme instead Of 、 vriting function-based views with nested-ifs representing different HTTP methods or class-b ased views where the HTTP methods are hidden behind get-context-data ( ) and f0 rm-va li d ( ) methods, they are readily accessible to developers. lmagine so mething like: EXAMPLE IO. from dj ango. shortcuts import get_object—or—4Ø4 735

Two Scoops of Django Best Practices for Django 1.8


70.2. ・ & ル 石 Ⅲ ″ C. 召 ln programming, a mixin is a class that provides functionality tO be inherited, but isn't meant for instantiation on its ( ) 、 Ⅵ 1. ln programming languages with multiple inheritance, mixins can be used to add enhanced functionality and behavior to classes. can use the po 、 0f mixins t() compose our () 、 vie 、 classes for our l)jango apps. using m1Xins t0 compose our 0 、 V1e 、 classes, we recommend these ofinheritance provided Kenneth Love. 田 rules 応 Ⅱ ow Python's method resolution order, which in the most simplistic definition po s sible, proceeds 伝 om le 仕 to right: ① FIhe base view classes provided by Django 4 / go to the right. 3 Mixins should inherit 伝 om Python's built-in object type. ② Mixins go to the le of the base view. context super(FreshFruitMixin, def get—context—data(setf, **kwargs) : ctass FreshFruitMixin(object) : from dj ango. views. generic import Temp1ateView EXAMPLE IO. Example of the rules in action : ctass FruityFtavorView(FreshFruitMixin, Temp1ateView) : return context context["has—fresh_fruitt'] = True setf) . get—context—data(**kwargs) 727 FinaIIy, FreshFruitMixin inherits 伝 om object (rule 3 ). and properties will execute correctly.. 1 ) , and to its le 仕 we place the FreshFrui tMi xi n (rule 2 ). lhis waywe 燔 ow that our methods Since TemptateVi ew is the base uew class provided by Django, it goes on the far right (rule Mixin and TempIateView. ln our rather silly example, the Frui tyFIavorVi ew class inherits 伝 om both FreshFrui t— temptate_name "fruity—ftavor. htmt't

Two Scoops of Django Best Practices for Django 1.8


C み 4 ア / 30. ・ D 学 / り た 2 / 4 グ み 4 Service on communlty 、 Heroku (http : //heroku. com) is a popular option in the PYth known for its documentation and add-ons system. lfyou choose this option' please read http: //Ⅷ刪 . theherokuhackersguide. com/ by Randall Degges. python. Anywhere (https : / / M. pythonanywhere.com/ is a PYthon-powered PaaS that is incredibly beginner-friendly. Why do we like these services? We've evaluated them carefully for our needs. Your needs may be different, SO read on about hOW tO choose a PaaS. 30.1 EvaIuating a PaaS When a paas is chosen tO hOSt a project, that project forces architecture concessions in order for the application to work in their system. lherefore' even ifwe heed our warning at the top of this chapter, extracting ourselves 伝 om the PaaS takes effort and time. when a paas is chosen for a or we are using a 、 constantly consider the following: 30.1.1 CompIiance Before メ ou begin evaluating any other aspect' it's critical to check to see if the PaaS meets 10C or federal mandates. Examples : Many medical-based projects in the United States reqmre meeting HIPAA standards. If the paaS doesn't meet HIPAA standards, and the project contains user medical data and a project is deployed there, ど ど ワ 0 ん 記 な 、 ル c ″ 4 〃 イ / 襯 4 / ア ル 化 石 〃 〃 T ″ ん / ー 2 の イ . see https://en.wikipedia.org/wiki/HlPAA#SecuritY—RuIe Most e-commerce projects require at least and anything dealing with credit cards needs to adhere to PCI. While services like Stripe often make this moot' many projects requlre internal integrafion of credit card processing. Make sure the PaaS complies with the PCI specification. See http: I/2SC00PS. co/wikipedia-PCl-standard. For the European Union, ifyou are processing any identifiable data you'll need to 応 Ⅱ ow EU Directive 95 / 46 / EC on the protection of personal data into account. Amongst other things , this places restrictions on exporting such data outside the European es¯ pecially ifyour paas doesn't participate in the US-EU Safe Harbor. If in doubt' consult legal counsel. 396

Two Scoops of Django Best Practices for Django 1.8


17.5.1 BuiIding SingIe Page Apps When MuIti-Page Apps suffice Single-page apps are challenging and fun to build, but does a traditional CMS-site need to be one? CertainIy the content pages can include API-powered editing controls, but when building this kind of site, there is something to be said for traditional HTML pages. However, when working with legacy projects, it's often easier to add new features as single-page apps. %is allows for the maintainers of the project to deliver improved experiences with new features, while preserving the stability of the existing code base. A good example of this might be adding a calendar application to an existmg project. 17.5.2 Not Writing Tests When you first begin working in a new language or framework, including client-sideJavaScript, it s tempting to skip the tests. ln a word, don't. working in the client is getting more complicated and sophisticated every year. Between evolving client-side standards, things are simply not as readable there as on the server side. We cover Django/Python testing in chapter 22. A good reference for JavaScript testing is http://2scoops. co/stack—overflow—javascript—unit—test—toots—for—tdd 17.5.3 Not Understanding JavaScript Memory Management Single-page apps are great, but the complex implementations where users keep them open con- stantly will hold objects in the browser for a very long time. Eventua11y, ifnot managed, this can cause browser SIO 、 and crashes. EachJavaScript 伝a1れC 、 with t001S advice how to handle this potential problem, and it's a good idea to ow the recommended approach. 17.5.4 Storing Data in the DOM When に 5 NotjQuery After years ofusing jQuery, some ofus have grown used to using DOM elements to store data (especially DanieI). However, when using otherJavaScript frameworks this isn't ideal. ヴ have 237

Two Scoops of Django Best Practices for Django 1.8


C カ 孕 / プ & 4 グ 犬 孕 な 〃 g Core C 。 襯 ア 。 れ 倉 18.1 The Temptation to BuiId FrankenDjango Every year, a new fad leads waves 0f developers t0 replace some particular core Django compo- nent. Here'S a summary Of S01 れ e Of fadS 、 seen go. Fad FO 「 perfO 「 mance 「 easons, Reasons NOt Okay: 、 ヨ have an idea for a social network forice cream haters. ljust started building it last month.l need it tO be web-scale!!!l!" 0kay: 、 、 Ou 「 site has 50M users andl ・ m hitting the limits ofwhat lcan d0 「 eplacing the database/0RM with a NOSQL database and co 「 「 esponding ORM 「 eplacement. with indexes, query 叩 timization, caching, etc. We' 「 e also pushing the limits Of our postgres cluster. l've done a lOt Of research on this and am going tO try stO 「 ing a simple denormalized view Of data in Cassandra tO see if it helps.l'm aware 0f the CAP theorem (http: //www. 2SC00PS. co/CAP-theorem/),andfo 「 thisview' eventual consistency iS fine.' ・ Not okay: 、 、 SQL Sucks! We're going with a document-oriented database like MongoDB!" 0kay: WhiIe PostgreSQL's HSTORE datatype 「 eplicates nea 「 ly every aspect 0f MongoDB ・ s data storage system, we want t0 use MongoDB's built-in M 叩 Reduce functionality.' N0t okay: 、 ヨ read on Hacker News that 」 inja2 is faste 「 」 don ・ t know anything about caching or optimization, butl need 」 inja2!" For data processing reasons, 「 eplacing the database/0RM with a NOSQL database and co 「 「 esponding ORM 「 eplacement. Not okay: コ hate having logic in Python modules.l want logic in my templates!" RepIacing Django's template engine with 」 inja2, Mak0, 0 「 something else. 0kay: 、 ヨ have a small number ofviews which generate IMB + HTML pages designed f0 「 Google t0 index. Ⅲ use Django ・ s native support f0 「 multiple template languages t0 「 ende 「 the IMB + sized pages with 」 i 可 a2 , and serve the 「 est with Django TempIate Language.' TabIe 18.1 : Fad-based Reasons to Replace Components of Django 2 イ 4

Two Scoops of Django Best Practices for Django 1.8


C み 4 ア た r27 ゞ 12 ノ 4 〃 g & 冴 立 e• ・ 耘 ィ ー り 2 ん g お ( I 月 0 270 Django packages are downloadable 伝 om the PYthon Package lndex in addition to pip ・ release of Django, pip downloads the files 伝 om the python package lndex. Most PYthon and center for python package information and files. Whenever メ ou use pip to install a particular lhe python package lndex is much more than just a directory of it as the world's largest until it occurs on the Python Package lndex. For the vast majority ofPyth on community, open is 0 一 石 ci it lists over 55 , 000 packages, including Django itself• itory ofsoftware for the python programming language. As ofthe time this sentence was written' ThePythonPackageIndex(PyPI).Iocatedathttps://PYPi ・ python.org/pypi'isarepos- 21.2 Know About the Python Package lndex prefixed with django-", but there are many exceptions. ) of them in other python projects. (GenerallY' l)jango-specific packages generally have names Note that not 砠 of those packages are l)jango-specifi% which means that you can use some packages to consider adding to your projects ・ out Two scoops of Django. lhis list is a great starting point ifyou're looking for highly-useful Appendix A: ル c ん g お イ 砌 石 記 ル な ル covers all of the packages mentioned through- 21.1 ExampIes 0fThird-Party Packages Figure 21.2 : 第 secret is out. lt's just hot fudge.

Two Scoops of Django Best Practices for Django 1.8


77.4. ・ 犬 / ー T / ど % 4 上 4. カ 4 / 砌 ヮ FIhere are a lot of other things you can do, making GoogIe's web crawling specification an im- portant resource for anyone creating single page apps: https://developers ・ google.com/webmasters/ajax-crawting/. 17.3.3 Use a Service to Make Your Site CrawIabIe Rather than do the work ofgenerating a sitemap yourself, consider using a service to do the work for you. For example, for a fee, b rombone. com crawls your Angular.js, Ember. js, or Backbone.js site and shows Google pre-rendered HTML representing the data that you want to display. 17.4 ReaI-Time Woes a. k. a. Latency Let's say we ve put together a well-designed, well-indexed, well-cached real-time project with the widest bandwidth piping content to the world. We can handle any load, and our test users applaud the speed and functionality of the project. %ings 100k great, and we 100k forward to bonuses and raises. "lhen the complaints from the other side of the planet start coming in about the slow speed of the application. Our effort isn't 'real-time' to any of a potentially large block of users and our client/boss is really unhappy. C gra / 4 / ど ど ノ / ん / / ん ど 記 グ / 愈 ん ′ %is isn't a joke, it's a very real problem. Here, Django isn't the problem. lnstead, it's physics. FIhe time it takes for HTTP requests to transmit back and forth across half the circumference of the planet is noticeable to human beings. Add in server-side and client-side processing, and we risk alienating potential or existing users. AISO, keep in mind that even the fastest 10C connections have hiccups and sl( ハ ハ *. so it's not uncommon for 'real-time' applications to have ways to handle this sort ofbehavior. 17.4.1 SoIution: Mask the Latency With Animations One of the more common fixes is to have JavaScript-powered animation distract the user 丘 om latencyissues. We encounter this every time we use a single page app with an attractive interface including all modern web-based email clients. 235