我一直在分配之前引用此错误局部变量'url'

时间:2019-02-16 04:50:47

标签: python api flask jinja2

它没有运行循环

更改了可变网址名称,但仍然无法正常工作

@

app.route("/processbuy", methods=["POST"])
def processbuy():
 if request.method == "POST":
        index2 = request.form['index2']
        querystring = {"api_key":"NN2T8jrqC6UH5inDezHh"}
        payload = ""
        headers = {
            'cache-control': "no-cache",
            'Postman-Token': "d2cd69a4-e6d4-466c-88b3-0a3987b1cd7d"
        }                              
        print("dsad")
        if index2 == "Stock Market Index at Exchange: NYSE":
                url = "https://www.quandl.com/api/v3/datasets/WFE/INDEXES_NYSE.json"
                response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
                indiceData = json.loads(response.text)
                latestIndicePrices = indiceData["dataset"]["data"][0]
                indexValue = float(latestIndicePrices[5])

        else: 
                if index2 == "NASDAQ-100 Target 25 Notional Net Return Index(XNDXT25NNR)":
                    url = "https://www.quandl.com/api/v3/datasets/NASDAQOMX/XNDXT25NNR.json"
                elif index2 == "Stock Market Index at Exchange: London Stock Exchange FTSE 100":
                    url = "https://www.quandl.com/api/v3/datasets/WFE/INDEXES_LONDONSEFTSE.json"
                elif index2 == "Stock Market Index at Exchange: NYSE":
                    url = "https://www.quandl.com/api/v3/datasets/WFE/INDEXES_NYSE.json"
                response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
                print("response="+response.text)
                indiceData = json.loads(response.text)
                latestIndicePrices = indiceData["dataset"]["data"][0]
                indexValue = float(latestIndicePrices[1])
        print("dwwsw")
        token = session['oauth_token']
        customersAccount = session['fidor_customer']
        customerDetails = customersAccount['data'][0]

在循环后添加打印件时,它应该显示打印件,但对我而言却不是。

2 个答案:

答案 0 :(得分:0)

仅当index2被定义为某物时,变量url才会初始化

答案 1 :(得分:0)

您的问题是,可能永远不会为变量url分配任何值。原因是您的if条件。

if condition1:
    url = "something"
else:
    if condition2:
        url = "something"
    elif condition3:
        url = "something"
    elif condition4:
        url = "something"
    else: # hypothetical
        url is undefined here # and here is your issue

您可以通过添加最后一个catch或在检查任何条件之前将url初始化为默认值来解决此问题。

如果您使用Pycharm这样的优质IDE,即使在运行代码之前,也会警告您这些问题。