0

I wrote a simple application that fetches stock quotes online, and post buy/sell orders. Now this is all done through the console. I read and followed a couple tutorials on Flask web apps. But I can't figure out how to run the server while fetching information to display on the Flask app at the same time.

The goal is to fetch the quotes for my watchlist, and display it on my index.html (localhost)

Here is what I tried to no avail:

  1. Run my looping requests in one thread, and another thread to run the server. - Server wont start!

  2. Run app.run() nested in main().

Please point me in the right direction to learn.

app = Flask(__name__)


@app.route('/')
def index(watchlist=None):
    return render_template("index.html", watchlist=watchlist)


app.run()
################# main code has most of it's functions stripped out for legibility
def main():
qt = Questrade.Questrade()
qt.update_all()
watchlist = Watchlist.Watchlist(qt.quotes)

loop_count = 0
while 1:
    print("loop start")
    qt.update_all()
    watchlist.update_stocks(qt.quotes)
    loop_count += 1
    print("loop end")
    print(loop_count)
    time.sleep(10)
fool
  • 11
  • 1
  • 6

1 Answers1

2

If you want to run background task please consider using celery or apscheduler for it.

This answer about how to execute background task in task using celery.

conf

Please configure celery conf like this

celery.conf.beat_schedule = {
    'watch-every-10-seconds': {
        'task': 'tasks.watchstock',
        'schedule': 10.0,
        'args': (16, 16)
    },
}

Run celery beat by celery beat --app myproject

views

from flask import Flask

flask_app = Flask(__name__)
flask_app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379',
    CELERY_RESULT_BACKEND='redis://localhost:6379'
)
celery = make_celery(flask_app)


@celery.task()
def watchstock():
    --- your function code ---

Create task function that can execute in a loop to get the stock for you and then save this into Database.

Raja Simon
  • 10,126
  • 5
  • 43
  • 74