Forums

Scheduled tasks in flask app need app context

I have an app-factory styled web-app running and I want to access it daily to check for expired database entries. There are functions within the program to do this, but I have not been able to access them unless I manually start a flask shell from the environment console. I tried running the following script but it hangs after the call to flask shell.

#!/bin/bash
source virtualenvwrapper.sh;
workon /VENV;
flask --app PROJECT shell;
import PROJECT.main.utils.check_expired;
check_expired();
quit();
deactivate;

[edit by admin: formatting]

The workon command should just take the name of the virtualenv, rather than the path. Try putting the python code into a separate file and then executing the file.

I tried that and got:

from: can't read /var/mail/__future__
import-im6.q16: unable to open X server `' @ error/import.c/ImportImageCommand/359.
mport-im6.q16: unable to open X server `' @ error/import.c/ImportImageCommand/359.
mport-im6.q16: unable to open X server `' @ error/import.c/ImportImageCommand/359.
bash: /bin/pythonanywhere_runner.py: line 9: syntax error near unexpected token `('
bash: /bin/pythonanywhere_runner.py: line 9: `__old_modules = list(sys.modules.keys())'
Console closed.

I'm looking on the internet to see if I can open this shell from a pyton file

[edit by admin: formatting]

That looks like an error from the run button in our editor. The most likely cause that I can think of is that you just renamed a bash script to have a .py extension to run it there. That will not work. The run button in the editor is for Python files.

I have not been able to write a python program to get access to the flask web app or create a flask shell to work in. I found that another person had this problem on the PythonAnywhere forum, but did not get a resolution. So...

I tried to use the requests package to get to the route that does the work as follows:

import requests
response = requests.get("https://www.MYWEBSITE.com/chk_expired")
print(response)
print(response.text)

What I got back was:

<Response [401]>
Unauthorized

The route does not require any user to be logged in, don't know what else to try.

[edit by admin: formatting]

Is the website you're trying to access the one that you have configured on the "Web" page on PythonAnywhere? You do have authentication set up for that, using the "Password protection" section at the bottom of the page. To access it using requests, you'll need to use its HTTP basic auth parameters.

That you for that observation, couldn't see the forest for the trees, problems solved.

Glad to hear you solved that!