def sendStory(request): # Get json data from request if it's available if request.method == 'POST': json_data = json.loads(request.body, "utf-8") # Save story if it was sent if "text" in json_data: story = Story(text = json_data["text"]) story.save() # Get list of stories read ids_read = [int(s) for s in json_data["ids_read"]] # Retriving best story not read from database try: # Get all stories not read stories = Story.objects.exclude(id__in = ids_read) # Raise exception if no story was found if not stories: raise Story.DoesNotExist # Get story with the highest score and the number of ratings nratings = Rating.objects.all().count() best_story, score = getBestStory(stories) # Transform the story model in json format story_data = best_story.to_json() story_data["score"] = score story_data["nratings"] = nratings # If user has read all stories, warn him except (Story.DoesNotExist, IndexError): return HttpResponse("") # Send story back in json format through the response object response_data = json.dumps(story_data, ensure_ascii=False) return HttpResponse(response_data, content_type="application/json")
# Set initial ratings mf = Rating(label = "muito fraca", value = 0) f = Rating(label = "fraca", value = 1) r = Rating(label = "regular", value = 2) b = Rating(label = "boa", value = 3) mb = Rating(label = "muito boa", value = 4) mf.save() f.save() r.save() b.save() mb.save() # Add stories and their ratings story = Story(text = "Esta semana resolvi virar garota de programa por causa da situação financeira difícil. Não sou lésbica, mas aceitei quando uma garota ligou marcando o meu primeiro programa. Chegando no local combinado, descubro que era minha irmã.") story.save() Vote(story = story, rating = mb).save() Vote(story = story, rating = mb).save() Vote(story = story, rating = b).save() Vote(story = story, rating = r).save() Vote(story = story, rating = f).save() Vote(story = story, rating = b).save() Vote(story = story, rating = mb).save() Vote(story = story, rating = mb).save() story = Story(text = "Há dois anos eu esperava pro meu pai comprar um notebook novo pra mim, ontem eu levei ele pra escola pra mostrar pros eu amigos, na volta eu fui assaltado") story.save() Vote(story = story, rating = b).save()