Problems Receiving a POST Request in Flask and Sending It Via Websockets

Viewed 26

I'm trying to connect between two services, one sends me POST requests which I then need to parse out and send the info via Websocket. (TradingView and Tradovate).

I'm using Flask and websocket-client.

My problem is that if I open the Websocket connection first, Flask doesn't run at all, and vice versa. I think it's because the 2 will run infinitely so one doesn't end for the other to begin.

I've also tried putting the Websocket inside a Flask "@app.route" and initiating it with a GET/POST request but that doesn't work since I can't return anything and the Heroku Worker times out.

It feels like a pretty simple problem but I couldn't get anything to work.

Here are parts of the code:

from flask import Flask, request
import config 
import json 
import requests
import websocket
# Requirements.txt:
# flask
# gunicorn
# gevent-websocket
# websocket-client
# websockets
# requests

URL    = 'https://demo.tradovateapi.com/v1'
socket = 'wss://demo.tradovateapi.com/v1/websocket'

app = Flask(__name__)


@app.route('/')
def dashboard():
    return 'Dash'


# Initiating with GET/POST Request
@app.route('/init')
def init():
    def onOpen(ws):
        authData = f'authorize\n2\n\n{accessToken}'
        ws.send(authData)
        print('Opened')
    def onMessage(ws, message):
        print('Incoming Message: ' + message)
        ws.send('[]')
        print('Heartbeat sent')
    def onError(ws, error):
        print('Error: ' + error)
    def onClose(ws, close_status_code, close_msg):
        print("### closed ###")

    global ws
    ws = websocket.WebSocketApp(socket, on_open=onOpen, on_message=onMessage, on_error=onError, on_close=onClose)
    ws.run_forever()
    return 'Initialized'

I would greatly appreciate any help! Thanks.

EDIT: I approached this a bit differently and changed the wording of my Google search and after 2 minutes found and implemented this wonderful solution: "How to break out of an infinite loop with flask and python using http?"

So that's the fix, so glad to have finally found this after a long, long search.

0 Answers
Related