Ошибка 405 flask

Example of a flask app using wsgi with JQuery, Ajax and json:

activecalls.py

from flask import Flask, jsonify

application = Flask(__name__, static_url_path='')

@application.route('/')
def activecalls():
    return application.send_static_file('activecalls/active_calls_map.html')

@application.route('/_getData', methods=['GET', 'POST'])
def getData():
    #hit the data, package it, put it into json.
    #ajax would have to hit this every so often to get latest data.
    arr = {}
    arr["blah"] = []
    arr["blah"].append("stuff");

    return jsonify(response=arr)


if __name__ == '__main__':
    application.run()

Javascript json, /static/activecalls/active_calls_map.html:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

<script>
$.ajax({
    //url : "http://dev.consumerunited.com/wsgi/activecalls.py/_getData",
    url : "activecalls.py/_getData",
    type: "POST",
    data : formData,
    datatype : "jsonp",
    success: function(data, textStatus, jqXHR)
    {
        //data - response from server
         alert("'" + data.response.blah + "'");
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
         alert("error: " + errorThrown);

    }
});
</script>

When you run this. The alert box prints: «stuff».

closeup photo of yellow Labrador retriever puppy

Sometimes, we want to fix POST Error 405 Method Not Allowed with Flask Python.

in this article, we’ll look at how to fix POST Error 405 Method Not Allowed with Flask Python.

How to fix POST Error 405 Method Not Allowed with Flask Python?

To fix POST Error 405 Method Not Allowed with Flask Python, we should make sure the action attribute of the form is set to the URL of the view that accepts POST requests.

For instance write

@app.route('/template', methods=['GET', 'POST'])
def template():
    if request.method == 'POST':
        return "Hello"
    return render_template('index.html')

to create the template view.

Then in index.html, we write

<form action="{{ url_for('template') }}" method="post">
  ...
</form>

to add a form that has the action attribute set to the URL for the template view that we get with url_for('template').

Then when we submit the form, the template view will be run since we have 'POST' in the methods list.

Conclusion

To fix POST Error 405 Method Not Allowed with Flask Python, we should make sure the action attribute of the form is set to the URL of the view that accepts POST requests.

Web developer specializing in React, Vue, and front end development.

View Archive

Answer by Keyla Villa

I would try putting the url methods in the app route just like you have in the entry_page function:,What is happening here is that database route does not accept any url methods.,I think you forgot to add methods for your database function.,

What is the danger in the over-use of reverse thrust during ground operations when operating a turboprop powerplant?

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

Answer by Bailee Correa

Hello, I’m a student and I’ve just started with the POSTMAN application. I’m trying to set up a python server using Flask so that I can create an API to share the results of home automation experiments (e.g. arduino).,I’m not even going to begin to tell you anything about Python or Flask but that looks like you are sending both the GET and POST to the same route.,Unfortunately I have a problem with my POST request, I don’t want to use JSON formats but “x-www-form-urlencoder”. When I send the request I get an error 405 “METHOD NOT ALLOWED”.,— Python — Flask script —

Add something like this I think but probably need more to handle the params and/or body:

@app.route("/", methods=['GET', 'POST'])

Answer by Ayden Middleton

This is my api code and run result:,This is web run result:

I am trying to upload file. the abnormal is 'The method is not allowed for the requested URL' after run .  However my code is request methods is 'POST'

This is my a part of html:

<form action="" enctype='multipart/form-data' method="POST">
<span class="btn btn-info" id="import">
<input type="file" name="file">
</span>input type="submit" value="upload" id="submit">

This is my api code and run result:

@api.route('/upload', methods=['POST','GET'])
def upload():
if request.method == 'POST':
    print '-'*100
    print request.files
    f = request.files['file']
    upload_path = os.path.join(APP_STATIC_TXT, secure_filename(f.filename))
    file.save(upload_path)
    return redirect(url_for('/upload'))

Answer by Beckham Owens

Hello guys, im starting in Flask, and i am trying to run a simple «hello» app. But when i try to run it via run flask —host=0.0.0.0 i get: «The method is not allowed for the requested URL» shown.,Soo… here is the code:,I’m on mobile so I apologize for the formatting. If this doesn’t solve the issue, let me know. Screenshots of the issue are also helpful ?,any help would be appreciated. I’m following this tutorial:

for flask

from flask import request
from flask import jsonify
from flask import Flask
app = Flask(__name__)
@app.route('/hello',methods=['POST'])
def hello():
    message = request.get_json(force=True)
    name = message['name']
    response = {
        'greeting': 'Hello, ' + name + '!'
    }
    return jsonify(response)                                                                                                                                                           
<!DOCTYPE html>
<html>
<head>
    <title>deeplizard greeting app</title>
    <style>
        * {
            font-size:30px;
        }
    </style>
</head>
<body>
    <input id="name-input" type="text"/>
    <button id="name-button">Submit Name</button>
    <p id="greeting"></p>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
        $("#name-button").click(function(event){
            let message = {
                name: $("#name-input").val()
            }
            $.post("http://35.196.202.178:5000/hello", JSON.stringify(message), function(response){
                $("#greeting").text(response.greeting);
                console.log(response);
            });
        });
    </script>
</body>
</html>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

Answer by Calum Campbell

And here is my flask code..,Edit.. My complete flask code:,I am getting this error when I try to submit a request.,The / route doesn’t accept POST, by default only GET, HEAD and OPTIONS are allowed.

I am getting this error when I try to submit a request.

Method Not Allowed

The method is not allowed for the requested URL.

And here is my flask code..

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

@app.route("/", methods=['POST','GET'])
def get_form():
  query = request.form["search"]
  print query

