本节尝试从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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。