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')
Related
I am having trouble using emit in my route, I have tried many things but nothing seems to be working. My code is as follows:
app.py:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
#app.route('/abc')
def index():
emit('message', {'data': 'Demo'})
return render_template('index.html')
#socketio.on('disconnect')
def on_disconnect():
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app)
index.html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
<script>
var socket = io();
socket.on('connect', function () {
console.log("Connected")
});
socket.on('message', function (msg) {
console.log(msg.data);
});
</script>
(?) How can I use emit in route?
Your design is flawed, since you are emitting too early.
Here is the sequence of events:
Client connects to the /abc route from the browser
The index() route runs and calls emit(). At this point the client is not connected, so it does not receive the message.
The index() function returns the index.html template to the browser.
The browser renders the HTML page, and as part of that executes the JavaScript code in it, which makes a Socket.IO connection to the server.
What you can do to verify that the emit is working is open this route in multiple browser tabs. When you open the first one nothing will happen, but when you open the second tab, the client on the first tab is going to receive the emit, since it is already connected. When you open the third tab, tabs 1 and 2 will receive the emit.
I have created fulfillment code for Dialogflow with Python Flask and deployed it as Azure Web App. Code is working fine with the url provided by Azure.
But if I use the same url in Dialog Flow's Fulfillment webhook, I get an error saying "Webhook call failed. Error: UNKNOWN."
Here's my simple Python Flask Code which is deployed in Azure as Web App.
from flask import Flask, request, make_response, jsonify
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
#app.route("/webhook")
def webhook():
return jsonify("Webhook Successfull")
if __name__ == "__main__":
app.run()
Webhook url in DialogFlow:
For your python code, there are two issues I think you met. First is that the route in the Flask just set to support the GET in default. So you need to set for the POST request manually. See the details here for the parameters:
By default a rule just listens for GET (and implicitly HEAD). Starting
with Flask 0.6, OPTIONS is implicitly added and handled by the
standard request handling.
Another is that you return the message via the function jsonify. It turns the JSON output into a Response object with the application/json mime-type, but you just give ita string. So the POST response will meet the conflict. This may be the problem you met.
You can change the code like this:
from flask import Flask, request, make_response, jsonify
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def hello():
return "Hello World!"
#app.route("/webhook", methods=["GET", "POST"])
def webhook():
return jsonify(response="Webhook Successfull")
if __name__ == "__main__":
app.run()
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.
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)
I'm trying to execute this little request with jquery on a page load:
$.ajax({
type: "GET",
url: "/static/query.py",
cache: false,
success: function (data) {
$(body).text(data);
}
});
On a server running nginx, python, in a virtualenv, working with Flask framework and the return is the query.py sourcecode, not the data retrieved from the DB.
query.py is marked as executable and the script has the shebang:
#!/home/gabriel/project/bin
which points to the bin in my virtualenv. I think got the basis covered but yet, the problem persists.
Tips?
More info:
Flask script:
from flask import Flask, render_template
application = Flask(__name__)
#application.route('/')
def init():
return render_template('index.html')
if __name__ == "__main__":
application.run(host='0.0.0.0', debug=True)
uwsgi.py to load the Flask script:
from myapp import application
if __name__ == "__main__":
application.run()
The query.py:
from db import * //Database model, SQLAlchemy.
def something():
data = Kingdom.query.all()
return data
something()
You should be running the actual code that's in query.py inside flask. Do something like:
#application.route("/query"):
def get_data():
.. whatever code you need; currently in query.py, you would probably use sqlalchemy/ flask-sqlalchemy
data = your data (dictionary? list?)
return jsonify(data=data) # flask will turn your data into a proper JSON string to send back as a response to the ajax call.
Don't forget to import jsonify from flask, consult docs here.
Also rename "/static/query.py" to "/query" in example above, or anything else you see fit. You can also send flask parameters via the AJAX call to process in your query; e.g., filtering parameters. Focus the question for further guidance.