python - Having Problems with Django Context Processors -


i'm new django context processors. wanted create give me famous quotes in every page of blog app. when deployed heroku started giving errors few minutes after launching. these errors :

could not fork new process connection: cannot allocate memory ssl syscall error: eof detected fatal:  out of memory detail:  failed on request of size 112. 

then app restarts - normal. generate same javascript still wanted context processor.

is advisable create context processor 1 given below ?

from blog.models import post  random import randrange  def recent_posts(request):     u = post.objects.all()[:5]      return {         'recent_posts': u     }   def quotes(request):     var = randrange(3)     quotes = {         '0' : "quote 1",         '1' : "quote 2",         '2' : "quote 3",     }      quoted_by = {         '0' : "person 1",         '1' : "person 2",         '2' : "person 3",        }      return {         'quotes': quotes[str(var)],         'quoted_by': quoted_by[str(var)]     } 

this isn't answer question, it's observations on code.

  1. your function quotes ignores argument request. why bother passing it?

  2. each time function quotes called, builds dictionaries quotes , quoted_by thrown away when function returns. put data in global variables instead, needs built once.

  3. you organize quotations 2 dictionaries, 1 mapping strings quotations, other mapping strings authors. generate random number, convert string, , in both dictionaries. error-prone in several ways: when updating dictionaries, might update 1 not other, or put quotation , author under different keys. might add entries dictionaries forget update argument randrange. remember dry principle ("don't repeat yourself").

here's how i'd write code:

from random import choice  # list of pairs (quotation, author). quotations = [     ("focusing saying no.", "steve jobs"),     ("first make run, make run fast.", "brian kernighan"),     ("it's easier ask forgiveness permission.", "grace hopper"),     # ... etc ... ]  def quotes():     """pick random quotation , return context dictionary keys     'quotes' , 'quoted_by'.     """     quotation, author = choice(quotations)     return dict(quotes = quotation, quoted_by = author) 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -