學習flask-restful_Url_Routing的參數處理

搞懂Url Routing的參數處理

來做個使用者CRUD

先來做一個基本的CRUD的操作

User基本結構

先定義User這個Resource的基本結構, 這只是定義結構

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from flask_restful import Resource


class User(Resource):
def get(self, name):
pass

def post(self, name):
pass

def put(self, name):
pass

def delete(self, name):
pass

註冊Resouce

不過如何將name由url帶入方法內

1
2
3
4
5
6
7
8
9
10
11
12
from flask import Flask
from flask_restful import Api
from resources.user import User

app = Flask(__name__)
api = Api(app)

api.add_resource(User, '/user/<string:name>')

if __name__ == "__main__":
app.run()

如此可以把User綁定到url/user/,而最後一個內容會轉型成字串傳遞給熱法當作是name的變數, 可以先以postman來測試,之前的uri應該是url

設定POSTMAN

可以在postman上執行get,post,put,delete的方法,只不過服務器的回應是null,應為我們的方法是空的

#### 實作GET方法

先不以資料庫的操作,修改user.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from flask_restful import Resource

users = [{
'name':'kitty'
}]


class User(Resource):
def get(self, name):
find = [item for item in users if item['name'] == name]
if len(find) == 0:
return {
'message': 'username not exist!'
}, 403
user = find[0]
if not user:
return {
'message': 'username not exist!'
}, 403
return {
'message': '',
'user': user
}

def post(self, name):
pass

def put(self, name):
pass

def delete(self, name):
pass

實作delete

可以使用get方法來測試

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from flask_restful import Resource

users = [
{'name': 'kitty'},
{'name': 'tom'}
]

class User(Resource):
def get(self, name):
find = [item for item in users if item['name'] == name]
if len(find) == 0:
return {
'message': 'username not exist!'
}, 403
user = find[0]
if not user:
return {
'message': 'username not exist!'
}, 403
return {
'message': '',
'user': user
}

def post(self, name):
pass

def put(self, name):
pass

def delete(self, name):
global users
users = [item for item in users if item['name'] != name]
return{
'message': 'Delete done!'
}