Run python script from Parse Cloud Code (Background Job) - python

Main.js
Parse.Cloud.job("grabPrices", function(request, status) {
// Set up to modify user data
Parse.Cloud.httpRequest({
method: 'POST',
url: 'http://xxx.parseapp.com/xxx.py',
success: function(httpResponse) {
console.log(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
}
})
});
Main.js is a Parse Cloud Job that I want to run which basically accesses a python script and runs it. Is this possible? If so, what changes do I make in my code?

I solved my problem by using Heroku.
My code is similar to #AlexCoren's answer, shown below:
Parse.Cloud.job("grabPrices", function(request, status) {
// Set up to modify user data
Parse.Cloud.httpRequest({
url: 'https://xxx.herokuapp.com/',
success: function(httpResponse) {
console.log(httpResponse.text);
status.success("Pricelist grabbed successfully!");
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
status.success("Oops.... something went wrong.");
}
})
});
And for heroku, I just slightly modified the views.py file (I just followed the tutorial 'Getting started with python', downloaded the example project and modified the \python-getting-started\hello\views.py file):
from django.shortcuts import render
from django.http import HttpResponse
import urllib2
import urllib
#import requests
import json, httplib
import time
from datetime import datetime
from .models import Greeting
# Create your views here.
def index(request):
# I put my python code here so it will run at the url `https://xxx.herokuapp.com/'

I do something similar in one of my apps. I hosted it on Heroku. The code looks as follows:
Parse.Cloud.define('MyFunction', function(request, response) {
var someParam = request.params['SOME_PARAM'];
var url = 'http://myapp.herokuapp.com/?param=' + someParam;
Parse.Cloud.httpRequest({
url: url,
success: function(httpResponse) {
console.log(httpResponse.headers);
console.log(httpResponse.text);
response.success();
}, error: function(httpResponse) {
response.error('Uh oh!');
}
});
});
That url specifies a parameter which gets sent to my server to and then used as a parameter in my python script.

Unfortunately, this is not possible. Parse backend only executes javascript files (cloud code folder) or html, css and javascript files (public folders).
Even if you are able to upload a python file to one of the folders, you want be able to execute the file.
You can upload your python file to your public folder and you would have a URL for it (mysubdomain.parseapp.com/python_file.py) but if you use Parse.Cloud.httpRequest, you'll get the content of the file, the server won't execute the file.
For example, if your python file has the following code:
print "Hello World!"
The result you'll get on your httpRequest will be:
print "Hello World!"
Instead of:
Hello World!
Which is what you want.
The python file should be hosted in other server that executes python.
I hope this makes sense.
Javier.

Related

Flask HTML/AJAX page Linking Issue

I have created a FLASK app which preforms CRUD operations on an SQL database. I had everything work a few days ago but now when using the web interface the HTML pages aren't working when clicked. For example after entering valid details and clicking login the URL now looks like:
incorrect url path
when it should redirect to
correct url path
showing in terminal
terminal
This is my folder layout
folder layout
My AJAX call to redirect to main.html
`
// Login a user
function userLogin() {
data = getLogin()
console.log(data)
$.ajax({
url:"http://127.0.0.1:5000/login",
data: JSON.stringify(data),
method:"POST",
dataType:"JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result == 1) {
window.location.replace("main.html"); // Redirect to to main.html if successful
}
},
error: function(xhr, status, error){
window.alert("Invaild username and/or password");
console.log("error "+ error + " code "+ status)
}
})
}
`
Flask Server route:
`
# Homepage route
#app.route('/')
def index():
if not 'username' in session:
return app.send_static_file('index.html')
# Login
#app.route("/login", methods = ["POST"])
def login():
account = {
"username":request.json["username"],
"password":request.json["password"]
}
return jsonify(bookmarkDAO.login(account))
`
I've tried deleting the cache, changing my folder directories around and I even tried an older version which correctly worked from my github repository but now it is even throwing the same error. I am using VS Code, could it possibly be an issue with the terminal?
You are not trailing the main.html with /
Change this
window.location.replace("main.html")
to
window.location.replace("/main.html")

Weird Axios Network Error with seemingly error-free code

I am trying to use react to get data from an API (Python, I'm hosting it on the same machine).
API Code:
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/')
def all_data():
all_data = "Hello"
return jsonify({
'data':all_data,
'message':"success"
}), 200
if __name__ == "__main__":
app.run(debug=True)
React code(Didn't include the render()):
export default class HomeScreen extends Component {
constructor(props){
super(props);
this.state = {
listData:[],
url:"http://localhost:5000"
}
}
getPlanets=()=>{
console.log("Axios called")
const url = this.state.url;
console.log(url)
axios.get(url).then((response)=>{
console.log(response.data)
return this.setState({listData:response.data})
}).catch((error)=>{
console.log(error.message)
Alert.alert(error.message);
})
}
componentDidMount(){
this.getPlanets();
}
}
I'm always getting Network Error for the console.log(error.message).
I'm also getting a larger Error: "Network Error" in Error: Network Error << at e.exports (axios.js:3:7286) << at d.onerror (axios.js:3:6270) for console.log(error).
Simultaneously, I got two weird error messages in my API:
code 400, message Bad request version ('localhost\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')
"▬♥☺☻☺☺ü♥♥ÆuaTÁS¾eài ¸ ²`½‼/cùCf{&*½(¨qh↓(â®z↨Ó ×D ÚÚ‼☺‼☻‼♥À+À/À,À0̨̩À‼À¶úú♫♀ l
ocalhost↨ÿ☺☺" HTTPStatus.BAD_REQUEST -
Help?
I've tried looking through a lot of websites for the problem, but they all just suggested adding the http:// prefix to my url, which I had already done. I'm also using Python for the API and not NodeJS, so I don't need to use CORS. I just couldn't find a relevant fix anywhere.

Why am I Unable to send an image from flask to react using "Send_file"

I have created a react app that takes information from a react frontend, sends it to a flask backend with axios, which then processes the information and creates a new image. Im trying to get flask to send the image via send_file to react, but i'm not sure how to do it. I tried saving the image as a png, and then sending it, but the react side can't use that since it's encoded.
Here's what's going on:
flask:
img = Image.fromarray((np.uint8(cm(img)*255)))
img.save("./thenewimg.png")
return send_file('./thenewimg.png','image/png')
react:
class App extends React.component{
onReturnProcessed = res =>{
console.log(res.data)
this.setState({img:res.data})
this.setState({ImgReturned:true})
console.log(res.data.img)
}
return axios
.post(`http://localhost:5000/time`, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
this.onReturnProcessed(res);
return res
});
}
render(){
return(
<div>
{this.state.ImgReturned &&
<img src={(this.state.img)} />}
</div>
);
}
}
React then sets the state variable "img" to whatever flask returns (namely, the file that flask sends to it). I try to display this state variable in an image html line, but it doesn't let me. Any ideas on how to do this?
note:
neither of these is the full code, but I think they give most of what is needed to get an idea of what is done.
Heres some of what is printed in console when the "img" state variable is logged: �m�O<���+����� ��S����i�<��G�~qZrޱ�����s�~9���
You're passing a second positional argument to send_file which it doesn't accept.
I think you're looking for:
return send_file('./thenewimg.png', mimetype='image/png')
However, as you're passing a filename as the first argument it should automatically detect the mimetype, based on that .png extension, so you'd probably get away with just:
return send_file('./thenewimg.png')

Python flask server issue

Could you please help me with Python-Flask server misunderstanding. I have some project with flask, it perfectly works on local server 127.0.0.1, but when I moved it to the Web Server (blue host), some of my script give me these errors:
Here I have jQuery, Ajax response to show a table without reloading page:
<button class="myButton" id = "Lbutton">Load</button>
<script>
$("#Lbutton").click(function(){
$.ajax({
url: "/table,
type: "get",
data: {jsdata: $( "#select option:selected" ).text()},
success: function(response) {
$("#place_for_suggestions").html(response);
},
error: function(xhr) {
// handle error
}
});
});
</script>
url: "/table, is the link for Flask function:
#FlaskApp2.route('/table')
def table():
modid = request.args.get('jsdata')
return render_template('table.html')
But finally the Server gave me error:
File does not exist: /home1/user/public_html/table
Why direct link for action, server understand like a link for a file?
So, every action to Python-Flask
<form action="/sendemail" method="post">
the Server understand like a link and give an error message !
What I'm doing wrong ?
Solved, I need to put the full path in action and route() decorator #app.route "/.../templates/table.html"
Most likely you need to add the POST method to your route definition.
#FlaskApp2.route('/table')
becomes:
#FlaskApp2.route('/table', methods=['GET', 'POST'])
Check out the documentation here:
http://flask.pocoo.org/docs/0.12/quickstart/#http-methods
Which has an example of an endpoint that accepts both GET and POST HTTP methods.
Also check out a related question: Flask example with POST

Sending Ajax request to call a python function through jquery

I am trying to send a request to call a python method in my python script.
Server Side:
I am using flask ,so the server is running on port 5000.It has a file called helloflask.py which look like
#helloflas.py
from flask import Flask
app = Flask(__name__)
#app.route("/hello",methods=['GET','POST'])
def hello():
return "Comming Here"
if __name__ == "__main__":
app.run(port=5000,debug=True)
Client Side:
Independent HTML outside of flask which is sending the ajax request.
<!--ajax call-->
<script>
function findAppartment() {
$.ajax({
url: "https://127.0.0.1:5000/hello/",
type: "get",
contentType: "application/xml; charset=utf-8",
success: function (response) {
// $('#blurg').html(response).fadeIn(1500);
}
});
}
</script>
when the request is made,I get the following error.It hits the server and gives the following error:
Error : code 400, message Bad request syntax ('\x16\x03\x01\x00\xa1\x01\x00\x00\x9d\x03\x02Q\xd8\xc0O+\x8f\xa6\x16F\x9a\x94\x90|$\x11\xd3\xd8\x15\x04$\xe4\xb4>\xc0\x0e\xe3\xa0h\xea\x07\x00\xc5\x00\x00H\xc0')
I tried many things but things don't seem to be working.Could any one help???Any help is highly appreciated.

Categories