基于原理图的python部分json-api实现

hyp的Python项目详细描述


hyp
==
python中的json-api响应。

about
----
hyp是实现[json-api]响应规范(http://jsonapi.org)的“必须”部分的库。这意味着您可以使用hyp将模型序列化为包含链接和链接复合文档的响应。它和你选择的微型网络框架结合起来真的很好,最好是[烧瓶](http://flask.pocoo.org)。

它内置了对[示意图](https://schematics.readthedocs.org/)和[棉花糖](http://marshmallow.readthedocs.org)的支持,因为您可以使用它们中的任何一个将模型(或原语)序列化为json,hyp从中创建响应。要添加对更多数据序列化库的支持,例如[colander](http://docs.pylonsproject.org/projects/colander/en/latest/)应该很简单。


tutorial
--
>首先让我们为您的模型定义一些序列化器:

``python
from marshmallow import serializer,字段



class commentserializer(序列化程序):
id=fields.integer()
content=fields.string()



class personserializer(序列化程序):
id=fields.integer()
name=fields.string()



class postsserializer(序列化程序):
id=fields.integer()
title=fields.string()
```

然后我们可以使用hyp.responders类创建自己的响应程序:

``python
from hyp.responder import responder



class commentresponder(响应程序):
type='comment'
serializer=commentserializer


class personresponder(响应程序):
type=“person”
serializer=personserializer



类PostResponder(响应程序):
type='post'
serializer=PostSerializer
links={
“comments”:{
“responder”:commentResponder(),
“ref”:“http://example.com/comments/{posts.comments},
},
“author”:{
“responder”:personresponder(),
“ref”:“http://example.com/people/{posts.author},
},
}
````

最后,我们可以使用响应程序创建响应。这些响应完全适用于任何烧瓶应用程序:

``python
post={
'id':1,
'title':'my post',
'comments':[
{'id':1,'content':'a comment'},
{'id':2,'content':'another comment'},
]

json=postreponder.respond(post,linked={'comments':post['comments']})

````

`json'变量现在将包含一些新压缩的json,可以发送回客户端:

``json
{
“posts”:[
{
“id”:1,
“title”:“My title”,
“links”:{
“comments”:[1,2]
}
}
],
“linked”:{
“comments”:[
{
“id”:1,
“content”:“my comment”
},
{
“id”:2,
“content”:“another comment”
}
]
},
“links”:{
“posts.comments”:{
“type”:“comments”,
“ref”:“http://example.com/comments/{posts.comments}”
}
}
}
````

例如,如果要使用flask的[jsonify](http://flask.pocoo.org/docs/api/flask.json.jsonify),则可以使用“build”方法,而不是这样:

``python
post={
'id:1,
'title':'my post',
'comment s':[
{'id:1,'content':'a comment'},
{'id:2,“content”:“另一个注释”},
]
}


response=postreponder.build(post,linked={'comments':post['comments']})
json=烧瓶J校准(响应)
```

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java我试图使用@OneToOne作为双向映射来映射实体,但却遇到了奇怪的异常   性能Java异步如何工作?异步方法似乎不是异步运行的   java这个代码可以更短吗   线程“main”Java中的csv Java ArrayList异常。lang.NegativeArraySizeException:28   java确定LayoutManager预布局中的显示视图   java如何在FirestorePagingAdapter中通过方法onLoadingStateChanged隐藏/显示进度条?   在Java中,如何打印一个类似于中间有“过道”的座位表的2d数组?   http Java实现字节范围服务,而不使用仅使用Java api的servlet   java无法使用命名根元素生成json   java如何在注销侦听器中获取http会话id?   数组内部输入(java)?   java如何为特殊情况提供更简单的构造函数   java在swing应用程序中显示JavaFX后台   java如何启用系统。出来在eclipse中运行Junit测试时使用println()?   如何在Java中实现Oracle用户定义的聚合函数