I'm trying to send some data from my frontend (react native) to a flask application running on a remote computer. Something isn't working and I'm not sure where the problem lies.
The flask app is listening on port 5000 on the remote server. I've tried simply sending a post request to the IP address of the server (with the port), but this doesn't work.
On my frontend I have this code:
fetch('http://18.222.109.76:5000/add_New_Entry', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
}).then((response) => /*do something with response*/
));
On my backend I have this code as part of the flask app:
app = Flask(__name__)
app.debug = True
app.config['CORS_HEADERS'] = 'Content-Type'
CORS(app)
#app.route("/")
def hello():
return ""
#app.route('/add_New_Entry', methods=['GET', 'POST'])
#cross_origin(origin='*',headers=['Content- Type','Authorization'])
def add_New_Form():
print('bla')
return ""
if __name__ == '__main__':
app.run(debug=True)
So, I expect that if I run the piece of code from the frontend, the server will print "bla", but it doesn't, and no sign of failure appears on the frontend as well (maybe it's because I failed to catch the exception?)
So I finally figured it out. Apparently it was because I was using a remote Amazon server, and I had to open its ports on the amazon interface.
After I did, this worked flawlessly.
Related
I am trying to create a simple chat app by using flask and flask_socketio and it works but the WebSocket upgrade doesn't happen and it gives me this error properly
The WebSocket transport is not available, you must install a WebSocket server that is compatible with your async mode to enable it. See the documentation for details. (further occurrences of this error will be logged with level INFO)
and I saw many tutorials and ended with installing (gunicorn, gevent, eventlet) and updating the packages and the library but when I run the app it works and the message sent from the client to the server and broadcasting it again to all the client but the connection is not websocket it's pooling
the server-side
from flask import Flask, app, render_template, redirect
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'test'
socketio = SocketIO(app)
#app.route('/')
def main():
return render_template('chat.html')
#socketio.on('message')
def message_func(data):
socketio.send(data)
if __name__ == '__main__':
socketio.run(app)
the client
var socket = io('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
console.log('connected');
})
socket.on('message', function(data) {
const p = document.createElement('p');
const br = document.createElement('br');
p.innerHTML = data;
document.querySelector('#panel').append(p);
})
document.querySelector('#send').onclick = () => {
socket.send(document.querySelector('#userin').value)
}
In the "Deployment: Gunicorn Web Server" documentation it says
In the documentation of When using gunicorn with the gevent worker
and the WebSocket support provided by gevent-websocket, the command
that starts the server must be changed to select a custom gevent web
server that supports the WebSocket protocol. The modified command is:
gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 module:app
For that to work you additionally need to install gevent-websocket.
So, I have a local script, which should output a specific message to display to the client of an user connected in the flask app.
From local script to server I've used:
import requests
requests.post(address, json=json)
And the message is received correctly to the server. Problem is that I can't manage to get it displayed through the client because doing something like:
from flask import render_template, url_for, redirect, request
#app.route('/home', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
result = request.json
return render_template('home.html', result=result, title='Homepage', current_user=current_user)
Doesn't effectively render any template.
I suspect that it's due to the nature of a socket connection, so probably I should set up a similar architecture using sockets events.
Problem is that I'd like to have for each user a unique message displayed on the home route and I fear that with sockets it would be impossible to do so.
Forgive me for the bad explanation of my question, I'm still a newbie regarding networks and web development with Flask.
Resolved, it was easier than I imagined. I ended up using socket events instead of http in the end. Here's the code from the server and client side (simplified for others that might have a similar situation).
The only thing that sucked was not being able to use jinja2 to display elements in the webpage. But with a bit of (bad) js I resolved.
Server side:
#app.route('/home', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
result = request.json
socketio.emit('my_socket_event',
result,
broadcast=True #use broadcast=True if you want the message to be displayed to all connected clients
)
Client side:
<script>
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('my_socket_event',function(result) {
console.log('[EVENT CALLED] my_socket_event')
for (var elem in result) {
let htmlFrag = "<p>" + elem + "</p>"
$('.container').append(htmlFrag);
}
})
</script>
This question already has an answer here:
Error when check request.method in flask
(1 answer)
Closed 4 years ago.
I am attempting to route my Flask routes and see the correct return from Flask (the returns indicated in my code below). When I direct my page to mypage.com/, I do see the output, but it seems to be returning the xxamp apache index page in my console when I am expecting to see "hello world".
here is my directory listing:
/localhost
/my_dir
/js
/templates
app.py
Here is my AJAX call to /:
js:
$(function(){
$('button').click(function(){
var user = "user";
$.ajax({
url: '/',
data: user,
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});
And here is my Flask:
app.py:
from flask import Flask, request, send_file, render_template, json
from ftplib import FTP
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'hello world!'
if __name__ == "__main__":
app.run()
There seems to be a disconnect here. I believe my Apache is running on 80 where Flask is listening on 5000. So my javascript AJAX call is actually making a call to port 80 instead of 5000, hence, why I think I am seeing a different return than expected. Do I have to specify the port in my AJAX call, or should I have flask listen on port 80?
Try to add POST with acceptable method
#app.route('/index', methods=['GET', 'POST'])
def index():
return render_template('index.html')
My backend is an AWS EC2 server that runs on flask, I'm trying to port over my code from http to https. I've used letsencrypt and certbot to create valid certificates. My flask backend accesses the certs and then calls the host. I tried adding SSLify after looking through other posts ( and seeing that it can be used with Flask, but it didn't change anything.
from flask_cors import CORS
from flask_sslify import SSLify
from OpenSSL import SSL
app = Flask(__name__)
CORS(app)
sslify = SSLify(app)
sslify
if __name__ == "__main__":
context = ("../../../../etc/letsencrypt/live/app.mydomain.name/fullchain.pem","../../../../etc/letsencrypt/live/app.mydomain.name/p$
app.run(host='127.0.0.1', port=5000, debug=True, ssl_context=context)
On the React frontend side, I'm using axios
axios.post('https://127.0.0.1:5000/run_query', postData, axiosConfig)
.then(function (response) {
console.log("Successful connection");
console.log(response.data);
influencerList = response.data.query_results;
console.log(influencerList);
currentComponent.setState({IL: influencerList});
})
.catch(function (error) {
console.log(error);
});
using app.run options I listed above on the backend returns
xhr.js:178 OPTIONS https://127.0.0.1:5000/run_query net::ERR_CONNECTION_REFUSED in the Google Chrome Browser Console.
I'm runnning nginx on Linux AMI. The certificates are for RehlOS/CentOS generated through letsencrypt and certbot. My Nginx error.log doesn't return anything, running the backend python file doesn't log anything anymore, like it did before going from HTTP. It just displays this:
* Running on https://ec2-34-209-86-220.us-west-2.compute.amazonaws.com:5000/ (Press CTRL+C to quit)
* Restarting with stat
I also tried changing the post URL to https://ec2-34-209-86-220.us-west-2.compute.amazonaws.com:5000/run-query instead of https://127.0.0.1:5000/run_query but got the exact same error.
I hope it's something simple, any help would be great. Thanks!
I would like to be able to run python code in my javascript. How do I do this?
This is my attempt, but it's not working and I don't know why
The two following files, I have in the same directory if that matters?
Please help, thanks
scripts.js:
function postPyScript(input){
var jqXHR = $.ajax({
type: "POST",
url: "/app.py",
data: { mydata: input }
});
return jqXHR.responseText;
}
$('#generateBtn').click(function(){
datatosend = 'this is my matrix';
result = postPyScript(datatosend);
alert('Got back ' + result);
});
app.py:
from flask import *
app = Flask(__name__)
#app.route("/app.py", methods=['GET', 'POST'])
def someFunction():
message = None
if(request.method=='POST'):
datafromjs = request.form['mydata']
result = "something to return"
resp = make_response('{"response": '+result+'}')
resp.headers['Content-Type'] = "application/json"
return respreturn
return render_template('index.html',message='')
if __name__ == '__main__':
app.run(debug=True)
Because you only have one route in flask, it seems that you are likely already using a server to serve your html and javascript - maybe you are using the apache instance that your computer came with? In addition to that, you need to be running your flask server. Your flask server will be running on a different port from your apache (or whatever) server.
So, two things:
run your flask server. you might do something like:
$ cd directory-of-this-project
$ export FLASK_APP=app.py
$ flask run
change the ajax url to include the port of the flask server (e.g. http://127.0.0.1:5000/app.py)