【问题标题】:Python/Flask Redefining and Initializing Variables [duplicate]Python / Flask重新定义和初始化变量[重复]
【发布时间】:2019-04-28 17:56:45
【问题描述】:

我敢肯定,我在这里有一个非常基本的问题,但这让我很头疼。我有一个烧瓶/python 程序,基本上,在提交表单后,变量的值会更改并且页面刷新,现在包括显示该变量的文本。

这里有一些示例代码来迭代我的想法:

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        if counter == 'one':
            #stuff happens here
            counter == 'two'
        else:
            if counter == 'two':
                #stuff happens
                counter == 'three'
    else:
        counter == 'one'
return render_template("index.html",counter=counter)
...

有什么帮助吗?我是新手,所以我可能只是在做一些愚蠢的事情。

【问题讨论】:

    标签: python variables flask


    【解决方案1】:

    变量赋值应使用= 而不是==

    @app.route("/", methods=["GET", "POST"])
    def index():
        if request.method == "POST":
            if counter == 'one':
                #stuff happens here
                counter = 'two'
            else:
                if counter == 'two':
                    #stuff happens
                    counter = 'three'
        else:
            counter = 'one'
    

    【讨论】:

      【解决方案2】:

      您应该在路由文件的开头定义变量。例如:)

      from flask import render_template
      
      counter = 'one'
      @app.route("/", methods=["GET", "POST"])
      def index():
          if request.method == "POST":
              if counter == 'one':
                  #stuff happens here
                  counter = 'two'
              else:
                  if counter == 'two':
                      #stuff happens
                      counter = 'three'
          else:
              counter = 'one'
      

      【讨论】:

      • 这仍然给我错误:UnboundLocalError: local variable 'counter' referenced before assignment
      • 请记住在方法调用之前包含 counter = 'one'
      猜你喜欢
      • 2015-01-28
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 2018-08-13
      相关资源
      最近更新 更多