Guest User

Untitled

a guest
May 25th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. from pprint import pprint
  2. from typing import Any, Dict, List
  3.  
  4. from marshmallow import Schema, fields, ValidationError, post_load
  5.  
  6.  
  7. RAW = '''{
  8. "id": "LC81770382018108LGN00",
  9. "geometry": {
  10. "type": "Polygon",
  11. "coordinates": [
  12. [
  13. [
  14. 30.024526874451784,
  15. 32.78682209753362
  16. ],
  17. [
  18. 31.957976470246887,
  19. 32.41139662622062
  20. ],
  21. [
  22. 31.477118543417134,
  23. 30.686648489399253
  24. ],
  25. [
  26. 29.57999924553097,
  27. 31.061660146074402
  28. ],
  29. [
  30. 30.024526874451784,
  31. 32.78682209753362
  32. ]
  33. ]
  34. ]
  35. },
  36. "properties": {
  37. "acquired_on": "2018-04-18T08:28:55.492251Z",
  38. "cloud_cover": 0.014,
  39. "resolution": 30,
  40. "wrs_path": "177",
  41. "wrs_row": "038"
  42. },
  43. "type": "Feature"
  44. }'''
  45.  
  46.  
  47. class Feature:
  48. class Geometry:
  49. def __init__(self, type: str, coordinates: List[Any]):
  50. self.type = type
  51. self.coordinates = coordinates
  52.  
  53. def __init__(self, id: str, geometry: Geometry, properties: Dict[str, Any], type: str = 'Feature'):
  54. self.geometry = geometry
  55. self.id = id
  56. self.properties = properties
  57. self.type = type
  58.  
  59.  
  60. class FeatureSchema(Schema):
  61. class GeometrySchema(Schema):
  62. type = fields.Str()
  63. coordinates = fields.List(fields.Field())
  64.  
  65. @post_load
  66. def instantiate(self, data):
  67. return Feature.Geometry(**data)
  68.  
  69. id = fields.Str()
  70. type = fields.Constant('Feature')
  71. geometry = fields.Nested(GeometrySchema)
  72. properties = fields.Dict()
  73.  
  74. @post_load
  75. def instantiate(self, data: Dict):
  76. data.pop('type')
  77. return Feature(**data)
  78.  
  79.  
  80. try:
  81. feature: Feature = FeatureSchema(strict=True).loads(RAW).data
  82. print(feature)
  83. except ValidationError as err:
  84. print('error:', err)
  85. exit(1)
Add Comment
Please, Sign In to add comment