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

  • 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:

主站蜘蛛池模板: 福安市| 家居| 海南省| 吴川市| 宁国市| 精河县| 资兴市| 探索| 德化县| 健康| 颍上县| 麻江县| 尼勒克县| 陆河县| 文山县| 克东县| 宜城市| 遂宁市| 阆中市| 阿拉善盟| 土默特左旗| 醴陵市| 璧山县| 喜德县| 陕西省| 临猗县| 鸡东县| 吴忠市| 观塘区| 仲巴县| 旺苍县| 南投市| 惠州市| 郯城县| 永城市| 西丰县| 玛纳斯县| 南川市| 壶关县| 遵义市| 凌源市|