简体   繁体   中英

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:

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 :

<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

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

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). One possibility is POST only works when there is some service running that can process the incoming file.

Consider changing your route decorator to use PUT: @blueprint.route('/index', methods=['GET', 'PUT'])

More on POST vs PUT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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