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

PUT /api/v1/users

The PUT API basically helps us update a user's record specified by user_id.

Go ahead and create a route with the PUT method to update the user records defined in the app.py file, as follows:

    @app.route('/api/v1/users/<int:user_id>', methods=['PUT']) 
    def update_user(user_id): 
     user = {} 
     if not request.json: 
         abort(400) 
     user['id']=user_id 
     key_list = request.json.keys() 
     for i in key_list: 
        user[i] = request.json[i] 
     print (user) 
     return jsonify({'status': upd_user(user)}), 200 

Let's specify the definition of the upd_user(user) function, which basically updates the information in the database with the check that the user id exists:

    def upd_user(user): 
      conn = sqlite3.connect('mydb.db') 
      print ("Opened database successfully"); 
      cursor=conn.cursor() 
      cursor.execute("SELECT * from users where id=? ",(user['id'],)) 
      data = cursor.fetchall() 
      print (data) 
      if len(data) == 0: 
        abort(404) 
      else: 
        key_list=user.keys() 
        for i in key_list: 
            if i != "id": 
                print (user, i) 
                # cursor.execute("UPDATE users set {0}=? where id=? ",
(i, user[i], user['id'])) cursor.execute("""UPDATE users SET {0} = ? WHERE id =
?""".format(i), (user[i], user['id'])) conn.commit() return "Success"

Now that we have added the API handle for the PUT method for the user resource, let's test it out as follows:

We have defined our resources that are a part of version v1. Now, let's define our next version release, v2, which will add a tweet resource to our microservices. Users who are defined in users resources are allowed to perform actions on their tweets. Now, /api/info will be shown, as follows:

Our tweets resource will use the HTTP methods as follows:

We can define a tweet as having the following fields:

  • id: This is the unique identifier for each tweet (Numeric type)
  • username: This should exist as a user in the users resources (String type)
  • body: This is the content of the tweet (String type)
  • Tweet_time: (Specify type)

You can define the preceding tweets resource schema in SQLite 3 as follows:

CREATE TABLE tweets( 
id integer primary key autoincrement, 
username varchar2(30), 
body varchar2(30), 
tweet_time date); 

Great! The tweets resource schema is ready; let's create our GET methods for the tweets resource.

主站蜘蛛池模板: 河东区| 彭阳县| 大同县| 峨眉山市| 抚宁县| 肃南| 南郑县| 花莲县| 德令哈市| 永靖县| 延川县| 浦城县| 奎屯市| 丹巴县| 池州市| 汶川县| 望谟县| 清河县| 铅山县| 株洲市| 米泉市| 清徐县| 彰化市| 宝清县| 雅安市| 仁布县| 铁岭市| 岳西县| 徐汇区| 安远县| 临颍县| 闽侯县| 定陶县| 奉新县| 扎赉特旗| 大余县| 新闻| 扎鲁特旗| 木里| 永德县| 慈利县|