如何在while循环中打印HttpResponse,然后为每个循环追加到它?

时间:2018-02-19 10:36:42

标签: python django views httpresponse

好的,我有这个观点:

def fight(request):
    monster = Monster.objects.get(pk=request.POST['monster'])
    user = Profile.objects.get(pk=2)
    while monster.health > 0 and user.health > 0:
        monsterattack = random.randint(monster.minattack, monster.maxattack)
        userattack = random.randint(user.attack*.75, user.attack*1.5)
        user.health = user.health - monsterattack
        monster.health = monster.health - userattack
        HttpResponse('Player attacked for: %s\n Monster attacked for: %s\n' % (userattack, monsterattack))
    return HttpResponse('You are fighting %s\n Player Health: %s \n Monsters Health: %s' % (monster.name, user.health, monster.health))

我想知道是否有一种方法可以在每次循环时将第一个HttpResponse打印到模板,然后在while循环结束后再打印第二个while循环。

2 个答案:

答案 0 :(得分:0)

视图应返回单个HTTPResponse。将多个HttpResponse个对象添加到一起是没有意义的。

您可以连接字符串并返回单个res

def fight(request):
    out = ""
    while monster.health > 0 and user.health > 0:
        out += 'Player attacked for: %s\n Monster attacked for: %s\n' % (userattack, monsterattack)
    out += 'You are fighting %s\n Player Health: %s \n Monsters Health: %s' % (monster.name, user.health, monster.health)
    return HttpResponse(out)

另一种常见模式是生成字符串列表,然后在最后加入它们。这可能比连接字符串更快,但我不确定您是否会在这种情况下看到任何明显的差异:

def fight(request):
    out = []
    while monster.health > 0 and user.health > 0:
        out.append('Player attacked for: %s\n Monster attacked for: %s' % (userattack, monsterattack))
    out.append('You are fighting %s\n Player Health: %s \n Monsters Health: %s' % (monster.name, user.health, monster.health)
    return HttpResponse("\n".join(out))

答案 1 :(得分:0)

视图仅返回一个响应。你想要什么将需要ajax轮询(简单但不是非常有效)或websockets(更复杂 - 看看django-channels如何在Django中 - 但可能对你的应用程序更有效)。