官术网_书友最值得收藏!

  • Cloud Native Python
  • Manish Sethi
  • 187字
  • 2021-07-02 19:11:59

DELETE /api/v1/users

The delete method helps remove a specific record, which is defined by a username. We will pass username as the JSON object that needs to be deleted from the database.

The following code snippet will create a new route in app.py for the DELETE method for users:

    @app.route('/api/v1/users', methods=['DELETE']) 
    def delete_user(): 
     if not request.json or not 'username' in request.json: 
        abort(400) 
     user=request.json['username'] 
      return jsonify({'status': del_user(user)}), 200 

In the next code snippet, we will call del_user, which deletes the user record specified by username after validating whether it exists or not:

    def del_user(del_user): 
      conn = sqlite3.connect('mydb.db') 
      print ("Opened database successfully"); 
      cursor=conn.cursor() 
      cursor.execute("SELECT * from users where username=? ",
(del_user,)) data = cursor.fetchall() print ("Data" ,data) if len(data) == 0: abort(404) else: cursor.execute("delete from users where username==?",
(del_user,)) conn.commit() return "Success"

Great! We have added the route /handler for the DELETE method for the user resource; let's test it using the following test API call:

    curl -i -H "Content-Type: application/json" -X delete -d '{ 
"username":"manish123" }' http://localhost:5000/api/v1/users

Then, hit the user list API (curl http://localhost:5000/api/v1/users) to see if the changes have been made:

Awesome! User deletion is successful.

主站蜘蛛池模板: 高安市| 浦城县| 阿巴嘎旗| 航空| 英超| 安义县| 黑龙江省| 建阳市| 莱芜市| 泽州县| 延川县| 江陵县| 涿州市| 佛山市| 黑龙江省| 腾冲县| 南和县| 云安县| 宁城县| 沅江市| 蒲江县| 阿鲁科尔沁旗| 哈尔滨市| 天全县| 曲沃县| 鹤山市| 千阳县| 徐汇区| 洛宁县| 龙州县| 无锡市| 余干县| 武宣县| 德江县| 濉溪县| 桐庐县| 长武县| 汉寿县| 永安市| 兴业县| 杭锦后旗|