lhy
lhy

Reputation: 11

Flask 405 Method Not Allowed for POST request from PyScript

I'm working on a Flask project where I need to send data from a PyScript (running in the browser) to the Flask backend using a POST request. However, when trying to make a POST request from the PyScript frontend to the Flask backend, I'm encountering error:

405 Method Not Allowed

Flask Backend

from flask import Flask, render_template, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/data/submit', methods=['POST'])
def handle_data():
    data = request.get_json()  # Get JSON data from the request body
    print(f"Received data: {data}")
    response = {"status": "success", "received": data}
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True)

PyScript Frontend:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PyScript 与后端交互</title>
  <link rel="stylesheet" href="https://pyscript.net/releases/2024.11.1/core.css">
  <script type="module" src="https://pyscript.net/releases/2024.11.1/core.js"></script>
  <script src="https://cdn.jsdelivr.net/pyodide/dev/full/pyodide.js"></script>
</head>
<body>

<h2>PyScript 与后端交互示例</h2>

<div id="result"></div>

<py-script>
import js

def send_data_to_backend():
    data = {"message": "Hello from PyScript"}
    js.fetch('/data/submit', {
        'method': 'POST',
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': js.JSON.stringify(data)
    }).then(lambda response: response.json()).then(lambda data: js.console.log(data))

send_data_to_backend()
</py-script>

</body>
</html>

Issue

Request URL: http://127.0.0.1:5000/data/submit
Status Code: 405 METHOD NOT ALLOWED

Upvotes: 1

Views: 38

Answers (1)

Detlef
Detlef

Reputation: 8562

PyScript gives you the option to use Python. Use the built-in fetch variant and the JSON module to send a POST request and it should work.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>
    <link rel="stylesheet" href="https://pyscript.net/releases/2024.11.1/core.css">
    <script type="module" src="https://pyscript.net/releases/2024.11.1/core.js"></script>
</head>
<body>
    <py-script>
from pyscript import fetch
import json

def send_data_to_backend():
    data = {'message': 'Hello from PyScript'}
    fetch('/data/submit', **{
        'method': 'POST',
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': json.dumps(data)
    }) \
        .then(lambda r: r.json()) \
        .then(lambda d: print(d))

send_data_to_backend()
    </py-script>
</body>
</html>

Upvotes: 0

Related Questions