"这是代码"
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)
据我所知,我甚至还包括了method =“POST”,但仍然不知道哪里出了问题。
我试着用redis,python,flask创建一个小的crud应用程序,但是没有遇到这个问题。有人能告诉我我哪里做错了吗?
2条答案
按热度按时间vfh0ocws1#
浏览器不会在
<form>
入口或 AJAX 函数之外运行POST方法。因此,您正在运行GET,这是“不允许的”。不清楚您的期望,但要查看所有用户,您需要编辑您的路由,首先添加GET方法,然后如果是这样,返回一个返回/呈现所有用户的响应,而不是检查request json主体,GET请求不存在json主体
如果您只想获取一个用户,请编辑url以包含用户ID
oknrviil2#
浏览器将使用GET方法来获取您在URL/搜索栏中输入的URL,但您没有任何使用
@app.route('/users', methods=['GET'])
修饰的函数。如果你想创建一个使用
POST /users
的用户,那么在浏览器的控制台中使用一些HTTP客户端,如https://www.postman.com、https://insomnia.rest等,甚至fetch,会更容易。