本節(jié)嘗試從client發(fā)送json到服務器,然后服務器根據內容響應
創(chuàng)新互聯建站-專業(yè)網站定制、快速模板網站建設、高性價比永年網站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式永年網站制作公司更省心,省錢,快速模板網站建設找我們,業(yè)務覆蓋永年地區(qū)。費用合理售后完善,十年實體公司更值得信賴。
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() #讀取客戶端請求內容
發(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" #結果正常
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']