I am attempting to create a personal use application that gets long and short data from a api. After getting the data, the application should store it in a database and display it on a JavaScript chart. The chart should update every hour (for testing purposes, it's currently set to update every minute) and display the last 24 hours of information. Everything works properly on my computer locally, even after creating a database with Render and connecting it. However, when I deploy the application on Render it doesn't store data to database at all so because of that the chart doesn't work. But when I run app locally at the same time it stores data to database so following that my chart on deployed site works as it should. Can someone help?
from flask import Flask, render_template, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
from flask_socketio import SocketIO
import threading
import time
import requests
from flask_cors import CORS
from flask import current_app
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://ihdawhiahdwihiowadhoia_user:[email protected]/ihdawhiahdwihiowadhoia"
db = SQLAlchemy(app)
socketio = SocketIO(app)
CORS(app)
class ForexData(db.Model):
id = db.Column(db.Integer, primary_key=True)
currency_pair = db.Column(db.String(10))
timestamp = db.Column(db.DateTime, default=datetime.now)
short = db.Column(db.Integer)
long = db.Column(db.Integer)
data_lock = threading.Lock()
def get_and_store_data():
url = "https://www.myfxbook.com/api/get-community-outlook.json?session=sessionid"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
target_currency_pair = "EURUSD"
target_symbol = next((symbol for symbol in data["symbols"] if symbol["name"] == target_currency_pair), None)
if target_symbol:
short_percentage = target_symbol["shortPercentage"]
long_percentage = target_symbol["longPercentage"]
print(f"Short Percentage: {short_percentage}%")
print(f"Long Percentage: {long_percentage}%")
with data_lock:
data_entry = ForexData(currency_pair=target_currency_pair, short=short_percentage, long=long_percentage)
db.session.add(data_entry)
db.session.commit()
else:
print(f"Could not find data for {target_currency_pair}")
else:
print("Error:", response.status_code)
def start_scheduler():
with app.app_context():
# Create database tables
db.create_all()
while True:
current_time = datetime.now()
next_minute = (current_time + timedelta(minutes=1)).replace(second=0, microsecond=0)
wait_seconds = (next_minute - current_time).total_seconds()
time.sleep(wait_seconds)
get_and_store_data()
@app.route('/')
def index():
latest_data = ForexData.query.filter_by(currency_pair='EURUSD').order_by(ForexData.timestamp.desc()).limit(24).all()
timestamps = [entry.timestamp.strftime("%H:%M") for entry in latest_data]
shorts = [entry.short for entry in latest_data]
longs = [entry.long for entry in latest_data]
return render_template('index.html',timestamps=timestamps, shorts=shorts, longs=longs)
@socketio.on('connect')
def handle_connect():
print('Client connected')
send_initial_data()
try:
with app.app_context():
latest_data = ForexData.query.filter_by(currency_pair='EURUSD').order_by(ForexData.timestamp.desc()).limit(24).all()
formatted_data = [
{'timestamp': entry.timestamp.isoformat(), 'short': entry.short, 'long': entry.long}
for entry in reversed(latest_data)
]
socketio.emit('initial_data', formatted_data)
except Exception as e:
error_message = str(e)
app.logger.error("An error occurred while fetching data: %s", error_message)
socketio.emit('initial_data', [])
def send_initial_data():
data = {
'message': 'Initial data',
'other_data': [1, 2, 3, 4, 5]
}
socketio.emit('initial_data', data)
@app.route('/get_latest_eurusd_data')
def get_latest_eurusd_data():
try:
with app.app_context():
latest_data = ForexData.query.filter_by(currency_pair='EURUSD').order_by(ForexData.timestamp.desc()).limit(24).all()
formatted_data = [
{'timestamp': entry.timestamp.isoformat(), 'short': entry.short, 'long': entry.long}
for entry in reversed(latest_data)
]
return jsonify(formatted_data)
except Exception as e:
error_message = str(e)
app.logger.error("An error occurred while fetching data: %s", error_message)
return jsonify({'error': 'An error occurred while fetching data'}), 500
if __name__ == '__main__':
threading.Thread(target=start_scheduler).start()
socketio.run(app, debug=True)