views.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Create your views here.
  2. from django.template import Context, loader
  3. from django.http import HttpResponse
  4. from django.core import serializers
  5. from world.models import World, Fortune
  6. from django.shortcuts import render
  7. from ujson import dumps as uj_dumps
  8. import random
  9. from operator import attrgetter
  10. import numpy.random as nprnd
  11. from functools import partial
  12. def json(request):
  13. response = {
  14. "message": "Hello, World!"
  15. }
  16. return HttpResponse(uj_dumps(response), mimetype="application/json")
  17. def db(request):
  18. queries = int(request.GET.get('queries', 1))
  19. # worlds = []
  20. # it's not required to explicitly loop instead of using list comprehension
  21. #for i in range(queries):
  22. # get a random row, we know the ids are between 1 and 10000
  23. #worlds.append(World.objects.get(id=random.randint(1, 10000)))
  24. # instead we can do:
  25. #worlds = [World.objects.get(id=random.randint(1, 10000)) for i in range(queries)]
  26. # fun fact: every dot-notation lookup calls some python magic under the hood. Like every other code,
  27. # one can eliminate dereferences by storing the end dereferenced thing in an identifier
  28. g = World.objects.get
  29. #r = random.randint
  30. # but wait! there's more!
  31. #http://stackoverflow.com/questions/4172131/create-random-list-of-integers-in-python
  32. #r = nprnd.randint
  33. # but wait! there's more! if we're calling a function over and over with the same parameters,
  34. # we can use even more function magic.
  35. rp = partial(nprnd.randint, 1, 10000)
  36. # now we're ready to write our awesome query iterator thingy
  37. # first of all, we know the id's correspond to the random number we're picking, so we can create
  38. # dictionaries on the fly instead of serializing later
  39. # by creating dicts, we don't need to user the model serializer, which is probably slow and only appropriate
  40. # for complicated serializations of joins and crazy query sets etc
  41. # test xrange vs range if the query number is gigantic
  42. worlds = uj_dumps([{'id' : r, 'randomNumber' : g(id=r).randomnumber} for r in [rp() for q in xrange(queries)]])
  43. return HttpResponse(worlds, mimetype="application/json")
  44. def fortunes(request):
  45. fortunes = list(Fortune.objects.all())
  46. fortunes.append(Fortune(id=0, message="Additional message added at runtime."))
  47. fortunes = sorted(fortunes, key=attrgetter('message'))
  48. context = {'fortunes': fortunes}
  49. return render(request, 'fortunes.html', context)