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

推薦閱讀
- 基于免疫進(jìn)化的算法及應(yīng)用研究
- Flash CS6中文版應(yīng)用教程(第三版)
- SQL Server 2016數(shù)據(jù)庫應(yīng)用與開發(fā)習(xí)題解答與上機(jī)指導(dǎo)
- Android 應(yīng)用案例開發(fā)大全(第3版)
- 網(wǎng)絡(luò)爬蟲原理與實(shí)踐:基于C#語言
- D3.js 4.x Data Visualization(Third Edition)
- Learning DHTMLX Suite UI
- 從Java到Web程序設(shè)計(jì)教程
- Mastering Unity 2D Game Development(Second Edition)
- MongoDB,Express,Angular,and Node.js Fundamentals
- 寫給程序員的Python教程
- Java自然語言處理(原書第2版)
- 從零開始學(xué)Unity游戲開發(fā):場景+角色+腳本+交互+體驗(yàn)+效果+發(fā)布
- MySQL核心技術(shù)與最佳實(shí)踐
- Java Web入門很輕松(微課超值版)