Search code examples
pythonglobal-variableschatbotpython-decoratorsline-api

Having problems with global variable in python and line api


I'm trying to build reply bot by using line api and python 2.7.15 . this is my code

from flask import Flask, request, abort
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (MessageEvent, TextMessage, TextSendMessage,)

app = Flask(__name__)
line_bot_api = LineBotApi('UIXwXWExxxxxxxxxxxxxxxxxxxxxxxxxxxx')
handler = WebhookHandler('458033a97c124xxxxxxxxxxxxxxxxxxxxx')
number = 1

@app.route("/")
def hello():
    return str(number)

@app.route("/webhook", methods=['POST'])
def webhook():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    text = event.message.text
    user_id = event.source.user_id

    if(text == 'inc'):
        #set global variable here
        number += 1
        line_bot_api.push_message(user_id,TextSendMessage(text=str(number)))


if __name__ == "__main__":
    app.run()

then i implement this on heroku and i try chatting with my bot, first i send messageinc, he reply me 2 then i try send inc once again ,he reply me 3 and i try again he replies me 1 i try send inc once again he reply me 4 what wrong? why my number doesn't continue?


Solution

  • Python backend apps are typically deployed in multiprocess configuration (the front server - apache, ngnix or whatever - runs multiple parallel processes to handle incoming requests), and any request can be served by any process. Global variables are per-process, so which state you will find your global depends on which process served the request. Conclusion: don't use global variables to store application state - use a shared database (of any kind, it doesn't have to be a SQL database, it just have to be shared amongst all processes).