本節(jié)嘗試從client發(fā)送json到服務(wù)器,然后服務(wù)器根據(jù)內(nèi)容響應(yīng)
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() #讀取客戶端請求內(nèi)容
發(fā)送測試請求,我用httpie,喜歡用postman的在Body,raw中添加即可。
http get localhost:8080/test name="hello"
注意發(fā)送時用雙引號,不要用單引號。單引號會報錯。
一切正常能看到如下輸出:
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" #結(jié)果正常
http get localhost:8080/test falcon_test:api method="get-names" #結(jié)果為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: #檢測內(nèi)容是否包含請求信息
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']
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。