Jacob
Jacob

Reputation: 359

Calling Python file in an Ajax Call

So I have established a pretty decent understanding of the simple architecture of an angularjs app, calling $http and posting to a php page, and receiving data back.

What I'm wondering, is how to do the same type of function with python. Is it possible to have python act the same, with self contained script files that accept post data and echo json back?

$username = $_POST['username'];

type variable assignment at the beginning of the script, and:

echo json_encode(response);

type response.

I'm wanting to use Python for some Internal Tools for my company, as it offers better libraries for remotely running powershell scripts (as the tools are all linux hosted) and overall just has libraries that fit my needs. I'm just having a difficult time finding a concise answer to how this could be set up.

---EDIT------

So I set up a quick example using the information below.

the angular: var app = angular.module("api");

app.controller("MainController", ["$scope","$http",MainController]);

function MainController($scope,$http){

    $http.post('/api',{test: "hello"})
        .then(function(response){
            console.log(response.data);
        })

}

The flask: from flask import Flask, request import json

app = Flask(__name__)


@app.route('/api', methods=['POST', 'GET'])
def api():
    if request.method == 'POST':
       request.data
    return 'You made it' # Just so I originally could see that the flask page                    

if __name__ == "__main__":
    app.run()

I'm getting a 404 for that URL. If I change the angular to look at 'localhost:5000/api' (where my flask app is running),it gives me the error of "Unsupported URL Type".

I am seeing when I do the first case, it tries to look at http://localhost/api , which is correct! except for the port. Which is why I tried to specify the port.

Any suggestions for a next step?

Upvotes: 0

Views: 2217

Answers (1)

JonathanG
JonathanG

Reputation: 292

Use flask.

You could host your app on a flask "server" and return the content you'd like too with a python processing.

http://flask.pocoo.org/

Use the documentation to setup a route where you'll POST your data using jquery or whatever, then on the route you can do your python stuff and return a JSON to your angular app if you need to.

 from flask import request   

 @app.route('/test', methods=['POST', 'GET'])
    def test():
        if request.method == 'POST':
            print request.data['your_field']

        return your_json_data

Upvotes: 3

Related Questions