0

I'm new to python, so this might be a dumb question, but I have the following issue:

I'm trying to deploy a Flask-SocketIO app to heroku, my app.py looks like this:

app = Flask(__name__)
socketio = SocketIO(app)
opt: Dict[Any, Any] = {}
.
.
@socketio.on('connect')
def joined():
   test = json.dumps(opt)
   emit('test', test)
.
.
if __name__ == '__main__':
   opt = setup_args()
   socketio.run(app)

My procfile looks like this:

web: gunicorn -k flask_sockets.worker app:app

If i run heroku local my server starts as expected, and I can establish a socket conection with my client, but my variable opt seems not to be filled. From what i've read in the docs, this is because the procfile does the socketio.run(app) for me, and my __main__ part is not getting executed. I need to somehow trigger a method that initializes some variables in my app.py. How can I achieve this?

Thanks

6
  • Is there a reason why you don't simply move opt = setup_args() out of the if statment, and move it, say, somewhere at the top of the file? Because this would solve the problem. If you want opt to be used for each request, you should use object g. Commented Dec 14, 2020 at 14:00
  • 1
    well, that was it.. thank you! So what is object g for? is it to set the variable global before assignment? If I understand it correctly, if I assign a variable in a function scope, it's only available in that function, if I use global opt opt = setup_args() the global variable opt is assigned. is that correct? Commented Dec 14, 2020 at 14:26
  • Object g is available to you on every request. And your other statements seem to be correct. Commented Dec 14, 2020 at 14:28
  • PS: I posted my comment as an answer too. So if you mark it as the correct answer and give an up vote others can easier spot what the correct answer is. :) Commented Dec 14, 2020 at 14:29
  • Ok, I have one mor issue now: if I try to change something in my opt dict like this: opt['agent'] = xyz I get the following error: NameError: name 'opt' is not defined So that means that my variable is not initialized if I'm not mistaken Commented Dec 14, 2020 at 14:36

1 Answer 1

1

Is there a reason why you don't simply move opt = setup_args() out of the if statment, and move it, say, somewhere at the top of the file?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.