【问题标题】:How to execute Python program within @app.route without 405 error?如何在@app.route 中执行 Python 程序而不会出现 405 错误?
【发布时间】:2019-07-02 14:21:53
【问题描述】:

一旦我到达句柄数据页面,我就会尝试执行这个 python 后端程序。为什么方法返回 405 Method Not Allowed 错误?

过去,我尝试将 python 的位置更改为 @ 装饰器和 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 错误。 如果您需要更多信息,请通知

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    @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

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      • 2021-06-15
      相关资源
      最近更新 更多