Home > OS >  How can the following issue be resolved in flask? "Method Not Allowed The method is not allowed
How can the following issue be resolved in flask? "Method Not Allowed The method is not allowed

Time:11-03

Here is the code

import os
import redis
import flask
import json
import urllib.parse
from flask import Flask, Response, request, render_template, abort
from flask_cors import CORS, cross_origin
#from flask.ext.cors import CORS, cross_origin

app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
redis_handle = redis.Redis('localhost')
requiredFields = ("id", "title", "name")  # fields required for user object


@app.route('/')
@cross_origin()
def hello():
    return 'Hello World!'


@app.route('/users/<user_id>', methods=['GET'])
@cross_origin()
def get_user(user_id):
    response = {}
    # user_id = request.args.get("id")
    user = redis_handle.get(user_id)
    if not user:
        response["msg"] = "no user found"
        return Response(json.dumps(response), status=404, mimetype="application/json")
    return user


@app.route('/users', methods=['POST'])
@cross_origin()
def save_user():
    data = request.get_json(force=True)
    response = {}
    if all(field in data for field in requiredFields):
        redis_handle.set(data["id"], json.dumps(data))
        return Response(status=201)
    else:
        missing_key = str([val for val in requiredFields if val not in dict(data).keys()])
        response["msg"] = "required key "   missing_key   " not found"
        return Response(json.dumps(response), status=400)


@app.route('/users/<user_id>', methods=['DELETE'])
@cross_origin()
def delete_user(user_id):
    response = {}
    resp = redis_handle.delete(user_id)
    if resp == 0:
        response["msg"] = "no such entity found"
        status = 404
    else:
        response["msg"] = "Delete op is successful"
        status = 200
    return Response(json.dumps(response), status=status)


@app.route('/clear', methods=['GET'])
@cross_origin()
def clear_data():
    redis_handle.flushall()
    return "ok!"


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

enter image description here

As of my knowledge, I have even included the method = "POST" as well but still don't know what is going wrong.

I tried to create a small crud application using redis, python, flask but couldn't encountering this issue. Can someone tell me where and what am I doing wrong?

CodePudding user response:

Browsers don't run POST methods outside of a <form> entry or AJAX function. Therefore, you're running a GET, which "isn't allowed".

Unclear what you expected, but to see all users, you'll need to edit your route to first add the GET method, then if so, return a response that returns/renders all users rather than checking the request json body, which won't exist for GET requests

If you only wanted to get one user, edit the url to include the user ID

CodePudding user response:

The browser will use the GET method for URLs that you input in URL/search bar but you don't have any function decorated with @app.route('/users', methods=['GET']).

If you want to create a user with POST /users then it would be easier to use some HTTP client like https://www.postman.com, https://insomnia.rest, etc. or even fetch in the browser's console.

  • Related