How to create the serial connection to Arduino in Flask?

I am building a live humidity graph with the possibility to light ON/OFF a LED from the flask application. I am having trouble in creating the serial variable in the app.py file, which looks like below:

import serial
import json
from time import time
from flask import render_template, make_response, Flask

# ser = serial.Serial("COM6", 9600)

app = Flask(__name__)
app.config["SECRET_KEY"] = "mysecretkey"


@app.route('/', methods=['GET', 'POST'])
def index():
    # ser = serial.Serial("COM6", 9600)
    #
    # if request.method == 'POST':
    #     if request.form.get('action1') == 'ON':
    #         print('light ON')
    #         ser.write(b'H')
    #         print('turning led ON')
    #         pass  # do something
    #     elif request.form.get('action2') == 'OFF':
    #         print('light OFF')
    #         # time.sleep(4)
    #         ser.write(b'L')
    #         print('turning led OFF')
    #         pass  # do something else
    #     else:
    #         pass  # unknown

    return render_template('Main.html')


@app.route('/humidity', methods=['GET'])
def humidity():
    # Create a PHP array and echo it as JSON
    ser = serial.Serial("COM6", 9600)

    while True:
        temp = ser.read(5).decode('utf-8')
        print('temperature ', float(temp))
        print('random temperature type ', type(temp))

        data = [time() * 1000, float(temp)]
        print('temperature ', data)

        response = make_response(json.dumps(data))
        response.content_type = 'application/json'
        return response


if __name__ == '__main__':
    app.run(debug=True)

I would like to create the ser variable before the app creation of variable, but this triggers the error: ```serial.serialutil.SerialException: could not open port 'COM6': PermissionError(13, 'Access is denied.', None, 5). How could I solve this issue and be able to see the humidity data, as well as control the LED?

One possibility is that some other application on the PC has "COM6" port open.

Perhaps you're running the Arduino IDE at the same time as your Python code and the IDE has the port open?

No, it's because that line ser = serial.Serial("COM6", 9600) will get run multiple times, don't know why exactly...

Then find a PYTHON forum to help. While I've never worked in PYTHON, I would assume this is an easy excersise in openeing & reading from a port.

It's been a while since I played with flask, but I think the "humidity" method is called on each get request. The way it's written it opens the COM port each time without ever closing it and the method never terminates.