简体   繁体   English

POST 方法不适用于 Flask(“POST/HTTP/1.1”405 -)

[英]POST method not working with Flask ("POST / HTTP/1.1" 405 -)

I am trying to upload a pdf using flask. But whenever I click the submit button I get the following error:我正在尝试使用 flask 上传 pdf。但是每当我单击提交按钮时,我都会收到以下错误:

Method Not Allowed
The method is not allowed for the requested URL.

I am not sure what to do, and why this is happening.我不确定该怎么做,以及为什么会这样。 Thanks for the help in advance.我在这里先向您的帮助表示感谢。

Inside my index.html :在我的index.html里面:

<form method="POST" action="/" enctype="multipart/form-data">
    <input type="file" class="form-control" id="customFile" name = "file"/>
    <input type="submit">
</form>

Inside my __init__.py I have: Relative path: apps/__init__.py在我的__init__.py里面我有: 相对路径: apps/__init__.py

def create_app(config):
    UPLOAD_FOLDER = ''
    app = Flask(__name__)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    app.config.from_object(config)
    return app

Inside my routes.py I have: Relative path: apps/home/routes.py在我的routes.py中,我有: 相对路径: apps/home/routes.py

from apps.home import blueprint
from flask import render_template, request, send_file, redirect, url_for, flash
from jinja2 import TemplateNotFound
import os
from werkzeug.utils import secure_filename

ALLOWED_EXTENSIONS = {'pdf'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@blueprint.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('upload_file', name=filename))
    
    return render_template('home/index.html', segment='index')

HTTP error 405 means that the target URL on the server does not support the method (in this case, POST). HTTP 错误 405 表示服务器上的目标 URL 不支持该方法(在本例中为 POST)。 One possibility is POST only works when there is some service running that can process the incoming file.一种可能性是 POST 仅在运行某些可以处理传入文件的服务时才有效。

Consider changing your route decorator to use PUT: @blueprint.route('/index', methods=['GET', 'PUT'])考虑更改路由装饰器以使用 PUT: @blueprint.route('/index', methods=['GET', 'PUT'])

More on POST vs PUT 有关 POST 与 PUT 的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM