在没有数据库的flask中创建api会导致405错误

问题描述 投票:0回答:1
app = Flask(__name__)
employees = [
    {"id": 1, "Name": "Ram", "Age": 20,"Gender":"Male"},
    {"id": 2, "Name": "Sita", "Age": 25,"Gender":"Female" }
]
   
@app.route('/', methods=['GET'])
def get_employees():
    return (employees)

@app.route('/employees/id', methods = ['GET'])
def get_employee(employee_id):
    for employee in employees:
        if employee['id']== employees_id:
            return employee
    return {'error':'Employee not found'}

我是 Flask 的新手。我试图通过 ID 获取员工,但它抛出 405 错误。但是我能够获取所有员工,但不能根据 id 获取。

python api flask
1个回答
0
投票
        from flask import Flask, jsonify, request

app = Flask(__name__)
employees = [
    {"id": 1, "Name": "Ram", "Age": 20,"Gender":"Male"},
    {"id": 2, "Name": "Sita", "Age": 25,"Gender":"Female" },
    {"id": 3, "Name": "Mahesh", "Age":45,"Gender":"Male"},
    {"id": 4, "Name": "Rita", "Age": 52,"Gender":"Female"},
]
   
@app.route('/', methods=['GET'])
def get_employees():
    return (employees)

@app.route('/employees/<int:employee_id>', methods = ['GET'])
def get_employee(employee_id):
    for employee in employees:
        if employee['id']== employee_id:
            return employee
    return {'error':'Employee not found'}

@app.route('/', methods=['POST'])
def add_employee():
    new_employee={'id':len(employees)+1, 'Name':request.json['Name'], 'Age':request.json['Age'], 'Gender':request.json['Gender']}
    employees.append(new_employee)
    return(new_employee)

@app.route('/employees/<int:employee_id>', methods=['PUT'])
def update_employee(employee_id):
    for employee in employees:
        if employee['id']== employee_id:
            employee['Name']= request.json['Name']
            employee['Age']=request.json['Age']
            employee['Gender']=request.json['Gender']
            return employee
    return {'error':'Employee not found'}

@app.route('/employees/<int:employee_id>', methods=['DELETE'])
def delete_employee(employee_id):
    for employee in employees:
        if employee['id']== employee_id:
            employees.remove(employee)
            return {'data':'Employe has been removed'}
    return {'error':'Employee not found'}

if __name__== "__main__":
    app.run(debug = True).   
© www.soinside.com 2019 - 2024. All rights reserved.