简体   繁体   中英

Getting Unbound local Error: local variable 'x' referenced below assignment

I have a python flask app that is receiving webhook from another application. When it receives the webhook, it responds back by carry out a task (looking up someone's availability) and responding back to the web application with a response. I am getting an unbound local error local variable 'response' referenced below assignment when sending a response back. It looks like calling response at that level is causing issues. Any help would be greatly appreciated.

from flask import Flask
from flask import request
from flask import make_response
import logging
import json
import random
import os
import importlib
import win32com.client
import pywintypes
import datetime
import pythoncom
from gevent.pywsgi import WSGIServer
from gevent import monkey; monkey.patch_all()
import string

pythoncom.CoInitialize()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(message)s')

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)
    logger.info("Incoming request: %s", req)
    intent = get_intent_from_req(req)
    logger.info('Detected intent %s', intent)

    if intent == "Check Schedule Next":
        pythoncom.CoInitialize()
        emailparam = req.get('queryResult').get('parameters').get('email')
        datetime1 = req.get('queryResult').get('parameters').get('date-time').get("date_time")
        datetime2=datetime1.replace('T',' ')
        datetime3=datetime2.replace("-04:00", "")
        print(datetime3)
        pythoncom.CoInitialize()
        class MeetingRoom:
            def __init__(self, inputDate, duration, locationMail):
                self.inputDate = inputDate
                self.oOutlook = win32com.client.Dispatch("Outlook.Application")
                self.bookings = self.oOutlook.CreateItem(1)
                self.bookings.Start = inputDate
                self.bookings.Duration = duration
                self.bookings.Subject = 'Follow Up Meeting'
                self.bookings.MeetingStatus = 1
                self.roomRecipient = self.bookings.Recipients.Add(locationMail)

            def checkRoomAvailability(self):
               bookingDateTime = datetime.datetime.strptime(self.inputDate, '%Y-%m-%d %H:%M:%S')
                self.roomRecipient.resolve
                myDate = bookingDateTime.date()
                pywintypeDate = pywintypes.Time(myDate)
                availabilityInfo = self.roomRecipient.FreeBusy(pywintypeDate, self.bookings.Duration, True)
                timeAvailability = []
                newTime = pywintypeDate
                # print(newTime)
                currentTime = datetime.datetime.now()
                for isAvailable in availabilityInfo:
                    # print(newTime, " :: ", isAvailable)
                    if isAvailable == "0" and newTime > currentTime:
                        timeAvailability.append(newTime)
                    newTime = newTime + datetime.timedelta(minutes=self.bookings.Duration)

                # print(availabilityInfo)
                # for value in timeAvailability:
                #     print(value)
                try:
                    index = timeAvailability.index(bookingDateTime)
                    print(emailparam, "is available")
                    response = {
                    'fulfillmentText': emailparam
                    }
                    # self.bookings.Save()
                    # self.bookings.Send()

                except ValueError:
                    for timestamp in timeAvailability:
                        if bookingDateTime <= timestamp:
                            break
                print("I dont see availability for", emailparam, "at", bookingDateTime, " but next available time is ", timestamp)
                x = ("I dont see availability for", emailparam, "at", bookingDateTime, " but next available time is ", timestamp)
                response = {
                    'fulfillmentText': x
                }
                # def bookMeetingRoom():

        if __name__ == '__main__':
            meetingRoomObj = MeetingRoom(datetime3, 15, emailparam)
            meetingRoomObj.checkRoomAvailability()
        #response = {
        #    'fulfillmentText': emailparam
        #}

    res = create_response(response)
    return res

def get_intent_from_req(req):
    try:
        intent_name = req['queryResult']['intent']['displayName']
    except KeyError:
        return None

    return intent_name

def get__from_req(req):
    try:
        intent_name = req['queryResult']['intent']['displayName']
    except KeyError:
        return None

    return intent_name


def create_response(response):
    res = json.dumps(response, indent=4)

    logger.info(res)

    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'

    return r

if __name__ == '__main__':
    LISTEN = ('0.0.0.0',8080)
    http_server = WSGIServer( LISTEN, app )
    http_server.serve_forever()

This line references response before it's initialized:

res = create_response(response)

Perhaps make sure all code paths initialize the response varaiable?

Solution

It seems you've created your response object in the wrong scope, remove it from the function checkRoomAvailability .

Inside the function checkRoomAvailability after you've created the response object, return it like so

response = {
                'fulfillmentText': x
            }
return response #ADD THIS LINE

Remove these lines

 if __name__ == '__main__':
        meetingRoomObj = MeetingRoom(datetime3, 15, emailparam)
        meetingRoomObj.checkRoomAvailability()

Then add back the object creation and call right before you create your response like so

meetingRoomObj = MeetingRoom(datetime3, 15, emailparam)
response = meetingRoomObj.checkRoomAvailability()
res = create_response(response)
return res

Suggestion

You are lacking some fundamental understanding about how python or scope works so I suggest taking a read friend https://docs.python.org/3.3/reference/executionmodel.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM