I am trying to execute a python script from flask. I understand I need to run it on a server. I am creating this for chrome extension, so I am wondering if that's even possible to run a server everytime we need it. Furthermore, this is my code to send the request:
var url = './app.py';
$http.get(
url,
{
params: {'id': "eminem"}
})
.success(function (data) {
console.log("data");
})
.error(function (error) {
console.log("error");
});
and the python code would be:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
#app.route('/data', methods=['POST'])
def getData():
return "db"
if __name__ == "__main__":
app.run()
Any ideas what I might be doing wrong? The error I am getting is that the server cannot locate the file.
In your Flask server you are declaring the method route as /data so you should be able to call it by localhost:5000/data (I am assuming that you are running the server in your computer with the default Flask port).
For doing that you should change your first line in your JS code like:
var url = 'localhost:5000/data';
Remember that you are requesting an url not a python file, it works different in php for example.
Related
I've spent about a week on this, with no luck whatsoever. I've used chatGPT even to create the program specifically, but it still doesn't work with no inkling as to why.
I am trying to send a post request from nodejs to a python app. The issue: nothing happens on either end. The request happens, but it just gets lost in some void even though the url is exatcly correct.
here is the code:
nodejs:
const request = require('request');
const options = {
method: 'POST',
url: 'thecorrectpath/api/text',
headers: {
'Content-Type': 'text/plain'
},
body: 'Hello World'
};
request(options, (error, response, body) => {
if (error) {
console.error(error);
return;
}
console.log(body);
});
Python:
from flask import Flask, request
app = Flask(__name__)
#app.route('/api/text', methods=['POST'])
def receive_text():
text = request.data.decode('utf-8')
print(text)
return 'Text received'
if __name__ == '__main__':
app.run(debug=True)
Both apps are running(via repl.it), nothing changes when the req is sent. Here is the python app total console:
hello
* Serving Flask app 'main'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on IP
Press CTRL+C to quit
* Restarting with stat
hello
* Debugger is active!
* Debugger PIN: pinhere
Here is the nodejs app total console:
sent
Error: socket hang up
at connResetException (internal/errors.js:607:14)
at TLSSocket.socketOnEnd (_http_client.js:493:23)
at TLSSocket.emit (events.js:327:22)
at TLSSocket.EventEmitter.emit (domain.js:467:12)
at endReadableNT (internal/streams/readable.js:1327:12) {
code: 'ECONNRESET'
}
I get that Err after about 2 minutes since the request was sent. Since nothing is ever logged in python app when this is sent, im assuming it never gets to it, even though the URL is perfectly correct.
Please help/suggestions to debug.
Turns out the issue was with repl.it. I created a python template app instead of a flask app.
So here is the issue...I have had to use two separate SDK's for telnyx due to each offering a functioning service the other did not. One is in Python, one is in Node. Essentially I am sending a message from my phone to a telnyx API endpoint in python, and what I am hoping to do is communicate the number, and the message received in python over to my node.js app, which I will not have a problem formatting. I am just confused about how to communicate data between the two. Open to the smoothest suggestions. It is all server side, no client, just sending messages to a server and responding to them with another server based on the content of the messages.
Python/flask below:
import os
from flask import Flask, request
app = Flask(__name__)
#app.route('/webhooks', methods=['POST'])
def webhooks():
body = request.json
messageSenderNumber = body['data']['payload']['from']['phone_number']
messageSenderMessage = body['data']['payload']['text']
newMessageSenderMessage = messageSenderMessage.lower()
print(f"You have a new message from {messageSenderNumber}: {newMessageSenderMessage}")
return '', 200
if __name__ == "__main__":
app.run(port=5000)
Here is the Node:
var telnyx = require('telnyx').
('KEY0178B7161E6B3873C151BDC3597EE42B_SHXIHH1anGGOgfhcIb3kjQ');
telnyx.messages.create(
{
'from': '+12182101811', // Your Telnyx number
'to': '+18646662611',
'text': 'Hello, World!'
},
function(err, response) {
console.log(response);
}
);
My goal is to take the newMessageSenderMessage and messageSenderNumber variable's data and export it into my node app, that is all I need. Nothing crazy, just a phone number and a string from the python server side code, and same in node.
Thanks in advance.
Replace your return statement in the flask with this.
This should send back a JSON to your Node.js app
return {"newMessageSenderMessage": newMessageSenderMessage, "messageSenderNumber": messageSenderNumber}
OVERVIEW
Hi, I have a Flask app that works on my localhost but not in pythonanywhere. My app basically does the following:
User fills out HTML form, hits submit
Script in HTML form uses jQuery $ajax to post to my flask app on sumbit
Flask app processes the data and sends it back to be displayed as HTML
Here are some things that I think might be wrong with my app when moving it to pythonanywhere:
urllib.requests might not be included in pythonanaywhere, I know urllib is included but I'm not sure if urllib.requests is different or just a part of urllib
On my localhost, my URL for $ajax was 'http:// 127.0.0.1:5000/ebaycode/', I couldnt find any info on what youre supposed to change this to after hours of looking so I tried 'http:// mander39.pythonanywhere.com/ebaycode/' which might be wrong
I have no idea what #app.route does and maybe this is messed up when moving to pythonanywhere
HTML CODE
<script>
$('#form').on('submit', function(e){
#random css changes with jQuery i.e. $('.box').css( "display","none")
#conditionals based on form data i.e. if ($('.checkbox').is(":checked"))
e.preventDefault();
$.ajax({
url: 'http://mander39.pythonanywhere.com/ebaycode/',
data: {'product': product, 'sold': sold, 'cond': cond},
method: 'POST',
success: function(data) {
#using $('#id').html to show my data output on my site
}
});
});
</script>
FLASK APP
from flask import Flask, render_template, request, jsonify
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
from statistics import mean
import numpy as np
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/ebaycode/', methods=['POST'])
def ebaycode():
prod = str(request.form.get('product', 0))
sold = str(request.form.get('sold', 0))
cond = str(request.form.get('cond', 0))
#whole bunch of other code
data = {'ebaycode': ebaycode,'lengthOne': lengthOne,'maxOne': maxOne,
'minOne': minOne,'avgOne': avgOne,'medOne': medOne, 'lengthTwo': lengthTwo,
'maxTwo':maxTwo, 'minTwo':minTwo,'avgTwo': avgTwo,'medTwo': medTwo, 'url': tac
}
data = jsonify(data)
return data
def reject_outliers(data, m = 3.):
#method called in ebaycode()
if __name__ == '__main__':
app.run(debug=True)
I wish I had a command prompt to show what my app is doing but bash and python cmd from pythonanywhere dont show anything. Thanks a bunch for the help, I really need it.
i am new to backend dev. I try to developp a flask restful api. I followed the documentation and made the suggested minimal api, that is just returning a jsonified dict. With postman, curl and in the browser, no problem, the api is running and responds to my requests.
From my react native app however, i always get a Netwrok Error.
I tried lots of things:
- multiple IP addresses for the flask serveur
- differents ways to use axios
- different os : win10, ubuntu
- different endpoints : /, /api, /test
- different ways of writing the api (flask-restful class, flask app functions ...)
- manips from web documentations : dev mode of my device, chrome dev tools (port forwarding)
- i asked a react native developper to check my client-side code, nothing wrong according to him,
precisions :
- python code runs under a conda virtual env
- appli runs under node js and expo
- container folders of my app and my api are at the same level
- the flask server does not respond 404 or whatever, it does not respond at all, the error returned in react native is a network error
- depending on url, the network errors occurs immediately or after a 2 minutes delay
- flask shows requests and status when called by postman, curl, chrome, but does not react when i press my buttons from the react native app
Here is (one of) my python code:
from flask import (Flask, jsonify)
# from flask_restful import Resource, Api
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
#app.route("/api", methods=["GET"])
def get():
return jsonify(hello='bouh !')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)
and here is the clientside code:
import React, {Component} from 'react';
import { View, Button } from 'react-native';
import axios from 'axios';
import { sharedStyles } from '../../SHARED/_shared';
var url = "http://192.168.1.16:5000/api";
export default class PrevCommune extends Component {
constructor(props){
super(props);
this.navigation=this.props.navigation;
};
getAxios=()=>{
axios.get(`${url}`).then((response)=>{
console.log("succes axios :",response);
}).catch((error)=>{
console.log("fail axios :", error);
});
};
getFetch=()=>{
fetch(url).then((response)=>{
console.log("succes fetch :",response)
}).catch((error)=>{
console.log("fail fetch :",error)
})
}
render(){
return (
<View style={sharedStyles.mainContainer}>
<Button onPress={()=>this.getAxios()} title={"get axios"}></Button>
<Button onPress={()=>this.getFetch()} title={"get fetch"}></Button>
</View>
);
};
};
And the lines returned by requests:
fail axios : [Error: Network Error]
fail fetch : [TypeError: Network request failed]
I saw lots of tutos, videos, articles on flask api but i didn't find where i am wrong. Please tell me if you have any ideas ! I think both client and server codes are ok, the problem seems to be that my requests are blocked by something.
Solved : the probleme was my firewall ... thank you ricardo for the CORS doc =)
What worked for me was to change the IP address of localhost to my network IP in the api call in react native and then starting the flask application using the below command.
flask run --host=0.0.0.0
Trying to use AJAX to POST to my Python script testing.py. Whenever I try the POST, I receive the following error.
POST http://localhost:5000/testing.py 404 (NOT FOUND)
I'm using Flask to serve up my website. Why is this a 404 error, and how do I get localhost to serve my python script?
somewhere you should have a file called app.py,(but you can call it testing.py if you want) inside should be at least:
from flask import Flask, request
app = Flask(__name__)
#app.route('/testing') # you can probably even put testing.py here
def testing():
vars = request.args
return ','.join(map(str,vars))
if __name__ == "__main__":
app.run()
then
python app.py # or testing.py
then you can send your POST to http://localhost:5000/testing
and it will print any posted parameters to the browser