Home > Enterprise >  Second task with flask app on pythonanywhere
Second task with flask app on pythonanywhere

Time:02-18

I am using python anywhere to host a flask app that has 2 components: 1) a website to show some stuff from a txt file and 2) a python script to do some API stuff and change the data in the txt file.

Currently, I can run both of these separately without issue but I cannot use them together. I have tried to use threading but it doesn't work.

Basically, the background script (part 2) is in backend.py called by mainloop() consists of some API calls to other websites, modifying the txt file then sleeping for an hour.

wsgi.py

import sys
path = '/home/michalis95/API-updater'
if path not in sys.path:
    sys.path.append(path)

from threading import Thread
import website
application = website.create_app()

/website/__init.py__

    from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from threading import Thread
from flask_login import LoginManager

db = SQLAlchemy()
DB_NAME = "database.db"

def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    from .models import User, Note

    create_database(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    import backend
    def run():
        t=Thread(target=backend.mainloop())
        t.start()
    run()
    return app

def create_database(app):
    if not path.exists('website/'   DB_NAME):
        db.create_all(app=app)
        print('Created Database!')

backend.py

def mainloop():
  while True:
    #do stuff
    time.sleep(3600)

CodePudding user response:

The problem was in

    def run():
       t=Thread(target=backend.mainloop())
       ...

it should be

def run():
   t=Thread(target=backend.mainloop())
   ...

CodePudding user response:

You might need to look into Always-on tasks,

"Always-on tasks are scripts that are kept running all the time, and restarted if they crash."

I use them, they are really effective.Depending on the plant you have, They cost about a buck per month, but they do the job.

  • Related