全面但易于使用的pythonic类orm访问json api服务

jsonapi-client的Python项目详细描述


https://travis-ci.org/qvantel/jsonapi-client.svg?branch=masterhttps://coveralls.io/repos/github/qvantel/jsonapi-client/badge.svghttps://img.shields.io/pypi/v/jsonapi-client.svghttps://img.shields.io/pypi/pyversions/jsonapi-client.svghttps://img.shields.io/badge/licence-BSD%203--clause-blue.svg

用于python的json api客户端

简介

包存储库:https://github.com/qvantel/jsonapi-client

这个python(3.6+)库提供了易于使用的pythonic类orm访问 json api(http://jsonapi.org

  • Optional asyncio implementation
  • Optional model schema definition and validation (=> easy reads even without schema)
  • Resource caching within session

安装

>;来自PYPI:

pip install jsonapi-client

或来源:

./setup.py install

使用量

客户端会话

fromjsonapi_clientimportSession,Filter,ResourceTuples=Session('http://localhost:8080/')# To start session in async modes=Session('http://localhost:8080/',enable_async=True)# You can also pass extra arguments that are passed directly to requests or aiohttp methods,# such as authentication objects=Session('http://localhost:8080/',request_kwargs=dict(auth=HttpBasicAuth('user','password'))# You can also use Session as a context manager. Changes are committed in the end# and session is closed.withSession(...)ass:yourcode# Or with enable_async=TrueasyncwithSession(...,enable_async=True):yourcode# If you are not using context manager, you need to close session manuallys.close()# Fetching documentsdocuments=s.get('resource_type')# Or if you want only 1, thendocuments=s.get('resource_type','id_of_document')# AsyncIO the same but remember to await:documents=awaits.get('resource_type')

过滤和包括
# You need first to specify your filter instance.# - filtering with two criteria (and)filter=Filter(attribute='something',attribute2='something_else')# - filtering some-dict.some-attr == 'something'filter=Filter(some_dict__some_attr='something'))# Same thing goes for including.# - including two fieldsinclude=Inclusion('related_field','other_related_field')# Custom syntax for request parameters.# If you have different URL schema for filtering or other GET parameters,# you can implement your own Modifier class (derive it from Modifier and# reimplement appended_query).modifier=Modifier('filter[post]=1&filter[author]=2')# All above classes subclass Modifier and can be added to concatenate# parametersmodifier_sum=filter+include+modifier# Now fetch your documentfiltered=s.get('resource_type',modifier_sum)# AsyncIO with await# To access resources included in document:r1=document.resources[0]# first ResourceObject of document.r2=document.resource# if there is only 1 resource we can use this

资源属性和关系访问
# - attribute accessattr1=r1.some_attrnested_attr=r1.some_dict.some_attr#   Attributes can always also be accessed via __getitem__:nested_attr=r1['some-dict']['some-attr']# If there is namespace collision, you can also access attributes via .fields proxy# (both attributes and relationships)attr2=r1.fields.some_attr# - relationship access.#   * Sync, this gives directly ResourceObjectrel=r1.some_relationattr3=r1.some_relation.some_attr# Relationship attribute can be accessed directly#   * AsyncIO, this gives Relationship object instead because we anyway need to#     call asynchronous fetch function.rel=r1.some_relation#     To access ResourceObject you need to first fetch contentawaitr1.some_relation.fetch()#     and then you can access associated resourceobjectres=r1.some_relation.resourceattr3=res.some_attr# Attribute access through ResourceObject# If you need to access relatinoship object itself (with sync API), you can do it via# .relationships proxy. For example, if you are interested in links or metadata# provided within relationship, or intend to manipulate relationship.rel_obj=r1.relationships.relation_name

资源更新

# Updating / patching existing resourcesr1.some_attr='something else'# Patching element in nested jsonr1.some_dict.some_dict.some_attr='something else'# change relationships, to-many. Accepts also iterable of ResourceObjects/# ResourceIdentifiers/ResourceTuplesr1.comments=['1','2']# or if resource type is not known or can have multiple types of resourcesr1.comments_or_people=[ResourceTuple('1','comments'),ResourceTuple('2','people')]# or if you want to add some resources you canr1.comments_or_people+=[ResourceTuple('1','people')]r1.commit()# change to-one relationshipsr1.author='3'# accepts also ResourceObjects/ResourceIdentifiers/ResourceTuple# or resource type is not known (via schema etc.)r1.author=ResourceTuple('3','people')# Committing changes (PATCH request)r1.commit(meta={'some_meta':'data'})# Resource committing supports optional meta data# AsyncIOawaitr1.commit(meta={'some_meta':'data'})

创建新资源
# Creating new resources. Schema must be given. Accepts dictionary of schema models# (key is model name and value is schema as json-schema.org).models_as_jsonschema={'articles':{'properties':{'title':{'type':'string'},'author':{'relation':'to-one','resource':['people']},'comments':{'relation':'to-many','resource':['comments']},}},'people':{'properties':{'first-name':{'type':'string'},'last-name':{'type':'string'},'twitter':{'type':['null','string']},}},'comments':{'properties':{'body':{'type':'string'},'author':{'relation':'to-one','resource':['people']}}}}# If you type schema by hand, it could be more convenient to type it as yml in a file# insteads=Session('http://localhost:8080/',schema=models_as_jsonschema)a=s.create('articles')# Creates empty ResourceObject of 'articles' typea.title='Test title'# Validates and performs POST request, and finally updates resource based on server responsea.commit(meta={'some_meta':'data'})# Or with AsyncIO, remember to awaitawaita.commit(meta={'some_meta':'data'})# Commit metadata could be also saved in advance:a.commit_metadata={'some_meta':'data'}# You can also commit all changed resources in session bys.commit()# or with AsyncIOawaits.commit()# Another example of resource creation, setting attributes and relationships & committing:# If you have underscores in your field names, you can pass them in fields keyword argument as# a dictionary:cust1=s.create_and_commit('articles',attribute='1',dict_object__attribute='2',to_one_relationship='3',to_many_relationship=['1','2'],fields={'some_field_with_underscore':'1'})# Async:cust1=awaits.create_and_commit('articles',attribute='1',dict_object__attribute='2',to_one_relationship='3',to_many_relationship=['1','2'],fields={'some_field_with_underscore':'1'})

删除资源

# Delete resourcecust1.delete()# Mark to be deletedcust1.commit()# Actually delete

学分

许可证

版权所有(C)2017,Qvantel

保留所有权利。

以源和二进制形式重新分配和使用,有无 如果满足以下条件,则允许修改:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name of the Qvantel nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

本软件由版权所有者和贡献者“按原样”提供,并且 任何明示或默示保证,包括但不限于 对特定用途的适销性和适合性的保证 否认。在任何情况下,Qvantel均不对任何 直接、间接、附带、特殊、惩戒性或后果性损害 (包括但不限于替代货物或服务的采购; 使用、数据或利润的损失;或营业中断),无论是何种原因造成的 论任何责任理论,无论是合同责任、严格责任还是侵权责任 (包括疏忽或其他)以任何方式产生的 软件,即使被告知有这种损坏的可能性。

变更日志

0.9.7(2019-02-01)

  • 在meta中支持getitem
  • 处理空关系数据列表
  • 允许以迭代器的形式返回到关系的链接
  • 修复处理空的一对一关系
  • 不要显式引用筛选器值
  • 包括支持

0.9.6(2017-06-26)

  • When creating new resources, use default value specified in jsonschema, when available.

0.9.5(2017-06-16)

  • Change Session.create_and_commit signature similarly as Session.create

0.9.4(2017-06-16)

  • Remove ? from filenames (illegal in Windows)
  • Pass event loop aiohttp’s ClientSession
  • Return resource from .commit if return status is 202
  • Support underscores in field names in Session.create() through fields keyword argument.
  • Add support for extra arguments such as authentication object
  • AsyncIO support for context manager usage of Session

0.9.3(2017-04-03)

  • Added aiohttp to install requirements

0.9.2(2017-04-03)

  • Github release.

0.9.1(2017-03-23)

  • Fix async content_type checking
  • Use Python 3’s new typing.NamedTuple instead of collections.NamedTuple
  • Make included resources available from Document
  • ResourceObject.json property

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

推荐PyPI第三方库


热门话题
java如何在jetty请求日志中添加milliscond字段?   java在使用Scanner类从文件读取信息时遇到问题   为什么。类不适用于泛型类型?   SQLite插入上的java空指针异常   java能告诉我们Guava缓存是在禁用统计数据的情况下构建的吗?   java在应用程序中使用常量   java无法使用AutoIT和Selenium Webdriver在所需位置/文件夹保存图像   java如何在jtable中更新jprogress栏   java是比较给定日期和当前日期(在给定时区中没有时间段)的最佳方法   安卓代码中的java错误   java无法访问实体类中的字段   java如何在tomcat中处理三个JDBC连接池?   java无法使用Spring Security保护AngularJS页面   如何在没有TCP/IP协议栈的情况下用Java发送以太帧