【问题标题】:Redirecting a dynamic route in Flask to a new route to show a result in browser将 Flask 中的动态路由重定向到新路由以在浏览器中显示结果
【发布时间】:2020-11-21 02:39:41
【问题描述】:

我根据 localhost 的路径制作了一个石头、剪纸、剪刀游戏,即我将我的机器用作带有 Flask 的动态 Web 服务器。

我的游戏逻辑是正确的,已经过测试,所以当我在浏览器中输入http://localhost:5000/rock/paper 时,浏览器窗口中会返回以下字符串:

Player 1 chose: Rock Player 2 chose: Paper So, the winner is...Player 2

但是,我希望使用 result.html 模板将这些结果的路径更改为另一个名为 result 的新路径。即我可能需要@app.route('/result') 之类的东西来定义新路线。目前,我可能不得不保留/rock/paper 路线,因为这是我目前确定游戏结果的数据输入方式。

我当前动态路径的代码如下 - 我有一个游戏类,它需要 2 个玩家和一个玩家类,它定义了一个可以选择石头/纸或剪刀的玩家:

@app.route('/<choice_1>/<choice_2>')
def play_the_game(choice_1, choice_2):
    player_1 = Player("Player 1", choice_1)
    player_2 = Player("Player 2", choice_2)
    game = Game(player_1, player_2)
    winner = game.play_game()
    return "Player 1 chose: " + choice_1.title() + " " + " Player 2 chose: " + choice_2.title() + "    " + " So, the winner is..." + winner

但是将结果路由到新模板并不像:

@app.route('/result') = @app.route('/<choice_1>/<choice_2>')

仅供参考,我的 results.html 文件的 HTML 不完整,如下所示。注意:我有一个 base.html 文件,该文件扩展为:

{% extends "base.html" %}

{% block content %}

<div>
    <p>Game Results here:</p>

</div>


{% endblock %}

我们将不胜感激。

【问题讨论】:

    标签: python python-3.x flask


    【解决方案1】:

    你可以只用获胜者的值来渲染模板

    @app.route('/<choice_1>/<choice_2>')
    def play_the_game(choice_1, choice_2):
        player_1 = Player("Player 1", choice_1)
        player_2 = Player("Player 2", choice_2)
        game = Game(player_1, player_2)
        winner = game.play_game()
        return render_template("result.html", winner = winner)
    

    通过这个,我们将变量“winner”的值传递给 HTML 页面。

    你的 result.html 应该是这样的

    {% extends "base.html" %}
    
    {% block content %}
    
    <div>
        <p>Game Results here:</p>
        <h2>  {{ winner }} </h2>
    
    </div>
    
    
    {% endblock %}
    

    Jinja 模板引擎会自动为 {{ }} 之间的变量填写值

    【讨论】:

    • 我能问一下为什么我们必须定义获胜者=获胜者作为回报render_template(“result.html”,获胜者=获胜者)?为什么需要另一个赋值才能传递给 result.html 模板?我认为我们可以直接返回 render_template("result.html", 获胜者)。谢谢你,我相信这解决了我的问题!
    • 如果我的变量命名不清楚,我很抱歉。我们可以将变量命名为任何东西。但是我们必须将winner = winner 中的第一个变量命名为与 HTML 中的变量相同。您可以观看此以获取更多详细信息youtube.com/watch?v=fQrq207zXzU
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 2019-10-29
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多