Reputation: 889
I have a Python script that prints and returns all image files from a folder in the server.
import os
images = ""
for dirname, dirnames, filenames in os.walk('..\directory'):
for filename in filenames:
images = images + os.path.join(dirname, filename) + "^"
print(images)
return images
I am calling this in Javascript using:
$.get("scripts/filename.py", function(data){
alert(data);
});
However, instead of the getting the 'printed' or returned data, it is just displaying the code from filename.py. Am I missing something here?
EDIT: By the way, I am using Google App Engine to host my website.
Upvotes: 4
Views: 5404
Reputation: 207501
Do you have Python set up to run on your server?
Upvotes: 1
Reputation: 5736
You need to have some Web Framework setup like Flask or cherrypy. I would suggest go with Flask, it's the easiest Web Framework to get started with.
And then you need to have some endpoint to which you can send an AJAX GET
Request, and then your Python script will return a JSON response. You can iterate through this JSON response to print out the results.
This code might work out for you:
import sys, os
from flask import Flask, request, url_for, render_template
@app.route('/images')
def index():
images = ""
for dirname, dirnames, filenames in os.walk('..\directory'):
for filename in filenames:
images = images + os.path.join(dirname, filename) + "^"
print(images)
# return a json encoded response
return Response(json.dumps(images, sort_keys=True, indent=4), mimetype='application/json')
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Now you need to start the server, and whenever you send a GET Request at localhost:5000/images
it will return the JSON response you're looking for.
Upvotes: 2