And my index.html

<body>

<div id="wrap">
  <form action="/" autocomplete="on" method="POST">
    <input id="search" name="search" type="text" placeholder="How are you feeling?">
     <input id="search_submit" value="Send" type="submit">
  </form>
</div>

  <script src="js/index.js"></script>

</body>

Edit.. My complete flask code:

from flask import  Flask,request,session,redirect,render_template,url_for
import flask
print flask.__version__
app = Flask(__name__)

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

@app.route("/data", methods=['POST'])
def entry_post():
    query = request.form["search"]
    print query
    return render_template("index.html")


if __name__ == "__main__":
    app.run()

Answer by Jedidiah Rhodes

Are you sure it’s a problem with the Flask server? It seems like it might be an issue with how you’ve set up the express server, in which case you should look here for issues.,I have tweaked some code in app.py because it was throwing some error.,Yeah,I have double checked and I have followed as per your instruction.
Here my heroku https://mighty-dusk-78515.herokuapp.com/
you can check it.,By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

app = Flask(__name__, template_folder='./')
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/prediction', methods=['GET','POST'])
def prediction():
    if request.form != None and 'message' in request.form:
        msg = request.form['message']
        response =  pred(str(msg))
        return jsonify(response) 
    else:
        return render_template('index.html')
      
if __name__ == '__main__':
    app.debug = True
    app.run()


I keep getting this error when trying to insert some simple text into a db.

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

I’m moving from PHP to python so bear with me here.

The code is:

from flask import Flask, request, session, g, redirect, url_for, 
    abort, render_template, flash

from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/pythontest'
    db = SQLAlchemy(app)
    app = Flask(__name__)

@app.route('/justadded/')
def justadded():
    cur = g.db.execute('select TerminalError, TerminalSolution from Submissions order by id desc')
    entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
    return render_template('view_all.html', entries=entries)

@app.route('/new', methods= "POST")
def newsolution():
    if not request.method == 'POST':
        abort(401)
    g.db.execute('INSERT INTO Submissions (TerminalError, TerminalSolution, VALUES (?, ?)'
                [request.form['TerminalError'], request.form['TerminalSolution']])
    g.db.commit()
    flash('Succesful')
    return redirect(url_for('justadded'))




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

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

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

And the html code for the form is:

    <form action="/new" method="POST">
        <input name="TerminalError" id="searchbar" type="text"         placeholder="Paste Terminal error here...">
        <input name="TerminalSolution" id="searchbar" type="text" placeholder="Paste Terminal solution here...">
        <button type="submit" id="search" class="btn btn-primary">Contribute</button>
        </form>

Issue

When I try to submit a request from my web form to my flask app I get a HTTP 405 method not allowed.


app.py (Python App code):

# app.py
from flask import Flask, render_template, request, redirect, json, url_for
from flaskext.mysql import MySQL
app = Flask(__name__)

# Database connection info. Note that this is not a secure connection.
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'RamsterDB'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql = MySQL()
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()

mysql = MySQL()
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()

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

@app.route('/showRegister', methods=['POST','GET'])
def showRegister():
    return render_template('register.html')

@app.route('/register', methods=['POST, GET'])
def register():
     # read the posted values from the UI
    #try:
        _username = request.form['inputUsername']
        _password = request.form['inputPassword']

     # validate the received values
        if _username and _password:
            return json.dumps({'html': '<span>All fields good !!</span>'})
        else:
            return json.dumps({'html': '<span>Enter the required fields</span>'})

    #return render_template('register.html')

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

register.html (Registration page code):

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Ramster</title>
    <link rel="stylesheet" href="/static/index.css">
    <script src="/static/js/jquery-1.11.2.js"></script>
    <script src="../static/js/register.js"></script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, height=100%">
</head>

<body>
    <div class="topnav">
        <a href="login">Login</a>
        <a href="#">Register</a>
    </div>

    <div class="content">
        <h2>Ramster</h2>
        <p>Register your team</p>
        <form class="example" method="post" action="" style="margin:left;max-width:600px">
        <input type="text" name="inputUsername" id="inputUsername" placeholder="Username" required autofocus><br><br><br>
        <input type="text" name="inputPassword" id="inputPassword" placeholder="Password" required><br><br><br>
        <button id="btnRegister" class="example" type="submit">Register</button>
        </form>
        <!--<form class="example" method="post" action="" style="margin:left;max-width:600px">
            <input type="text" placeholder="Username" name="inputUsername">
            <input type="text" placeholder="Password" name="inputPassword">
                    <button type="submit">Register</button>
                </form>
                <p></p>-->
    </div>
    <div class="footer">
        <p>Terms and Conditions</p>
    </div>

</body>

</html>

register.js:

$(function() {
    $('#btnRegister').click(function() {

        $.ajax({
            url: '/register',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});

error in browser:

jquery-1.11.2.js:9659 POST http://localhost:5000/register 405 (METHOD NOT ALLOWED)

I have tried changing the form parameters as well as the Python code, but nothing seems to be working. I have not attempted to connect to MySQL yet until I fix the 405 issue. I have tried to find an answer but cannot find one anywhere.

Solution

You have list with single element instead of list with 2 elements.
Replace

@app.route('/register', methods=['POST, GET'])

with

@app.route('/register', methods=['POST', 'GET'])

Answered By – Daweo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Понравилась статья? Поделить с друзьями:
  • Ошибка 405 api
  • Ошибка 404b что это
  • Ошибка 4049 мерседес атего
  • Ошибка 4048 как исправить
  • Ошибка 4048 атол 30ф