m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

815 lines
26 KiB

6 months ago
  1. import logging
  2. from itertools import * # noqa
  3. from jsonpath_ng.lexer import JsonPathLexer
  4. # Get logger name
  5. logger = logging.getLogger(__name__)
  6. # Turn on/off the automatic creation of id attributes
  7. # ... could be a kwarg pervasively but uses are rare and simple today
  8. auto_id_field = None
  9. NOT_SET = object()
  10. LIST_KEY = object()
  11. class JSONPath:
  12. """
  13. The base class for JSONPath abstract syntax; those
  14. methods stubbed here are the interface to supported
  15. JSONPath semantics.
  16. """
  17. def find(self, data):
  18. """
  19. All `JSONPath` types support `find()`, which returns an iterable of `DatumInContext`s.
  20. They keep track of the path followed to the current location, so if the calling code
  21. has some opinion about that, it can be passed in here as a starting point.
  22. """
  23. raise NotImplementedError()
  24. def find_or_create(self, data):
  25. return self.find(data)
  26. def update(self, data, val):
  27. """
  28. Returns `data` with the specified path replaced by `val`. Only updates
  29. if the specified path exists.
  30. """
  31. raise NotImplementedError()
  32. def update_or_create(self, data, val):
  33. return self.update(data, val)
  34. def filter(self, fn, data):
  35. """
  36. Returns `data` with the specified path filtering nodes according
  37. the filter evaluation result returned by the filter function.
  38. Arguments:
  39. fn (function): unary function that accepts one argument
  40. and returns bool.
  41. data (dict|list|tuple): JSON object to filter.
  42. """
  43. raise NotImplementedError()
  44. def child(self, child):
  45. """
  46. Equivalent to Child(self, next) but with some canonicalization
  47. """
  48. if isinstance(self, This) or isinstance(self, Root):
  49. return child
  50. elif isinstance(child, This):
  51. return self
  52. elif isinstance(child, Root):
  53. return child
  54. else:
  55. return Child(self, child)
  56. def make_datum(self, value):
  57. if isinstance(value, DatumInContext):
  58. return value
  59. else:
  60. return DatumInContext(value, path=Root(), context=None)
  61. class DatumInContext:
  62. """
  63. Represents a datum along a path from a context.
  64. Essentially a zipper but with a structure represented by JsonPath,
  65. and where the context is more of a parent pointer than a proper
  66. representation of the context.
  67. For quick-and-dirty work, this proxies any non-special attributes
  68. to the underlying datum, but the actual datum can (and usually should)
  69. be retrieved via the `value` attribute.
  70. To place `datum` within another, use `datum.in_context(context=..., path=...)`
  71. which extends the path. If the datum already has a context, it places the entire
  72. context within that passed in, so an object can be built from the inside
  73. out.
  74. """
  75. @classmethod
  76. def wrap(cls, data):
  77. if isinstance(data, cls):
  78. return data
  79. else:
  80. return cls(data)
  81. def __init__(self, value, path=None, context=None):
  82. self.value = value
  83. self.path = path or This()
  84. self.context = None if context is None else DatumInContext.wrap(context)
  85. def in_context(self, context, path):
  86. context = DatumInContext.wrap(context)
  87. if self.context:
  88. return DatumInContext(value=self.value, path=self.path, context=context.in_context(path=path, context=context))
  89. else:
  90. return DatumInContext(value=self.value, path=path, context=context)
  91. @property
  92. def full_path(self):
  93. return self.path if self.context is None else self.context.full_path.child(self.path)
  94. @property
  95. def id_pseudopath(self):
  96. """
  97. Looks like a path, but with ids stuck in when available
  98. """
  99. try:
  100. pseudopath = Fields(str(self.value[auto_id_field]))
  101. except (TypeError, AttributeError, KeyError): # This may not be all the interesting exceptions
  102. pseudopath = self.path
  103. if self.context:
  104. return self.context.id_pseudopath.child(pseudopath)
  105. else:
  106. return pseudopath
  107. def __repr__(self):
  108. return '%s(value=%r, path=%r, context=%r)' % (self.__class__.__name__, self.value, self.path, self.context)
  109. def __eq__(self, other):
  110. return isinstance(other, DatumInContext) and other.value == self.value and other.path == self.path and self.context == other.context
  111. class AutoIdForDatum(DatumInContext):
  112. """
  113. This behaves like a DatumInContext, but the value is
  114. always the path leading up to it, not including the "id",
  115. and with any "id" fields along the way replacing the prior
  116. segment of the path
  117. For example, it will make "foo.bar.id" return a datum
  118. that behaves like DatumInContext(value="foo.bar", path="foo.bar.id").
  119. This is disabled by default; it can be turned on by
  120. settings the `auto_id_field` global to a value other
  121. than `None`.
  122. """
  123. def __init__(self, datum, id_field=None):
  124. """
  125. Invariant is that datum.path is the path from context to datum. The auto id
  126. will either be the id in the datum (if present) or the id of the context
  127. followed by the path to the datum.
  128. The path to this datum is always the path to the context, the path to the
  129. datum, and then the auto id field.
  130. """
  131. self.datum = datum
  132. self.id_field = id_field or auto_id_field
  133. @property
  134. def value(self):
  135. return str(self.datum.id_pseudopath)
  136. @property
  137. def path(self):
  138. return self.id_field
  139. @property
  140. def context(self):
  141. return self.datum
  142. def __repr__(self):
  143. return '%s(%r)' % (self.__class__.__name__, self.datum)
  144. def in_context(self, context, path):
  145. return AutoIdForDatum(self.datum.in_context(context=context, path=path))
  146. def __eq__(self, other):
  147. return isinstance(other, AutoIdForDatum) and other.datum == self.datum and self.id_field == other.id_field
  148. class Root(JSONPath):
  149. """
  150. The JSONPath referring to the "root" object. Concrete syntax is '$'.
  151. The root is the topmost datum without any context attached.
  152. """
  153. def find(self, data):
  154. if not isinstance(data, DatumInContext):
  155. return [DatumInContext(data, path=Root(), context=None)]
  156. else:
  157. if data.context is None:
  158. return [DatumInContext(data.value, context=None, path=Root())]
  159. else:
  160. return Root().find(data.context)
  161. def update(self, data, val):
  162. return val
  163. def filter(self, fn, data):
  164. return data if fn(data) else None
  165. def __str__(self):
  166. return '$'
  167. def __repr__(self):
  168. return 'Root()'
  169. def __eq__(self, other):
  170. return isinstance(other, Root)
  171. def __hash__(self):
  172. return hash('$')
  173. class This(JSONPath):
  174. """
  175. The JSONPath referring to the current datum. Concrete syntax is '@'.
  176. """
  177. def find(self, datum):
  178. return [DatumInContext.wrap(datum)]
  179. def update(self, data, val):
  180. return val
  181. def filter(self, fn, data):
  182. return data if fn(data) else None
  183. def __str__(self):
  184. return '`this`'
  185. def __repr__(self):
  186. return 'This()'
  187. def __eq__(self, other):
  188. return isinstance(other, This)
  189. def __hash__(self):
  190. return hash('this')
  191. class Child(JSONPath):
  192. """
  193. JSONPath that first matches the left, then the right.
  194. Concrete syntax is <left> '.' <right>
  195. """
  196. def __init__(self, left, right):
  197. self.left = left
  198. self.right = right
  199. def find(self, datum):
  200. """
  201. Extra special case: auto ids do not have children,
  202. so cut it off right now rather than auto id the auto id
  203. """
  204. return [submatch
  205. for subdata in self.left.find(datum)
  206. if not isinstance(subdata, AutoIdForDatum)
  207. for submatch in self.right.find(subdata)]
  208. def update(self, data, val):
  209. for datum in self.left.find(data):
  210. self.right.update(datum.value, val)
  211. return data
  212. def find_or_create(self, datum):
  213. datum = DatumInContext.wrap(datum)
  214. submatches = []
  215. for subdata in self.left.find_or_create(datum):
  216. if isinstance(subdata, AutoIdForDatum):
  217. # Extra special case: auto ids do not have children,
  218. # so cut it off right now rather than auto id the auto id
  219. continue
  220. for submatch in self.right.find_or_create(subdata):
  221. submatches.append(submatch)
  222. return submatches
  223. def update_or_create(self, data, val):
  224. for datum in self.left.find_or_create(data):
  225. self.right.update_or_create(datum.value, val)
  226. return _clean_list_keys(data)
  227. def filter(self, fn, data):
  228. for datum in self.left.find(data):
  229. self.right.filter(fn, datum.value)
  230. return data
  231. def __eq__(self, other):
  232. return isinstance(other, Child) and self.left == other.left and self.right == other.right
  233. def __str__(self):
  234. return '%s.%s' % (self.left, self.right)
  235. def __repr__(self):
  236. return '%s(%r, %r)' % (self.__class__.__name__, self.left, self.right)
  237. def __hash__(self):
  238. return hash((self.left, self.right))
  239. class Parent(JSONPath):
  240. """
  241. JSONPath that matches the parent node of the current match.
  242. Will crash if no such parent exists.
  243. Available via named operator `parent`.
  244. """
  245. def find(self, datum):
  246. datum = DatumInContext.wrap(datum)
  247. return [datum.context]
  248. def __eq__(self, other):
  249. return isinstance(other, Parent)
  250. def __str__(self):
  251. return '`parent`'
  252. def __repr__(self):
  253. return 'Parent()'
  254. def __hash__(self):
  255. return hash('parent')
  256. class Where(JSONPath):
  257. """
  258. JSONPath that first matches the left, and then
  259. filters for only those nodes that have
  260. a match on the right.
  261. WARNING: Subject to change. May want to have "contains"
  262. or some other better word for it.
  263. """
  264. def __init__(self, left, right):
  265. self.left = left
  266. self.right = right
  267. def find(self, data):
  268. return [subdata for subdata in self.left.find(data) if self.right.find(subdata)]
  269. def update(self, data, val):
  270. for datum in self.find(data):
  271. datum.path.update(data, val)
  272. return data
  273. def filter(self, fn, data):
  274. for datum in self.find(data):
  275. datum.path.filter(fn, datum.value)
  276. return data
  277. def __str__(self):
  278. return '%s where %s' % (self.left, self.right)
  279. def __eq__(self, other):
  280. return isinstance(other, Where) and other.left == self.left and other.right == self.right
  281. def __hash__(self):
  282. return hash((self.left, self.right))
  283. class Descendants(JSONPath):
  284. """
  285. JSONPath that matches first the left expression then any descendant
  286. of it which matches the right expression.
  287. """
  288. def __init__(self, left, right):
  289. self.left = left
  290. self.right = right
  291. def find(self, datum):
  292. # <left> .. <right> ==> <left> . (<right> | *..<right> | [*]..<right>)
  293. #
  294. # With with a wonky caveat that since Slice() has funky coercions
  295. # we cannot just delegate to that equivalence or we'll hit an
  296. # infinite loop. So right here we implement the coercion-free version.
  297. # Get all left matches into a list
  298. left_matches = self.left.find(datum)
  299. if not isinstance(left_matches, list):
  300. left_matches = [left_matches]
  301. def match_recursively(datum):
  302. right_matches = self.right.find(datum)
  303. # Manually do the * or [*] to avoid coercion and recurse just the right-hand pattern
  304. if isinstance(datum.value, list):
  305. recursive_matches = [submatch
  306. for i in range(0, len(datum.value))
  307. for submatch in match_recursively(DatumInContext(datum.value[i], context=datum, path=Index(i)))]
  308. elif isinstance(datum.value, dict):
  309. recursive_matches = [submatch
  310. for field in datum.value.keys()
  311. for submatch in match_recursively(DatumInContext(datum.value[field], context=datum, path=Fields(field)))]
  312. else:
  313. recursive_matches = []
  314. return right_matches + list(recursive_matches)
  315. # TODO: repeatable iterator instead of list?
  316. return [submatch
  317. for left_match in left_matches
  318. for submatch in match_recursively(left_match)]
  319. def is_singular(self):
  320. return False
  321. def update(self, data, val):
  322. # Get all left matches into a list
  323. left_matches = self.left.find(data)
  324. if not isinstance(left_matches, list):
  325. left_matches = [left_matches]
  326. def update_recursively(data):
  327. # Update only mutable values corresponding to JSON types
  328. if not (isinstance(data, list) or isinstance(data, dict)):
  329. return
  330. self.right.update(data, val)
  331. # Manually do the * or [*] to avoid coercion and recurse just the right-hand pattern
  332. if isinstance(data, list):
  333. for i in range(0, len(data)):
  334. update_recursively(data[i])
  335. elif isinstance(data, dict):
  336. for field in data.keys():
  337. update_recursively(data[field])
  338. for submatch in left_matches:
  339. update_recursively(submatch.value)
  340. return data
  341. def filter(self, fn, data):
  342. # Get all left matches into a list
  343. left_matches = self.left.find(data)
  344. if not isinstance(left_matches, list):
  345. left_matches = [left_matches]
  346. def filter_recursively(data):
  347. # Update only mutable values corresponding to JSON types
  348. if not (isinstance(data, list) or isinstance(data, dict)):
  349. return
  350. self.right.filter(fn, data)
  351. # Manually do the * or [*] to avoid coercion and recurse just the right-hand pattern
  352. if isinstance(data, list):
  353. for i in range(0, len(data)):
  354. filter_recursively(data[i])
  355. elif isinstance(data, dict):
  356. for field in data.keys():
  357. filter_recursively(data[field])
  358. for submatch in left_matches:
  359. filter_recursively(submatch.value)
  360. return data
  361. def __str__(self):
  362. return '%s..%s' % (self.left, self.right)
  363. def __eq__(self, other):
  364. return isinstance(other, Descendants) and self.left == other.left and self.right == other.right
  365. def __repr__(self):
  366. return '%s(%r, %r)' % (self.__class__.__name__, self.left, self.right)
  367. def __hash__(self):
  368. return hash((self.left, self.right))
  369. class Union(JSONPath):
  370. """
  371. JSONPath that returns the union of the results of each match.
  372. This is pretty shoddily implemented for now. The nicest semantics
  373. in case of mismatched bits (list vs atomic) is to put
  374. them all in a list, but I haven't done that yet.
  375. WARNING: Any appearance of this being the _concatenation_ is
  376. coincidence. It may even be a bug! (or laziness)
  377. """
  378. def __init__(self, left, right):
  379. self.left = left
  380. self.right = right
  381. def is_singular(self):
  382. return False
  383. def find(self, data):
  384. return self.left.find(data) + self.right.find(data)
  385. def __eq__(self, other):
  386. return isinstance(other, Union) and self.left == other.left and self.right == other.right
  387. def __hash__(self):
  388. return hash((self.left, self.right))
  389. class Intersect(JSONPath):
  390. """
  391. JSONPath for bits that match *both* patterns.
  392. This can be accomplished a couple of ways. The most
  393. efficient is to actually build the intersected
  394. AST as in building a state machine for matching the
  395. intersection of regular languages. The next
  396. idea is to build a filtered data and match against
  397. that.
  398. """
  399. def __init__(self, left, right):
  400. self.left = left
  401. self.right = right
  402. def is_singular(self):
  403. return False
  404. def find(self, data):
  405. raise NotImplementedError()
  406. def __eq__(self, other):
  407. return isinstance(other, Intersect) and self.left == other.left and self.right == other.right
  408. def __hash__(self):
  409. return hash((self.left, self.right))
  410. class Fields(JSONPath):
  411. """
  412. JSONPath referring to some field of the current object.
  413. Concrete syntax ix comma-separated field names.
  414. WARNING: If '*' is any of the field names, then they will
  415. all be returned.
  416. """
  417. def __init__(self, *fields):
  418. self.fields = fields
  419. @staticmethod
  420. def get_field_datum(datum, field, create):
  421. if field == auto_id_field:
  422. return AutoIdForDatum(datum)
  423. try:
  424. field_value = datum.value.get(field, NOT_SET)
  425. if field_value is NOT_SET:
  426. if create:
  427. datum.value[field] = field_value = {}
  428. else:
  429. return None
  430. return DatumInContext(field_value, path=Fields(field), context=datum)
  431. except (TypeError, AttributeError):
  432. return None
  433. def reified_fields(self, datum):
  434. if '*' not in self.fields:
  435. return self.fields
  436. else:
  437. try:
  438. fields = tuple(datum.value.keys())
  439. return fields if auto_id_field is None else fields + (auto_id_field,)
  440. except AttributeError:
  441. return ()
  442. def find(self, datum):
  443. return self._find_base(datum, create=False)
  444. def find_or_create(self, datum):
  445. return self._find_base(datum, create=True)
  446. def _find_base(self, datum, create):
  447. datum = DatumInContext.wrap(datum)
  448. field_data = [self.get_field_datum(datum, field, create)
  449. for field in self.reified_fields(datum)]
  450. return [fd for fd in field_data if fd is not None]
  451. def update(self, data, val):
  452. return self._update_base(data, val, create=False)
  453. def update_or_create(self, data, val):
  454. return self._update_base(data, val, create=True)
  455. def _update_base(self, data, val, create):
  456. if data is not None:
  457. for field in self.reified_fields(DatumInContext.wrap(data)):
  458. if field not in data and create:
  459. data[field] = {}
  460. if field in data:
  461. if hasattr(val, '__call__'):
  462. data[field] = val(data[field], data, field)
  463. else:
  464. data[field] = val
  465. return data
  466. def filter(self, fn, data):
  467. if data is not None:
  468. for field in self.reified_fields(DatumInContext.wrap(data)):
  469. if field in data:
  470. if fn(data[field]):
  471. data.pop(field)
  472. return data
  473. def __str__(self):
  474. # If any JsonPathLexer.literals are included in field name need quotes
  475. # This avoids unnecessary quotes to keep strings short.
  476. # Test each field whether it contains a literal and only then add quotes
  477. # The test loops over all literals, could possibly optimize to short circuit if one found
  478. fields_as_str = ("'" + str(f) + "'" if any([l in f for l in JsonPathLexer.literals]) else
  479. str(f) for f in self.fields)
  480. return ','.join(fields_as_str)
  481. def __repr__(self):
  482. return '%s(%s)' % (self.__class__.__name__, ','.join(map(repr, self.fields)))
  483. def __eq__(self, other):
  484. return isinstance(other, Fields) and tuple(self.fields) == tuple(other.fields)
  485. def __hash__(self):
  486. return hash(tuple(self.fields))
  487. class Index(JSONPath):
  488. """
  489. JSONPath that matches indices of the current datum, or none if not large enough.
  490. Concrete syntax is brackets.
  491. WARNING: If the datum is None or not long enough, it will not crash but will not match anything.
  492. NOTE: For the concrete syntax of `[*]`, the abstract syntax is a Slice() with no parameters (equiv to `[:]`
  493. """
  494. def __init__(self, index):
  495. self.index = index
  496. def find(self, datum):
  497. return self._find_base(datum, create=False)
  498. def find_or_create(self, datum):
  499. return self._find_base(datum, create=True)
  500. def _find_base(self, datum, create):
  501. datum = DatumInContext.wrap(datum)
  502. if create:
  503. if datum.value == {}:
  504. datum.value = _create_list_key(datum.value)
  505. self._pad_value(datum.value)
  506. if datum.value and len(datum.value) > self.index:
  507. return [DatumInContext(datum.value[self.index], path=self, context=datum)]
  508. else:
  509. return []
  510. def update(self, data, val):
  511. return self._update_base(data, val, create=False)
  512. def update_or_create(self, data, val):
  513. return self._update_base(data, val, create=True)
  514. def _update_base(self, data, val, create):
  515. if create:
  516. if data == {}:
  517. data = _create_list_key(data)
  518. self._pad_value(data)
  519. if hasattr(val, '__call__'):
  520. data[self.index] = val.__call__(data[self.index], data, self.index)
  521. elif len(data) > self.index:
  522. data[self.index] = val
  523. return data
  524. def filter(self, fn, data):
  525. if fn(data[self.index]):
  526. data.pop(self.index) # relies on mutation :(
  527. return data
  528. def __eq__(self, other):
  529. return isinstance(other, Index) and self.index == other.index
  530. def __str__(self):
  531. return '[%i]' % self.index
  532. def __repr__(self):
  533. return '%s(index=%r)' % (self.__class__.__name__, self.index)
  534. def _pad_value(self, value):
  535. if len(value) <= self.index:
  536. pad = self.index - len(value) + 1
  537. value += [{} for __ in range(pad)]
  538. def __hash__(self):
  539. return hash(self.index)
  540. class Slice(JSONPath):
  541. """
  542. JSONPath matching a slice of an array.
  543. Because of a mismatch between JSON and XML when schema-unaware,
  544. this always returns an iterable; if the incoming data
  545. was not a list, then it returns a one element list _containing_ that
  546. data.
  547. Consider these two docs, and their schema-unaware translation to JSON:
  548. <a><b>hello</b></a> ==> {"a": {"b": "hello"}}
  549. <a><b>hello</b><b>goodbye</b></a> ==> {"a": {"b": ["hello", "goodbye"]}}
  550. If there were a schema, it would be known that "b" should always be an
  551. array (unless the schema were wonky, but that is too much to fix here)
  552. so when querying with JSON if the one writing the JSON knows that it
  553. should be an array, they can write a slice operator and it will coerce
  554. a non-array value to an array.
  555. This may be a bit unfortunate because it would be nice to always have
  556. an iterator, but dictionaries and other objects may also be iterable,
  557. so this is the compromise.
  558. """
  559. def __init__(self, start=None, end=None, step=None):
  560. self.start = start
  561. self.end = end
  562. self.step = step
  563. def find(self, datum):
  564. datum = DatumInContext.wrap(datum)
  565. # Used for catching null value instead of empty list in path
  566. if not datum.value:
  567. return []
  568. # Here's the hack. If it is a dictionary or some kind of constant,
  569. # put it in a single-element list
  570. if (isinstance(datum.value, dict) or isinstance(datum.value, int) or isinstance(datum.value, str)):
  571. return self.find(DatumInContext([datum.value], path=datum.path, context=datum.context))
  572. # Some iterators do not support slicing but we can still
  573. # at least work for '*'
  574. if self.start is None and self.end is None and self.step is None:
  575. return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in range(0, len(datum.value))]
  576. else:
  577. return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in range(0, len(datum.value))[self.start:self.end:self.step]]
  578. def update(self, data, val):
  579. for datum in self.find(data):
  580. datum.path.update(data, val)
  581. return data
  582. def filter(self, fn, data):
  583. while True:
  584. length = len(data)
  585. for datum in self.find(data):
  586. data = datum.path.filter(fn, data)
  587. if len(data) < length:
  588. break
  589. if length == len(data):
  590. break
  591. return data
  592. def __str__(self):
  593. if self.start is None and self.end is None and self.step is None:
  594. return '[*]'
  595. else:
  596. return '[%s%s%s]' % (self.start or '',
  597. ':%d'%self.end if self.end else '',
  598. ':%d'%self.step if self.step else '')
  599. def __repr__(self):
  600. return '%s(start=%r,end=%r,step=%r)' % (self.__class__.__name__, self.start, self.end, self.step)
  601. def __eq__(self, other):
  602. return isinstance(other, Slice) and other.start == self.start and self.end == other.end and other.step == self.step
  603. def __hash__(self):
  604. return hash((self.start, self.end, self.step))
  605. def _create_list_key(dict_):
  606. """
  607. Adds a list to a dictionary by reference and returns the list.
  608. See `_clean_list_keys()`
  609. """
  610. dict_[LIST_KEY] = new_list = [{}]
  611. return new_list
  612. def _clean_list_keys(struct_):
  613. """
  614. Replace {LIST_KEY: ['foo', 'bar']} with ['foo', 'bar'].
  615. >>> _clean_list_keys({LIST_KEY: ['foo', 'bar']})
  616. ['foo', 'bar']
  617. """
  618. if(isinstance(struct_, list)):
  619. for ind, value in enumerate(struct_):
  620. struct_[ind] = _clean_list_keys(value)
  621. elif(isinstance(struct_, dict)):
  622. if(LIST_KEY in struct_):
  623. return _clean_list_keys(struct_[LIST_KEY])
  624. else:
  625. for key, value in struct_.items():
  626. struct_[key] = _clean_list_keys(value)
  627. return struct_