1

I have a chatbot setup on a Heroku server running Flask in Python 3.8 on a gunicorn framework. Everything is working well except for a single global variable. Below is my code relating to this issue; I am not very experienced in python so this could be a simple mistake I am overlooking.

import os
import sys
import json
from flask import Flask, request
import requests
from random import randint
import datetime

...

@app.route('/spam', endpoint = 'spam', methods=['POST'])
def webhook():
    log('The Talker Log: Received a ping to the /spam endpoint.')
    global spam_message_count
    spam_message_count += 1 
    if spam_message_count == 1:
        post_message('The Talker', 'SPAM HAS BEEN ACTIVATED. Message #1', '')
    else:
        post_message('The Talker', 'SPAM Message #{}'.format(spam_message_count), '')
    return "ok", 200

(other methods not shown) This code in question doesn't have any value, it's really just a test for later.

The setup for this includes a separate machine that uses cron to ping the /spam endpoint every minute. Upon setting this up I receive the following messages from the chatbot:

SPAM HAS BEEN ACTIVATED. Message #1

One minute later

SPAM HAS BEEN ACTIVATED. Message #1

One minute later

SPAM Message #2

One minute later

SPAM Message #3

One minute later

SPAM Message #4

One minute later

SPAM Message #5

One minute later

SPAM Message #2

One minute later

SPAM Message #3

One minute later

SPAM Message #4

One minute later

SPAM Message #6

After leaving it run for about forty minutes, it only ended at #22. I'm really not sure where the variable gets tripped up, any help would be appreciated.

Strat5
  • 13
  • 1
  • 6
  • 1
    maybe you should keep it in file or database. This variable can be global in one thread but server may use many threads/processes and then other processes have own variable `spam_message_count` – furas Jun 19 '20 at 22:26

1 Answers1

2

Heroku Dynos run a containerized version of your app and do not guarantee that your app will be run continuously. Dynos are transparently restarted from time to time and free accounts will see the dyno shut down after 30 minutes of no activity - only to be restarted again when a request comes in. This means you cannot store the state of your application inside the applications itself, a.k.a. global variables that you intend to live beyond a single request.

Your best bet is likely to hold any state you wish to save in between requests in a datastore. In your case you might consider Redis

Chase
  • 3,009
  • 3
  • 17
  • 23