This snippet allows to up and down TCP server via Flask endpoints. I'm seriously concerned about global variables here. And asking for review this code.

The main idea is to be able to up/down TCP server by request to the Flask web service, we need it for testing purposes.

import socket

from flask import Flask
import threading

# tcp server
TCP_IP = ''
TCP_PORT = 5001

# flask app
app = Flask(__name__)

light_on = False
thread_on = False
thread = False

def launchServer():
    def run():
        global light_on
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((TCP_IP, TCP_PORT))
        print("run", flush=True)

        print('waiting for connection', flush=True)
        CONN, addr = s.accept()
        while light_on:
            print('Connection address:', addr, flush=True)
            # Logic Here


    global thread
    if thread_on:
        thread = threading.Thread(target=run)

def start():
    print('starting', flush=True)
    global light_on
    global thread_on
    light_on = True
    thread_on = True
    return "Started"

def stop():
    global light_on
    global thread
    global thread_on
    light_on = False
    thread_on = False
    thread.do_run = False
    return "Stopped"

if __name__ == "__main__":
    app.run(host='', debug=True, port=5000, use_reloader=False, threaded=True)

Is there a best way for it, or can I avoid global variables, and be sure that the code thread safe?

| improve this question | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.