I hope someone can help me: My index.html page: https://example.com/index.html, it includes a 'message' input and 'send' button, when the 'send' button is clicked, message will send to https://example.com/python_app/ (the folder of app.py) by POST method, then python app will return stream data back to https://example.com/index.html, and it append word by word to div output of index.html page (like chatgpt). Now, The error show in Console, Network tab of browser is: python_app, POST , 200 OK then python_app , GET , 405 Method Not Allowed Please help me. app.py:
from flask import Flask, request, Response
import time
app = Flask(__name__)
@app.route("/", methods=["POST"])
def handle_message():
message = request.form["message"]
words = message.split()
def event_stream():
for word in words:
time.sleep(1)
yield "data: {}\n\n".format(word)
return Response(event_stream(), mimetype="text/event-stream")
if __name__ == "__main__":
app.run()
And index.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="messageInput" />
<button id="sendButton">Send</button>
<div id="output"></div>
<script>
$("#sendButton").click(function() {
var message = $("#messageInput").val();
$.ajax({
url: "/python_app/",
type: "POST",
data: {message: message},
success: function(res) {
var eventSource = new EventSource("/python_app/");
eventSource.onmessage = function(event) {
$("#output").append(event.data + "<br>");
}
}
});
});
</script>
</body>
</html>
I have already tried this, but error is 404:
from flask import Flask, request, Response
import time
app = Flask(__name__)
words = []
@app.route("/python_app/", methods=["POST", "GET"])
def handle_message():
if request.method == "POST":
message = request.form["message"]
words.extend(message.split())
elif request.method == "GET":
def event_stream():
for word in words:
time.sleep(1)
yield "data: {}\n\n".format(word)
return Response(event_stream(), mimetype="text/event-stream")
if __name__ == "__main__":
app.run()