passing a multiproccessed dict to web.py

37 Views Asked by At

i have a django page, and an eternal python script.

the external python script is multiproccessed, 1 proccess has a while loop which sends websocket messages to my django page, the other proccess is a web.py server.

I have a multiproccessed dict to share a variable between my while loop and my web.py server.

Ive struggled to pass my multiproccessed dict into my web.py server, but thanks to chatgpt (after it made a bunch of wrong suggestions) im doing

app.add_processor(lambda handle: web.loadhook(lambda: handle(shared_dict)))

but now when i post to my web.py server i get

web.py post result

i want my web.py to return

    return "<h1> it worked !!!!! </h1>"

how can i pass a multiproccesed dict to my web.py server and allow me to post, what should i do to fix this?

minimal reprodicable example of my external.py below

import web
import os
import time
from multiprocessing import Process, Manager, freeze_support
import asyncio
import websockets
import json
import mysql.connector

class hello:
    def __init__(self, shared_dict):
        self.shared_dict = shared_dict

    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'

    def POST(self, d):
        print('variable_i_want_to_update_for_my_web_py_from_websocket_loop')
        print(self.shared_dict['x'])
        return "<h1> it worked !!!!! </h1>"

async def SendSMS(shared_dict):
    ws_url = 'ws://localhost:8000/ws/endpoint/home/'
    async with websockets.connect(ws_url, ping_interval=None) as websocket:
        i = 0
        while True:
            await websocket.send(json.dumps({'message': "oh my god, a message", 'token': 'hello'}))
            await asyncio.sleep(1)
            i += 1
            shared_dict['x'] = str(i)
            print(str(shared_dict['x']) + "   x      according to websocket loop ")

def send_SMS_caller(shared_dict):
    asyncio.run(SendSMS(shared_dict))

def mi_webpy_func(shared_dict):
    urls = (
        '/(.*)', 'hello'
    )
    app = web.application(urls, globals())
    app.add_processor(lambda handle: web.loadhook(lambda: handle(shared_dict)))  # Pass shared_dict to the handle function
    app.run()

if __name__ == '__main__':
    freeze_support()
    manager = Manager()
    shared_dict = manager.dict()
    shared_dict['x'] = "not_set"
    p1 = Process(target=send_SMS_caller, args=(shared_dict,))
    p2 = Process(target=mi_webpy_func, args=(shared_dict,))
    p2.start()
    p1.start()
    p2.join()
    p1.join()

i have placed a full minimal reproducable example with a django page too here

https://github.com/tgmjack/min_reproducable_example_of_unchanging_variable

ive tried a whole bunch of stuff chatgpt suggested and now its going round in circles with the same suggestions.

0

There are 0 best solutions below