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

  • Cloud Native Python
  • Manish Sethi
  • 236字
  • 2021-07-02 19:11:58

POST /api/v1/users

In this book, we go with the first approach to the POST method. So, let's define our route for the post method in app.py, and call the function to update the user record to the database file, as follows:

    @app.route('/api/v1/users', methods=['POST']) 
    def create_user(): 
      if not request.json or not 'username' in request.json or not
'email' in request.json or not 'password' in request.json: abort(400) user = { 'username': request.json['username'], 'email': request.json['email'], 'name': request.json.get('name',""), 'password': request.json['password'] } return jsonify({'status': add_user(user)}), 201

As you can see, in the preceding method, we called the exception with error code 400; let's write its handler now:

    @app.errorhandler(400) 
    def invalid_request(error): 
       return make_response(jsonify({'error': 'Bad Request'}), 400) 

We still need to define the add_user(user) function, which will update the new user record. Let's define it in app.py, as follows:

    def add_user(new_user): 
     conn = sqlite3.connect('mydb.db') 
     print ("Opened database successfully"); 
     api_list=[] 
     cursor=conn.cursor() 
     cursor.execute("SELECT * from users where username=? or
emailid=?",(new_user['username'],new_user['email'])) data = cursor.fetchall() if len(data) != 0: abort(409) else: cursor.execute("insert into users (username, emailid, password,
full_name) values(?,?,?,?)",(new_user['username'],new_user['email'],
new_user['password'], new_user['name'])) conn.commit() return "Success" conn.close() return jsonify(a_dict)

Now that we have added handler, as well as the route for the POST method of the user, let's test it by adding a new user using the following API call:

curl -i -H "Content-Type: application/json" -X POST -d '{
"username":"mahesh@rocks", "email": "mahesh99@gmail.com",
"password": "mahesh123", "name":"Mahesh" }'
http://localhost:5000/api/v1/users

Then, validate the user's list curl, http://localhost:5000/api/v1/users, as shown in the following screenshot:

主站蜘蛛池模板: 卓资县| 图们市| 西乡县| 昌平区| 高青县| 德令哈市| 礼泉县| 根河市| 湘阴县| 安仁县| 长宁区| 怀柔区| 天长市| 临桂县| 府谷县| 锦屏县| 翁牛特旗| 阳朔县| 九龙城区| 德州市| 城口县| 洛川县| 巴林左旗| 平湖市| 黄山市| 虎林市| 阿合奇县| 河间市| 赞皇县| 阿拉善左旗| 诏安县| 锡林郭勒盟| 台北县| 临夏县| 米易县| 海伦市| 清涧县| 孟州市| 兴和县| 资源县| 兰西县|