Forums

Location of source code

I have a python script which i want to be able to access at http://mysubdomain.pythonanywhere.com/test.py

I am completely confused where to put this file and how to make it accessible, please can you let me know the directory which I should put the file in?

I have created a web app with the manual configuration setting

Do you just want to access/download it? Or do you actually want to run the script? What is the use case for this?

Yes i want to run the script, it will be a simple script which will connect to a api and display some data on the page.

When I currently go to /test.py it says page not found but I'm not sure which directory it is looking in for the test.py file.

I solved this by adding forwarders to my flask application, something like:

@application.route('/test.py')
def test_py():
    import imp
    test = imp.load_source('test', '/home/myusername/test.py')
    return test.web()

Here, 'imp' is being used to manually load 'test.py' as a module without first setting up module paths. 'test_py' is just a Flask request handler that forward the request on to 'test.py', invoking the 'web' function defined in test.py. Just implement 'def web():' to render the page you want and return it as a string.

Note that you can lift the call to 'load_source' outside of test_py.

That's a neat trick, thanks for sharing! It might be easier in the long run to set up the module path by changing sys.path in the WSGI file -- there's already code there that does some of that, so you can just extend it. But that's a judgement call on your part :-)

Thank you that seems to work.

I have another problem, I successfully installed a module as described at https://help.pythonanywhere.com/pages/InstallingNewModules/

but when i try to import it in test.py it gives the error 'ImportError: No module named ', any ideas why this is happening?

Which version of Python are you using for your website? It's important that the version of pip you use to install matches the version your website is set up to use, eg. pip2.7 for Python 2.7, and so on.

It works now I have used pip3.5 install instead of just pip install, thank you!

Excellent, thanks for confirming!