本节尝试从client发送json到服务器,然后服务器根据内容响应
创新互联建站-专业网站定制、快速模板网站建设、高性价比永年网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式永年网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖永年地区。费用合理售后完善,十年实体公司更值得信赖。
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']