Tuesday, 1 November 2022

Flask update a global variable with value from Redis

I have a python flask app with a global variable reading some data from Redis. I have another process that's updating data in Redis independently, and it will ping the flask app (i.e. endpoint /reload-redis-data) to tell flask app to update that global variable with the latest data in Redis.

There are 3 files involved:

  • app.py
from re import A
from flask import Flask
from util import load_redis_config
from function import f

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello world!"

@app.route("/test")
def test():
    f()
    return ""

@app.route("/reload-redis-config")
def reload_redis_config():
    load_redis_config()
    return "reloaded"

if __name__ == "__main__":
    app.run("localhost", 3001)
  • util.py
import redis

global a
a = ""

def load_redis_config():
    con = redis.Redis("localhost", 6379)
    global a
    a = eval(con.get("a"))
    print(f"Updated {a=}")

load_redis_config()
print(f"At server start {a=}")
  • function.py
from util import a

def f():
    global a
    print(f"In function f {a=}")

The setup is:

  1. in Redis set a 1
  2. at server start, load_redis_config() will be called and load a -> print 1
  3. /test -> print 1
  4. in Redis set a 2
  5. ping /reload-redis-config, load_redis_config() will print a is changed to 2
  6. /test -> I'm expecting it to be changed to 2 since a is a global variable which is updated in step 5, but within function f a is still 1.

My trace:

Updated a=1
At server start a=1
 * Serving Flask app 'app'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://localhost:3001
Press CTRL+C to quit
In function f a=1
127.0.0.1 - - [28/Oct/2022 14:22:21] "GET /test HTTP/1.1" 200 -
Updated a=2
127.0.0.1 - - [28/Oct/2022 14:22:32] "GET /reload-redis-config HTTP/1.1" 200 -
In function f a=1
127.0.0.1 - - [28/Oct/2022 14:22:35] "GET /test HTTP/1.1" 200 -

Basically my question is, why function isn't picking up the updated global variable a? Is there anything or any concept that I'm missing?



from Flask update a global variable with value from Redis

Joi validate at least one of 2 input fields are completed

I seem to hit a roadblock when it comes to joi's .or() function as it doesn't seem to implement as I'd expect.

I have 2 text input fields, both have their own way of validating, though only at least one is required.

    const schema = joi
      .object({
        "either-this-field": joi.string().trim().max(26),
        "or-this-field": joi
          .string()
          .trim()
          .regex(/^\d+$/)
          .max(26)
        "other-field-1": joi.string().required(),
        "other-field-2": joi.string().max(40).required(),
    
      })
      .or("either-this-field", "or-this-field");

it just seems that this or doesn't do as I'd expect and each field from the or is just validated as per it's own validation rules

if neither field has values, then I'll display error for both fields until at least one is completed



from Joi validate at least one of 2 input fields are completed

Android Slow Bluetooth RFCOMM Transfer Rate with RN4678

We are experimenting with a bunch of new tablets, and every one we tried is having issues with slow transfer rates with the RN4678 board. We currently use the Lenovo M10 FHD Plus. We tried a few such as the Teclast M40S, Nokia T20, and Samsung Galaxy Tab A8. The first two had horrible transfer rates, while the latter was okay but not ideal. We cannot use the Lenovo M10 Plus 3rd Gen because the buttons are too close to the corner to use with our tablet holders.

Here is my code:

public void SendMessage(BluetoothSocket socket, String msg) {
    OutputStream outStream;
    try {
        outStream = BluetoothConnectionService.outputStream;
        outStream.write("S".getBytes());
        Thread.sleep(4000);
        processThread = true;
        mApp.running = true;
        BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
                CollectingDetail.this);
        Thread messageListener = new Thread(bsl);

        messageListener.start();
        timer = new CounterClass(remaingTime, 1000);
        timer.start();
        bt_stop.setText("Stop");

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bluetoothReceiver, filter);
        bluetoothReceiver.setRegistered(true);
    } catch (IOException | InterruptedException e) {
        Log.e("BLUETOOTH_COMMS", e.getMessage());

        connectSocket();
    } 
}

public static class BluetoothSocketListener implements Runnable {
    private final WeakReference<CollectingDetail> wrActivity;
    private BluetoothSocket socket;

    public BluetoothSocketListener(BluetoothSocket socket, CollectingDetail collectingDetail) {
        this.socket = socket;
        wrActivity = new WeakReference<CollectingDetail>(collectingDetail);
    }

    @Override
    public void run() {
        final CollectingDetail activity = wrActivity.get();
        if (activity != null) {
            activity.inStream = null;
            if (!Thread.currentThread().isInterrupted()) {
                int bufferSize = 512;
                byte[] buffer = new byte[bufferSize];
                Log.i("Bluetooth bytes", new String(buffer));
                activity.inStream = BluetoothConnectionService.inputStream;
                int availableBytes;
                int bytesRead = -1;
                String message = "";

                while (activity.processThread) {
                    message = "";
                    try {
                        availableBytes = activity.inStream.available();
                        if (availableBytes > 0) {
                            bytesRead = activity.inStream.read(buffer);
                            if (bytesRead != -1 && bytesRead < bufferSize) {
                                message = new String(buffer, 0, bytesRead);

                                if (activity.mainHandler != null) {
                                    activity.mainHandler.post(new MessagePoster(message, activity));

                                }


                            }
                        }
                    } catch (IOException e) {
                        Log.e("BLUETOOTH_COMMS", "Error reading bytes");
                        try {
                            socket.close();
                        } catch (IOException e1) {
                            Log.e("BLUETOOTH_COMMS", "Could not close socket");
                        }
                        activity.processThread = false;
                    }
                }
            }
        }
    }
}


public void seprateData(String message) {
    try {
        message = message.replaceAll("(\\r\\n|\\n|\\r)", ",");
        String[] a = message.split(",");
        boolean goodData = false;

        for (int i = 0; i < a.length; i++) {
            final String data = a[i];
            if (data.length() > 0 && !data.equals(" ")) {
                if (data.length() >= 10 && data.startsWith("5A")) {
                    al_sepratedMessageList.add(data);
                    goodData = true;

                }
            }
        }

        if (goodData) {
            calculation();
            if (ConnectThrough.equalsIgnoreCase("usb")) {
                UsbConnectionSerivce.sendMessage("K");
            } else {
                BluetoothConnectionService.sendMessage(socket, "K");
            }
        }

    } catch (Exception e) {
        Log.e("BiSym", "Error Parsing BiSym Data");
    }
}

Is there any way we can increase the transfer rate without changing the firmware? It appears others have faced similar problems, but none of the answers have a real solution. Could you please help me out. Thanks.



from Android Slow Bluetooth RFCOMM Transfer Rate with RN4678