如何在@app.route内执行Python程序而不出现405错误?

2024-09-28 22:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在到达handledata页面后执行这个python后端程序。为什么方法返回405 Method Not Allowed错误

在过去,我曾尝试将python的位置更改为@decorator和methods=[“POST”]条件之外

Python

import random
import requests
import time
from datetime import date
import sys
import re
import json
from bs4 import BeautifulSoup
from flask import Flask, render_template, jsonify

app = Flask(__name__)

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

@app.route("/handle_data") 
def handle_data():
        userName = requests.form['username']
        listName = requests.form['listname']

        full python code is here

        randomNumber = randint(0,len(nameList)-1)
        films = nameList[randomNumber]
        return render_template('home.html', films=films)
if __name__ == '__main__':
    app.run(debug=True)

。。。 HTML

<form action="{{ url_for('handle_data') }}" method="POST">
<form>
  <div class="form-row">
    <div class="col">
      <input type="text" size=15 name=username class="form-control" placeholder="Username">
     </div>
     <div class="col">
      <input type="text" size=15 name=listname class="form-control" placeholder="List Name">
    </div>
  </div>
  <p><input type = "submit" class="buttonclass" value = "Random!" /></p>
</form>

我希望程序通过程序运行表单中的请求,并以变量“films”的形式返回随机列表项,但我收到一个405错误。 如果您需要更多信息,请通知


Tags: namefromimportdivformapphomedata
1条回答
网友
1楼 · 发布于 2024-09-28 22:19:57

@app.route("/handle_data")仅为GET请求注册路由。如果您也想要POST,您需要明确地请求它:

@app.route("/handle_data", methods=['GET', 'POST'])
def handle_data():
    # your code here

或:

@app.route("/handle_data", methods=['GET'])
def handle_get_data():
    pass

@app.route("/handle_data", methods=['POST'])
def handle_post_data():
    pass

更多信息:http://flask.pocoo.org/docs/1.0/api/#url-route-registrations

相关问题 更多 >