一个用于Contentful的Python工具箱,允许您以ORM样式创建/维护内容类型和查询。

contentful-orm的Python项目详细描述


知足虫


一个用于Contentful的Python工具箱,允许您以ORM样式创建/维护内容类型和查询。在

安装


  • 要安装:
    pip install git+https://github.com/Phoenix-Chen/ContentfulORM.git
    

使用


ORM环境


  • 创建ORM环境: ^{pr2}$ 在

内容类型模型


  • 为您的内容类型建模:
    fromdatetimeimportdatetimefromcontentful_orm.modelsimportModelfromcontentful_orm.fieldsimportArrayField,BooleanField,DateField,DecimalField,IntegerField,MediaField,ReferenceField,SymbolField,TextField,LocationFieldfromcontentful_orm.fields.validationsimportIn,Range,Unique,Size,Regex,ImageDimensions,FileSize# class name will become content type name# class name in camel case will become content type idclassPerson(Model):# docstring will become content type description"""Person model description    """__display_field__='name'# Each field need to be a {SomeType}Field from contentful_orm.fields# Most of the fields have keyword argument: disabled, localized, omitted, required, validations and default# (disabled, localized, omitted and required default to False. validations defaults to []. default defaults to None)email=SymbolField(validations=[Unique,Regex('^\\w[\\w.-]*@([\\w-]+\\.)+[\\w-]+$',error_msg='Invalid email address.')],required=True)name=SymbolField(localized=True,required=True)# ArrayField takes an argument to specify content typetitle=ArrayField(SymbolField(validations=[In(['Manager','Seller'],error_msg='Invalid title')]),localized=True)age=IntegerField(validations=[Range(min=1,error_msg='age must be a positive integer.')])created_date=DateField(default=datetime.now().strftime("%Y-%m-%dT%H:%M-00:00"))classCompany(Model):"""Company model description    """__display_field__='name'name=SymbolField(validations=[Unique],required=True)employees=ArrayField(ReferenceField(model_set={Person},error_msg='employee has to be a Person entry'))address=LocationField()classProduct(Model):"""Product model description    """__display_field__='name'name=SymbolField(validations=[Unique],required=True)description=TextField(localized=True)# ReferenceField takes an additional keyword argument model_set to restrict reference content type.# (Currently doesn't support reference to the content type itself)seller=ReferenceField(model_set={Person,Company},error_msg="seller has to be a Person or Company entry")images=ArrayField(MediaField(# validations takes a list of contentful_orm.fields.validations# See: https://www.contentful.com/r/knowledgebase/validations/ for detailsvalidations=[ImageDimensions(max_width=12,max_height=12),FileSize(max=40000,error_msg='Maximum file size is 40000 Bytes')]),validations=[Size(max=10,error_msg="At most 10 images")])sponsored=BooleanField(required=True)price=DecimalField(required=True)
  • 使用模型创建和发布内容类型:
    orm_env.create(Person).publish()# Ororm_env.create(Person)orm_env.publish(Person)
  • 使用模型取消发布并删除内容类型:
    orm_env.unpublish(Product)orm_env.delete(Product)
  • 添加和发布条目:
    person1=orm_env.add(Person(email='a@a.com',name='a',title=['Manager','Seller'],age=13)).publish()# You can specify entry id or it will randomly generate a UUIDperson2=orm_env.add(Person(email='b@a.com',name='b',title=['Seller'],age=66),id='S9SN3JWKN3565D').publish()person3=orm_env.add(Person(email='c@a.com',name='c',title=['Manager'],created_date='2019-08-11T00:00-07:00')).publish()company1=orm_env.add(Company(name='Contentful',employees=[person1.to_link().to_json(),person2.to_link().to_json()])).publish()# Orproduct1=Product(name='ContentfulORM',description='Write your Contentful in ORM style!',seller=company1.to_link().to_json(),sponsored=True,price=0.01)orm_env.add(product1).publish()
  • 查询:
    # Query all entries of a content typeorm_env.query(Person).all()# Filter query# ORMContentTypeEntriesProxy extends ContentTypeEntriesProxy with additional filter functionfromcontentful_orm.operatorsimportall_,limit,select,skip# Filter with field names as keyword arguments for exact searchorm_env.query(Person).filter(email='c@a.com',name='c')# Filter with operators, see operators all at: https://github.com/Phoenix-Chen/ContentfulORM/blob/dev/contentful_orm/operators.pyorm_env.query(Person).filter(all_(title=['Manager','seller']),skip(1),limit(100),select('fields.name'))# Use combination of bothorm_env.query(Person).filter(limit(1),name='c')
  • 序列化:
    fromcontentful_orm.serializersimportModelSerializerclassProductSerializer(ModelSerializer):classMeta:model=Product# Specify fields to be serialized or use '__all__' for all the fieldsfields=['name','description','price']# Query the entry/entries you want to serializeproducts=orm_env.query(Product).all()# Serialize single entryserialized_product=ProductSerializer(products[0])# Serialize multiple entriesserialized_products=ProductSerializer(products,many=True)# Currently links won't be recursively serialized, in case of circular references.

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

推荐PyPI第三方库


热门话题
java Spring启动启用HTTPS   actionscript 3 java中的这个[“var”+“name”]   java只匹配给定集合中一个字符的一个匹配项   java Hibernate:防止角色表中出现多个相同的条目   javajersey+Spring注入servlet请求   java HtmlEditor javafx失去焦点   java Apache Wicket AjaxRequestTarget ListView组件未刷新或更新   mysql java。无法将lang.String转换为java。sql。时间戳   java将巨大的整数文件(在一行中)拆分为具有内存限制的已排序块   安卓如何完全关闭proguard?   安装Eclipse和Android SDK后的java“无AVD可用”消息   java动态显示图像视图   java在Spring中还有哪些WebsocketClient实现?   java Glassfish需要很长时间才能重新启动   使用Java简单串行连接器将pc与arduino连接   java如何在camel文件组件配置中结合readLockCheckInterval和maxMessagesPerPoll?   单击Android时的java预览图像   java如何将字节数组转换为ByteArrayOutputStream