您好,登錄后才能下訂單哦!
本節嘗試從client發送json到服務器,然后服務器根據內容響應
import json,falcon
class ObjRequestClass:
def on_get(self,req,resp):
resp.status = falcon.HTTP_200
data = json.loads(req.stream.read())
content = {
'name':'falcon',
'age':30
}
resp.body=json.dumps(data)
api = falcon.API()
api.add_route('/test',ObjRequestClass())
req.stream.read() #讀取客戶端請求內容
發送測試請求,我用httpie,喜歡用postman的在Body,raw中添加即可。
http get localhost:8080/test name="hello"
注意發送時用雙引號,不要用單引號。單引號會報錯。
一切正常能看到如下輸出:
HTTP/1.1 200 OK
Content-Length: 17
Content-Type: application/json
Date: Fri, 08 Nov 2019 03:39:59 GMT
Server: waitress
{
"name": "hello"
}
{
"method":"get-name"
}
import json,falcon
class ObjRequestClass:
def on_get(self,req,resp):
resp.status = falcon.HTTP_200
data = json.loads(req.stream.read())
content = {
'name':'falcon',
'age':30
}
value={}
if data["method"]=="get-name":
value['value']=content['name']
else:
value['value']=None
resp.body=json.dumps(value)
api = falcon.API()
api.add_route('/test',ObjRequestClass())
httpie測試
http get localhost:8080/test falcon_test:api method="get-name" #結果正常
http get localhost:8080/test falcon_test:api method="get-names" #結果為null
import json,falcon
class ObjRequestClass:
def on_get(self,req,resp):
resp.status = falcon.HTTP_200
data = json.loads(req.stream.read())
content = {
'name': 'falcon',
'age': 30
}
value = {}
if "method" not in data: #檢測內容是否包含請求信息
resp.status == falcon.HTTP_501
else:
if data["method"] == "get-name":
value['value'] = content['name']
elif data["method"] == "get-age":
value['age'] = content['age']
else:
resp.status = falcon.HTTP_404
value['value'] = None
resp.body = json.dumps(value)
api = falcon.API()
api.add_route('/test',ObjRequestClass())
req.stream 可用
['__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__
enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__nex
t__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', 'close', 'c
losed', 'detach', 'fileno', 'flush', 'getbuffer', 'getvalue', 'isatty', 'read', 'read1', 'readable', 'readinto', 'readinto1', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'wr
ite', 'writelines']
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。