Deploying the Flask App with Websockets Issue

Hi there,

I have a very simple Flask app that is working perfectly locally. Unfortunately I’m not able to deploy it on Render. Here is the code:

from flask import Flask, request, render_template_string
from flask_socketio import SocketIO, emit
import json
import requests

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")  # Consider CORS needs

HOME_PAGE_TEMPLATE = '''
<!doctype html>
<html lang="en">
<head>
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
  <title>Fetch Data</title>
  <style>
    .form-container {
      max-width: 500px;
      margin: 100px auto;
    }
  </style>
</head>
<body>
<div class="form-container">
  <form id="dataForm" class="text-center">
    <div class="form-group">
      <label for="makerUserId" class="h4">Enter UserId:</label>
      <input type="text" class="form-control" id="makerUserId" name="makerUserId" required>
    </div>
    <button type="submit" class="btn btn-primary">Fetch Data</button>
  </form>
</div>
<div class="container text-center mt-5" id="resultsContainer">
  <h2>Results:</h2>
  <div id="status">Waiting for input...</div>
  <div id="results"></div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script>
  // Determine the correct protocol to use for the WebSocket connection
  var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
  var socket = io(ws_scheme + '://' + document.domain + ':' + location.port);

  socket.on('connect', function() {
    $('#dataForm').submit(function(e) {
      e.preventDefault();
      $('#results').empty();
      $('#status').text('Work in Progress...');
      var makerUserId = $('#makerUserId').val();
      socket.emit('fetch_data', { makerUserId: makerUserId });
    });
  });

  socket.on('update', function(data) {
    $('#results').append('<p>' + data.result + '</p>');
  });

  socket.on('completed', function(data) {
    $('#status').text(data.message);
  });
</script>


</body>
</html>
'''

# Optimize data handling in your data fetch function
def fetch_data(crypto, fiat, makerUserId, side):
    url = "https://api2.bybit.com/fiat/otc/item/online"
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    payload = json.dumps({
        "userId": 71473441,  # Consider if all these parameters are necessary
        "makerUserId": makerUserId,
        "side": side,
        "tokenId": crypto,
        "currencyId": fiat,
        "page": "1",
        "size": "100"  # Adjust size based on actual needs to reduce memory usage
    })

    try:
        response = requests.post(url, headers=headers, data=payload)
        if response.status_code == 200:
            data = response.json()
            action = "Sell to User" if side == "0" else "Buy from User"
            # Only process necessary parts of the response to minimize memory usage
            count = data['result'].get('count', 'N/A') if data and 'result' in data and data['result'] else "No Results"
            return f"{crypto}-{fiat} {action}: {count}"
        else:
            return f"Failed to fetch data for {crypto}-{fiat}. Status Code: {response.status_code}"
    except Exception as e:
        return f"An error occurred while fetching data for {crypto}-{fiat}: {e}"

@app.route('/', methods=['GET'])
def home():
    return render_template_string(HOME_PAGE_TEMPLATE)

# Optimize SocketIO event handling
@socketio.on('fetch_data')
def handle_fetch_data(json_data):
    makerUserId = json_data['makerUserId']
    crypto_list = ['USDT', 'BTC', 'ETH', 'USDC']
    currencyList = ["GEL", "USD"]
    
    # Consider batching or limiting the amount of data processed in a single event
    for crypto in crypto_list:
        for fiat in currencyList:
            for side in ["0", "1"]:
                result = fetch_data(crypto, fiat, makerUserId, side)
                emit('update', {'result': result})
    emit('completed', {'message': 'Code Execution Complete'})

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=10000, debug=True)

Please tell what am I doing wrong :frowning:

Hi there,

Could you provide a little bit more information about exactly what is not working? Screenshots and error logs are a great place to start.

If you’re not seeing anything in your application logs, you can always add some additional logging to help with your troubleshooting.

Regards,

Matt

Hi VakhoGeoLab,
I’m too facing the same issue, did you find any solution? please reply