'Trying to combine async def function into Flask's webhook

The idea is Flask gets a signal, and must run the "async def main()" function, which by it's self, it works if separately. So im trying to combine this async def function, to a Flask's webhook:

    import asyncio
    # #################### webhook here #############
    from flask import Flask, request, abort
    
    app = Flask(__name__)
    
    @app.route('/webhooktest', methods=['POST'])
    def webhook():
        if request.method == 'POST':
            print(request.json)
            #do something
            return 'success', 200
        else:
            abort(400)
    
    
    
    if __name__ == '__main__':
        #app.run(host='192.168.1.12')   
        app.run()

under "#do something" im trying to place this(its just closes exchange's all open positions at once):

async def main():
    tim = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
    
    client = await AsyncClient.create(api_key=cfg.getPublicKey(), api_secret=cfg.getPrivateKey())
    async def balance_def(): # for short TP
        while True:
            try:    
                balance_def = await client.futures_account()
            except BinanceAPIException as e:
                print("Exception API")                  
                return False
            except Timeout:
                print("balance timeout")
                sleep(2)
                pass
            except requests.exceptions.ConnectTimeout:
                print("balance Connect Timeout")
                sleep(2)
                pass
            except requests.exceptions.ReadTimeout:
                print("balance ReadTimeout")
                sleep(2)
                pass    
            except Exception as e:
                # and not treating it can lead to errors
                print("balance Another unexpected exception occurred")
                print("Reason:", e)  
                printRAW_asyncio(time)
                printRAW_asyncio(" Reason:")
                printRAW_asyncio(e)
                return False
            return balance_def  
    
    tim = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
        
    try:
        balance = await balance_def()
    except BinanceAPIException as e:
        print(e)
    except Timeout:
        print("balance timeout")
        sleep(2)
        pass
    except requests.exceptions.ConnectTimeout:
        print("balance Connect Timeout")
        sleep(2)
        pass
    except requests.exceptions.ReadTimeout:
        print("balance ReadTimeout")
        sleep(2)
        pass    
    except Exception as e:
        # and not treating it can lead to errors
        print("balance Another unexpected exception occurred")
        print("Reason:", e)  
        printRAW_asyncio(time)
        printRAW_asyncio(" Reason:")
        printRAW_asyncio(e) 
    else:
        printRAW_asyncio(json.dumps(balance, indent=3))
        x = 0
        coiny_shorty = {}
    
        coiny_shorty["symbol"] = {1:0}
        coiny_shorty["quantity"] = {1:0}
        
        for value2 in balance["positions"]:
            positionAmt = str(value2['positionAmt'])
            positionAmt_abs = float(value2['positionAmt'])
            position_quantity = abs(positionAmt_abs)
            Para_USDT = str(value2["symbol"])
            
            
            Find_ifShort = positionAmt.find('-')# for shorts
            if Find_ifShort != -1:
                x = x + 1
                coiny_shorty["symbol"][x] = Para_USDT
                coiny_shorty["quantity"][x] = position_quantity
                tim = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
                printRAW_asyncio("----------------------------------------- " + tim)
                printRAW_asyncio(f'{coiny_shorty["symbol"][x]}------------------------------------ ' + tim)
                printRAW_asyncio(f'{coiny_shorty["quantity"][x]}------------------------------------ ' + tim)
        
        def generate_message(c):
           codes = {
             -1002: "UNAUTHORIZED",
             -1003: "Too many requests queued",
             -1007: "Timeout",
             -1015: "Too many new orders.",
             -1021: "Timestamp for this request is outside of the recvWindow",
             -1100: "Illegal characters found in a parameter",
             -1121: "Invalid symbol",
             -2013: "Order does not exist.",
             -2021: "Order would immediately trigger",
             -2022: "ReduceOnly Order is rejected.",
             -4045: "Reach max stop order limit(comment:for the pair)",
             -4003: "Quantity less than zero",
             -4014: "Price not increased by tick size"
           }
           msg = codes.get(c, "[Message not translated]")
           return "Code: {}. {}".format(c, msg)
        async def order_MARKET_BUY_RO(symbol, quantity): # for short TP
            while True:
                try:    
                    order_MARKET_BUY_RO = await client.futures_create_order(symbol=symbol, side=SIDE_BUY, type="MARKET", quantity=quantity, reduceOnly=True)
                except BinanceAPIException as e:
                    print("Exception API", generate_message(e.code))
                    if (e.code) == -2022:
                        print("Yes, code = -2022")
                        printRAW_asyncio(e)
                        sleep(1)
                        pass
                    return False
                except Timeout:
                    print("timeout")
                    sleep(2)
                    pass
                except requests.exceptions.ConnectTimeout:
                    print("Connect Timeout")
                    sleep(2)
                    pass
                except requests.exceptions.ReadTimeout:
                    print("ReadTimeout")
                    sleep(2)
                    pass    
                except Exception as e:
                    # and not treating it can lead to errors
                    print("Another unexpected exception occurred")
                    print("Reason:", e)  
                    printRAW_asyncio(time)
                    printRAW_asyncio(" Reason:")
                    printRAW_asyncio(e)
                    return False    
                return order_MARKET_BUY_RO #
            
        tim = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
        printRAW_asyncio("==========time after closing ===================== " + tim)
        massorders = [order_MARKET_BUY_RO(symbol=coiny_shorty["symbol"][coin],quantity=coiny_shorty["quantity"][coin]) for coin in coiny_shorty["symbol"]]
        res = await asyncio.gather(*massorders)  # Use a starred expression to unpack the list.
        printRAW_asyncio(res)
        await client.close_connection() # it works here
        tim = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
        printRAW_asyncio("================time after closing ================== " + tim)
        print(f"closed all short orders")
        printRAW_asyncio("----------------------------------------- " + tim)
        printRAW_asyncio(f"closed all short orders ")



    
if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main()) 

both codes works separately, if combined, webook works, but closing dont, proobably because: i dont know where to place this part:

if __name__ == "__main__":
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main()) 

With

def webhook():

theres no errors. Just dont works.

with async def webook():

theres "The view function did not return a valid response. (...) but it was a coroutine."

when i ctrl + c, it also says: "coroutine webhook was never awaited"

Any clues much appreiciated! as im trying things as we speak. I had Flask 1.1.2. installed 2.0.0 now, wow it does not work at all now with simple webhook...will edit and also if find answer i will post it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source