ccxt 4.2.77__py2.py3-none-any.whl → 4.4.49__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (546) hide show
  1. ccxt/__init__.py +36 -14
  2. ccxt/abstract/alpaca.py +4 -0
  3. ccxt/abstract/bigone.py +1 -1
  4. ccxt/abstract/binance.py +112 -48
  5. ccxt/abstract/binancecoinm.py +112 -48
  6. ccxt/abstract/binanceus.py +147 -83
  7. ccxt/abstract/binanceusdm.py +112 -48
  8. ccxt/abstract/bingx.py +133 -78
  9. ccxt/abstract/bitbank.py +5 -0
  10. ccxt/abstract/bitfinex.py +136 -65
  11. ccxt/abstract/bitfinex1.py +69 -0
  12. ccxt/abstract/bitflyer.py +1 -0
  13. ccxt/abstract/bitget.py +8 -1
  14. ccxt/abstract/bitmart.py +13 -1
  15. ccxt/abstract/bitopro.py +1 -0
  16. ccxt/abstract/bitpanda.py +0 -12
  17. ccxt/abstract/bitrue.py +3 -3
  18. ccxt/abstract/bitstamp.py +26 -3
  19. ccxt/abstract/blofin.py +24 -0
  20. ccxt/abstract/btcbox.py +1 -0
  21. ccxt/abstract/bybit.py +29 -14
  22. ccxt/abstract/cex.py +28 -29
  23. ccxt/abstract/coinbase.py +6 -0
  24. ccxt/abstract/coinbaseadvanced.py +94 -0
  25. ccxt/abstract/{coinbasepro.py → coinbaseexchange.py} +1 -0
  26. ccxt/abstract/coinbaseinternational.py +1 -1
  27. ccxt/abstract/coincatch.py +94 -0
  28. ccxt/abstract/coinex.py +233 -123
  29. ccxt/abstract/coinmetro.py +1 -0
  30. ccxt/abstract/cryptocom.py +14 -0
  31. ccxt/abstract/defx.py +69 -0
  32. ccxt/abstract/deribit.py +1 -0
  33. ccxt/abstract/digifinex.py +1 -0
  34. ccxt/abstract/ellipx.py +25 -0
  35. ccxt/abstract/gate.py +20 -0
  36. ccxt/abstract/gateio.py +20 -0
  37. ccxt/abstract/gemini.py +1 -0
  38. ccxt/abstract/hashkey.py +67 -0
  39. ccxt/abstract/hyperliquid.py +1 -1
  40. ccxt/abstract/independentreserve.py +6 -0
  41. ccxt/abstract/kraken.py +4 -3
  42. ccxt/abstract/krakenfutures.py +4 -0
  43. ccxt/abstract/kucoin.py +24 -0
  44. ccxt/abstract/kucoinfutures.py +34 -0
  45. ccxt/abstract/luno.py +2 -0
  46. ccxt/abstract/mexc.py +4 -0
  47. ccxt/abstract/myokx.py +340 -0
  48. ccxt/abstract/oceanex.py +5 -0
  49. ccxt/abstract/okx.py +30 -0
  50. ccxt/abstract/onetrading.py +0 -12
  51. ccxt/abstract/oxfun.py +34 -0
  52. ccxt/abstract/paradex.py +40 -0
  53. ccxt/abstract/phemex.py +1 -0
  54. ccxt/abstract/upbit.py +4 -0
  55. ccxt/abstract/vertex.py +19 -0
  56. ccxt/abstract/whitebit.py +31 -1
  57. ccxt/abstract/woo.py +6 -2
  58. ccxt/abstract/woofipro.py +119 -0
  59. ccxt/abstract/xt.py +153 -0
  60. ccxt/abstract/zonda.py +6 -0
  61. ccxt/ace.py +164 -60
  62. ccxt/alpaca.py +727 -63
  63. ccxt/ascendex.py +395 -249
  64. ccxt/async_support/__init__.py +36 -14
  65. ccxt/async_support/ace.py +164 -60
  66. ccxt/async_support/alpaca.py +727 -63
  67. ccxt/async_support/ascendex.py +396 -249
  68. ccxt/async_support/base/exchange.py +531 -155
  69. ccxt/async_support/base/ws/aiohttp_client.py +28 -5
  70. ccxt/async_support/base/ws/cache.py +3 -2
  71. ccxt/async_support/base/ws/client.py +26 -5
  72. ccxt/async_support/base/ws/fast_client.py +4 -3
  73. ccxt/async_support/base/ws/functions.py +1 -1
  74. ccxt/async_support/base/ws/future.py +40 -31
  75. ccxt/async_support/base/ws/order_book_side.py +3 -0
  76. ccxt/async_support/bequant.py +1 -1
  77. ccxt/async_support/bigone.py +329 -202
  78. ccxt/async_support/binance.py +3030 -1087
  79. ccxt/async_support/binancecoinm.py +2 -1
  80. ccxt/async_support/binanceus.py +12 -1
  81. ccxt/async_support/binanceusdm.py +3 -1
  82. ccxt/async_support/bingx.py +3205 -937
  83. ccxt/async_support/bit2c.py +119 -38
  84. ccxt/async_support/bitbank.py +215 -76
  85. ccxt/async_support/bitbns.py +124 -53
  86. ccxt/async_support/bitfinex.py +3236 -1078
  87. ccxt/async_support/bitfinex1.py +1711 -0
  88. ccxt/async_support/bitflyer.py +238 -49
  89. ccxt/async_support/bitget.py +1525 -573
  90. ccxt/async_support/bithumb.py +199 -65
  91. ccxt/async_support/bitmart.py +1320 -435
  92. ccxt/async_support/bitmex.py +308 -111
  93. ccxt/async_support/bitopro.py +256 -96
  94. ccxt/async_support/bitrue.py +365 -233
  95. ccxt/async_support/bitso.py +201 -89
  96. ccxt/async_support/bitstamp.py +438 -269
  97. ccxt/async_support/bitteam.py +179 -73
  98. ccxt/async_support/bitvavo.py +180 -70
  99. ccxt/async_support/bl3p.py +92 -25
  100. ccxt/async_support/blockchaincom.py +193 -79
  101. ccxt/async_support/blofin.py +392 -148
  102. ccxt/async_support/btcalpha.py +161 -55
  103. ccxt/async_support/btcbox.py +250 -34
  104. ccxt/async_support/btcmarkets.py +232 -85
  105. ccxt/async_support/btcturk.py +159 -60
  106. ccxt/async_support/bybit.py +2231 -1193
  107. ccxt/async_support/cex.py +1409 -1329
  108. ccxt/async_support/coinbase.py +1454 -287
  109. ccxt/async_support/coinbaseadvanced.py +17 -0
  110. ccxt/async_support/{coinbasepro.py → coinbaseexchange.py} +233 -99
  111. ccxt/async_support/coinbaseinternational.py +428 -88
  112. ccxt/async_support/coincatch.py +5152 -0
  113. ccxt/async_support/coincheck.py +121 -38
  114. ccxt/async_support/coinex.py +4020 -3339
  115. ccxt/async_support/coinlist.py +273 -116
  116. ccxt/async_support/coinmate.py +204 -97
  117. ccxt/async_support/coinmetro.py +203 -110
  118. ccxt/async_support/coinone.py +142 -68
  119. ccxt/async_support/coinsph.py +223 -97
  120. ccxt/async_support/coinspot.py +137 -62
  121. ccxt/async_support/cryptocom.py +515 -185
  122. ccxt/async_support/currencycom.py +203 -85
  123. ccxt/async_support/defx.py +2066 -0
  124. ccxt/async_support/delta.py +404 -109
  125. ccxt/async_support/deribit.py +639 -323
  126. ccxt/async_support/digifinex.py +465 -233
  127. ccxt/async_support/ellipx.py +1887 -0
  128. ccxt/async_support/exmo.py +317 -128
  129. ccxt/async_support/gate.py +1472 -463
  130. ccxt/async_support/gemini.py +206 -84
  131. ccxt/async_support/hashkey.py +4164 -0
  132. ccxt/async_support/hitbtc.py +433 -178
  133. ccxt/async_support/hollaex.py +207 -83
  134. ccxt/async_support/htx.py +1095 -563
  135. ccxt/async_support/huobijp.py +178 -56
  136. ccxt/async_support/hyperliquid.py +1678 -292
  137. ccxt/async_support/idex.py +219 -95
  138. ccxt/async_support/independentreserve.py +300 -31
  139. ccxt/async_support/indodax.py +226 -62
  140. ccxt/async_support/kraken.py +871 -354
  141. ccxt/async_support/krakenfutures.py +324 -100
  142. ccxt/async_support/kucoin.py +917 -357
  143. ccxt/async_support/kucoinfutures.py +1004 -149
  144. ccxt/async_support/kuna.py +198 -107
  145. ccxt/async_support/latoken.py +199 -79
  146. ccxt/async_support/lbank.py +360 -113
  147. ccxt/async_support/luno.py +185 -62
  148. ccxt/async_support/lykke.py +168 -55
  149. ccxt/async_support/mercado.py +101 -29
  150. ccxt/async_support/mexc.py +995 -429
  151. ccxt/async_support/myokx.py +53 -0
  152. ccxt/async_support/ndax.py +234 -82
  153. ccxt/async_support/novadax.py +195 -75
  154. ccxt/async_support/oceanex.py +244 -59
  155. ccxt/async_support/okcoin.py +301 -165
  156. ccxt/async_support/okx.py +1776 -454
  157. ccxt/async_support/onetrading.py +198 -414
  158. ccxt/async_support/oxfun.py +2898 -0
  159. ccxt/async_support/p2b.py +142 -52
  160. ccxt/async_support/paradex.py +2085 -0
  161. ccxt/async_support/paymium.py +56 -32
  162. ccxt/async_support/phemex.py +572 -196
  163. ccxt/async_support/poloniex.py +218 -95
  164. ccxt/async_support/poloniexfutures.py +260 -92
  165. ccxt/async_support/probit.py +143 -110
  166. ccxt/async_support/timex.py +123 -70
  167. ccxt/async_support/tokocrypto.py +129 -93
  168. ccxt/async_support/tradeogre.py +39 -25
  169. ccxt/async_support/upbit.py +322 -113
  170. ccxt/async_support/vertex.py +2983 -0
  171. ccxt/async_support/wavesexchange.py +227 -173
  172. ccxt/async_support/wazirx.py +145 -65
  173. ccxt/async_support/whitebit.py +533 -138
  174. ccxt/async_support/woo.py +1137 -296
  175. ccxt/async_support/woofipro.py +2716 -0
  176. ccxt/async_support/xt.py +4628 -0
  177. ccxt/async_support/yobit.py +160 -92
  178. ccxt/async_support/zaif.py +80 -33
  179. ccxt/async_support/zonda.py +140 -69
  180. ccxt/base/errors.py +51 -20
  181. ccxt/base/exchange.py +1722 -480
  182. ccxt/base/precise.py +10 -0
  183. ccxt/base/types.py +223 -4
  184. ccxt/bequant.py +1 -1
  185. ccxt/bigone.py +329 -202
  186. ccxt/binance.py +3030 -1087
  187. ccxt/binancecoinm.py +2 -1
  188. ccxt/binanceus.py +12 -1
  189. ccxt/binanceusdm.py +3 -1
  190. ccxt/bingx.py +3205 -937
  191. ccxt/bit2c.py +119 -38
  192. ccxt/bitbank.py +215 -76
  193. ccxt/bitbns.py +124 -53
  194. ccxt/bitfinex.py +3235 -1078
  195. ccxt/bitfinex1.py +1710 -0
  196. ccxt/bitflyer.py +238 -49
  197. ccxt/bitget.py +1525 -573
  198. ccxt/bithumb.py +198 -65
  199. ccxt/bitmart.py +1320 -435
  200. ccxt/bitmex.py +308 -111
  201. ccxt/bitopro.py +256 -96
  202. ccxt/bitrue.py +365 -233
  203. ccxt/bitso.py +201 -89
  204. ccxt/bitstamp.py +438 -269
  205. ccxt/bitteam.py +179 -73
  206. ccxt/bitvavo.py +180 -70
  207. ccxt/bl3p.py +92 -25
  208. ccxt/blockchaincom.py +193 -79
  209. ccxt/blofin.py +392 -148
  210. ccxt/btcalpha.py +161 -55
  211. ccxt/btcbox.py +250 -34
  212. ccxt/btcmarkets.py +232 -85
  213. ccxt/btcturk.py +159 -60
  214. ccxt/bybit.py +2231 -1193
  215. ccxt/cex.py +1408 -1329
  216. ccxt/coinbase.py +1454 -287
  217. ccxt/coinbaseadvanced.py +17 -0
  218. ccxt/{coinbasepro.py → coinbaseexchange.py} +233 -99
  219. ccxt/coinbaseinternational.py +428 -88
  220. ccxt/coincatch.py +5152 -0
  221. ccxt/coincheck.py +121 -38
  222. ccxt/coinex.py +4020 -3339
  223. ccxt/coinlist.py +273 -116
  224. ccxt/coinmate.py +204 -97
  225. ccxt/coinmetro.py +203 -110
  226. ccxt/coinone.py +142 -68
  227. ccxt/coinsph.py +223 -97
  228. ccxt/coinspot.py +137 -62
  229. ccxt/cryptocom.py +515 -185
  230. ccxt/currencycom.py +203 -85
  231. ccxt/defx.py +2065 -0
  232. ccxt/delta.py +404 -109
  233. ccxt/deribit.py +639 -323
  234. ccxt/digifinex.py +465 -233
  235. ccxt/ellipx.py +1887 -0
  236. ccxt/exmo.py +317 -128
  237. ccxt/gate.py +1472 -463
  238. ccxt/gemini.py +206 -84
  239. ccxt/hashkey.py +4164 -0
  240. ccxt/hitbtc.py +433 -178
  241. ccxt/hollaex.py +207 -83
  242. ccxt/htx.py +1095 -563
  243. ccxt/huobijp.py +178 -56
  244. ccxt/hyperliquid.py +1677 -292
  245. ccxt/idex.py +219 -95
  246. ccxt/independentreserve.py +299 -31
  247. ccxt/indodax.py +226 -62
  248. ccxt/kraken.py +871 -354
  249. ccxt/krakenfutures.py +324 -100
  250. ccxt/kucoin.py +917 -357
  251. ccxt/kucoinfutures.py +1004 -149
  252. ccxt/kuna.py +198 -107
  253. ccxt/latoken.py +199 -79
  254. ccxt/lbank.py +360 -113
  255. ccxt/luno.py +185 -62
  256. ccxt/lykke.py +168 -55
  257. ccxt/mercado.py +101 -29
  258. ccxt/mexc.py +994 -429
  259. ccxt/myokx.py +53 -0
  260. ccxt/ndax.py +234 -82
  261. ccxt/novadax.py +195 -75
  262. ccxt/oceanex.py +244 -59
  263. ccxt/okcoin.py +301 -165
  264. ccxt/okx.py +1776 -454
  265. ccxt/onetrading.py +198 -414
  266. ccxt/oxfun.py +2897 -0
  267. ccxt/p2b.py +142 -52
  268. ccxt/paradex.py +2085 -0
  269. ccxt/paymium.py +56 -32
  270. ccxt/phemex.py +572 -196
  271. ccxt/poloniex.py +218 -95
  272. ccxt/poloniexfutures.py +260 -92
  273. ccxt/pro/__init__.py +29 -5
  274. ccxt/pro/alpaca.py +32 -17
  275. ccxt/pro/ascendex.py +62 -14
  276. ccxt/pro/bequant.py +4 -0
  277. ccxt/pro/binance.py +1596 -329
  278. ccxt/pro/binancecoinm.py +1 -0
  279. ccxt/pro/binanceus.py +2 -9
  280. ccxt/pro/binanceusdm.py +2 -0
  281. ccxt/pro/bingx.py +527 -134
  282. ccxt/pro/bitcoincom.py +4 -1
  283. ccxt/pro/bitfinex.py +731 -266
  284. ccxt/pro/bitfinex1.py +635 -0
  285. ccxt/pro/bitget.py +726 -357
  286. ccxt/pro/bithumb.py +380 -0
  287. ccxt/pro/bitmart.py +143 -39
  288. ccxt/pro/bitmex.py +199 -40
  289. ccxt/pro/bitopro.py +25 -13
  290. ccxt/pro/bitrue.py +31 -32
  291. ccxt/pro/bitstamp.py +7 -6
  292. ccxt/pro/bitvavo.py +203 -81
  293. ccxt/pro/blockchaincom.py +30 -17
  294. ccxt/pro/blofin.py +692 -0
  295. ccxt/pro/bybit.py +791 -82
  296. ccxt/pro/cex.py +99 -51
  297. ccxt/pro/coinbase.py +220 -30
  298. ccxt/{async_support/hitbtc3.py → pro/coinbaseadvanced.py} +5 -5
  299. ccxt/pro/{coinbasepro.py → coinbaseexchange.py} +19 -19
  300. ccxt/pro/coinbaseinternational.py +193 -30
  301. ccxt/pro/coincatch.py +1464 -0
  302. ccxt/pro/coincheck.py +11 -6
  303. ccxt/pro/coinex.py +965 -665
  304. ccxt/pro/coinone.py +17 -10
  305. ccxt/pro/cryptocom.py +446 -66
  306. ccxt/pro/currencycom.py +11 -10
  307. ccxt/pro/defx.py +832 -0
  308. ccxt/pro/deribit.py +167 -31
  309. ccxt/pro/exmo.py +252 -20
  310. ccxt/pro/gate.py +729 -64
  311. ccxt/pro/gemini.py +44 -26
  312. ccxt/pro/hashkey.py +802 -0
  313. ccxt/pro/hitbtc.py +208 -103
  314. ccxt/pro/hollaex.py +25 -9
  315. ccxt/pro/htx.py +83 -39
  316. ccxt/pro/huobijp.py +17 -16
  317. ccxt/pro/hyperliquid.py +502 -31
  318. ccxt/pro/idex.py +28 -13
  319. ccxt/pro/independentreserve.py +21 -16
  320. ccxt/pro/kraken.py +298 -51
  321. ccxt/pro/krakenfutures.py +166 -75
  322. ccxt/pro/kucoin.py +395 -77
  323. ccxt/pro/kucoinfutures.py +400 -99
  324. ccxt/pro/lbank.py +52 -31
  325. ccxt/pro/luno.py +12 -10
  326. ccxt/pro/mexc.py +400 -50
  327. ccxt/pro/myokx.py +28 -0
  328. ccxt/pro/ndax.py +25 -12
  329. ccxt/pro/okcoin.py +28 -9
  330. ccxt/pro/okx.py +935 -124
  331. ccxt/pro/onetrading.py +41 -24
  332. ccxt/pro/oxfun.py +1054 -0
  333. ccxt/pro/p2b.py +100 -24
  334. ccxt/pro/paradex.py +352 -0
  335. ccxt/pro/phemex.py +92 -33
  336. ccxt/pro/poloniex.py +128 -49
  337. ccxt/pro/poloniexfutures.py +53 -32
  338. ccxt/pro/probit.py +92 -85
  339. ccxt/pro/upbit.py +401 -8
  340. ccxt/pro/vertex.py +943 -0
  341. ccxt/pro/wazirx.py +46 -28
  342. ccxt/pro/whitebit.py +65 -12
  343. ccxt/pro/woo.py +437 -65
  344. ccxt/pro/woofipro.py +1271 -0
  345. ccxt/pro/xt.py +1067 -0
  346. ccxt/probit.py +143 -110
  347. ccxt/static_dependencies/__init__.py +1 -1
  348. ccxt/static_dependencies/lark/__init__.py +38 -0
  349. ccxt/static_dependencies/lark/__pyinstaller/__init__.py +6 -0
  350. ccxt/static_dependencies/lark/__pyinstaller/hook-lark.py +14 -0
  351. ccxt/static_dependencies/lark/ast_utils.py +59 -0
  352. ccxt/static_dependencies/lark/common.py +86 -0
  353. ccxt/static_dependencies/lark/exceptions.py +292 -0
  354. ccxt/static_dependencies/lark/grammar.py +130 -0
  355. ccxt/static_dependencies/lark/grammars/__init__.py +0 -0
  356. ccxt/static_dependencies/lark/indenter.py +143 -0
  357. ccxt/static_dependencies/lark/lark.py +658 -0
  358. ccxt/static_dependencies/lark/lexer.py +678 -0
  359. ccxt/static_dependencies/lark/load_grammar.py +1428 -0
  360. ccxt/static_dependencies/lark/parse_tree_builder.py +391 -0
  361. ccxt/static_dependencies/lark/parser_frontends.py +257 -0
  362. ccxt/static_dependencies/lark/parsers/__init__.py +0 -0
  363. ccxt/static_dependencies/lark/parsers/cyk.py +340 -0
  364. ccxt/static_dependencies/lark/parsers/earley.py +314 -0
  365. ccxt/static_dependencies/lark/parsers/earley_common.py +42 -0
  366. ccxt/static_dependencies/lark/parsers/earley_forest.py +801 -0
  367. ccxt/static_dependencies/lark/parsers/grammar_analysis.py +203 -0
  368. ccxt/static_dependencies/lark/parsers/lalr_analysis.py +332 -0
  369. ccxt/static_dependencies/lark/parsers/lalr_interactive_parser.py +158 -0
  370. ccxt/static_dependencies/lark/parsers/lalr_parser.py +122 -0
  371. ccxt/static_dependencies/lark/parsers/lalr_parser_state.py +110 -0
  372. ccxt/static_dependencies/lark/parsers/xearley.py +165 -0
  373. ccxt/static_dependencies/lark/py.typed +0 -0
  374. ccxt/static_dependencies/lark/reconstruct.py +107 -0
  375. ccxt/static_dependencies/lark/tools/__init__.py +70 -0
  376. ccxt/static_dependencies/lark/tools/nearley.py +202 -0
  377. ccxt/static_dependencies/lark/tools/serialize.py +32 -0
  378. ccxt/static_dependencies/lark/tools/standalone.py +196 -0
  379. ccxt/static_dependencies/lark/tree.py +267 -0
  380. ccxt/static_dependencies/lark/tree_matcher.py +186 -0
  381. ccxt/static_dependencies/lark/tree_templates.py +180 -0
  382. ccxt/static_dependencies/lark/utils.py +343 -0
  383. ccxt/static_dependencies/lark/visitors.py +596 -0
  384. ccxt/static_dependencies/marshmallow/__init__.py +81 -0
  385. ccxt/static_dependencies/marshmallow/base.py +65 -0
  386. ccxt/static_dependencies/marshmallow/class_registry.py +94 -0
  387. ccxt/static_dependencies/marshmallow/decorators.py +231 -0
  388. ccxt/static_dependencies/marshmallow/error_store.py +60 -0
  389. ccxt/static_dependencies/marshmallow/exceptions.py +71 -0
  390. ccxt/static_dependencies/marshmallow/fields.py +2114 -0
  391. ccxt/static_dependencies/marshmallow/orderedset.py +89 -0
  392. ccxt/static_dependencies/marshmallow/py.typed +0 -0
  393. ccxt/static_dependencies/marshmallow/schema.py +1228 -0
  394. ccxt/static_dependencies/marshmallow/types.py +12 -0
  395. ccxt/static_dependencies/marshmallow/utils.py +378 -0
  396. ccxt/static_dependencies/marshmallow/validate.py +678 -0
  397. ccxt/static_dependencies/marshmallow/warnings.py +2 -0
  398. ccxt/static_dependencies/marshmallow_dataclass/__init__.py +1047 -0
  399. ccxt/static_dependencies/marshmallow_dataclass/collection_field.py +51 -0
  400. ccxt/static_dependencies/marshmallow_dataclass/lazy_class_attribute.py +45 -0
  401. ccxt/static_dependencies/marshmallow_dataclass/mypy.py +71 -0
  402. ccxt/static_dependencies/marshmallow_dataclass/py.typed +0 -0
  403. ccxt/static_dependencies/marshmallow_dataclass/typing.py +14 -0
  404. ccxt/static_dependencies/marshmallow_dataclass/union_field.py +82 -0
  405. ccxt/static_dependencies/marshmallow_oneofschema/__init__.py +1 -0
  406. ccxt/static_dependencies/marshmallow_oneofschema/one_of_schema.py +193 -0
  407. ccxt/static_dependencies/marshmallow_oneofschema/py.typed +0 -0
  408. ccxt/static_dependencies/starknet/__init__.py +0 -0
  409. ccxt/static_dependencies/starknet/cairo/__init__.py +0 -0
  410. ccxt/static_dependencies/starknet/cairo/data_types.py +123 -0
  411. ccxt/static_dependencies/starknet/cairo/deprecated_parse/__init__.py +0 -0
  412. ccxt/static_dependencies/starknet/cairo/deprecated_parse/cairo_types.py +77 -0
  413. ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser.py +46 -0
  414. ccxt/static_dependencies/starknet/cairo/deprecated_parse/parser_transformer.py +138 -0
  415. ccxt/static_dependencies/starknet/cairo/felt.py +64 -0
  416. ccxt/static_dependencies/starknet/cairo/type_parser.py +121 -0
  417. ccxt/static_dependencies/starknet/cairo/v1/__init__.py +0 -0
  418. ccxt/static_dependencies/starknet/cairo/v1/type_parser.py +59 -0
  419. ccxt/static_dependencies/starknet/cairo/v2/__init__.py +0 -0
  420. ccxt/static_dependencies/starknet/cairo/v2/type_parser.py +77 -0
  421. ccxt/static_dependencies/starknet/ccxt_utils.py +7 -0
  422. ccxt/static_dependencies/starknet/common.py +15 -0
  423. ccxt/static_dependencies/starknet/constants.py +39 -0
  424. ccxt/static_dependencies/starknet/hash/__init__.py +0 -0
  425. ccxt/static_dependencies/starknet/hash/address.py +79 -0
  426. ccxt/static_dependencies/starknet/hash/compiled_class_hash_objects.py +111 -0
  427. ccxt/static_dependencies/starknet/hash/selector.py +16 -0
  428. ccxt/static_dependencies/starknet/hash/storage.py +12 -0
  429. ccxt/static_dependencies/starknet/hash/utils.py +78 -0
  430. ccxt/static_dependencies/starknet/models/__init__.py +0 -0
  431. ccxt/static_dependencies/starknet/models/typed_data.py +45 -0
  432. ccxt/static_dependencies/starknet/serialization/__init__.py +24 -0
  433. ccxt/static_dependencies/starknet/serialization/_calldata_reader.py +40 -0
  434. ccxt/static_dependencies/starknet/serialization/_context.py +142 -0
  435. ccxt/static_dependencies/starknet/serialization/data_serializers/__init__.py +10 -0
  436. ccxt/static_dependencies/starknet/serialization/data_serializers/_common.py +82 -0
  437. ccxt/static_dependencies/starknet/serialization/data_serializers/array_serializer.py +43 -0
  438. ccxt/static_dependencies/starknet/serialization/data_serializers/bool_serializer.py +37 -0
  439. ccxt/static_dependencies/starknet/serialization/data_serializers/byte_array_serializer.py +66 -0
  440. ccxt/static_dependencies/starknet/serialization/data_serializers/cairo_data_serializer.py +71 -0
  441. ccxt/static_dependencies/starknet/serialization/data_serializers/enum_serializer.py +71 -0
  442. ccxt/static_dependencies/starknet/serialization/data_serializers/felt_serializer.py +50 -0
  443. ccxt/static_dependencies/starknet/serialization/data_serializers/named_tuple_serializer.py +58 -0
  444. ccxt/static_dependencies/starknet/serialization/data_serializers/option_serializer.py +43 -0
  445. ccxt/static_dependencies/starknet/serialization/data_serializers/output_serializer.py +40 -0
  446. ccxt/static_dependencies/starknet/serialization/data_serializers/payload_serializer.py +72 -0
  447. ccxt/static_dependencies/starknet/serialization/data_serializers/struct_serializer.py +36 -0
  448. ccxt/static_dependencies/starknet/serialization/data_serializers/tuple_serializer.py +36 -0
  449. ccxt/static_dependencies/starknet/serialization/data_serializers/uint256_serializer.py +76 -0
  450. ccxt/static_dependencies/starknet/serialization/data_serializers/uint_serializer.py +100 -0
  451. ccxt/static_dependencies/starknet/serialization/data_serializers/unit_serializer.py +32 -0
  452. ccxt/static_dependencies/starknet/serialization/errors.py +10 -0
  453. ccxt/static_dependencies/starknet/serialization/factory.py +229 -0
  454. ccxt/static_dependencies/starknet/serialization/function_serialization_adapter.py +110 -0
  455. ccxt/static_dependencies/starknet/serialization/tuple_dataclass.py +59 -0
  456. ccxt/static_dependencies/starknet/utils/__init__.py +0 -0
  457. ccxt/static_dependencies/starknet/utils/constructor_args_translator.py +86 -0
  458. ccxt/static_dependencies/starknet/utils/iterable.py +13 -0
  459. ccxt/static_dependencies/starknet/utils/schema.py +13 -0
  460. ccxt/static_dependencies/starknet/utils/typed_data.py +182 -0
  461. ccxt/static_dependencies/starkware/__init__.py +0 -0
  462. ccxt/static_dependencies/starkware/crypto/__init__.py +0 -0
  463. ccxt/static_dependencies/starkware/crypto/fast_pedersen_hash.py +50 -0
  464. ccxt/static_dependencies/starkware/crypto/math_utils.py +78 -0
  465. ccxt/static_dependencies/starkware/crypto/signature.py +2344 -0
  466. ccxt/static_dependencies/starkware/crypto/utils.py +63 -0
  467. ccxt/static_dependencies/sympy/__init__.py +0 -0
  468. ccxt/static_dependencies/sympy/core/__init__.py +0 -0
  469. ccxt/static_dependencies/sympy/core/intfunc.py +35 -0
  470. ccxt/static_dependencies/sympy/external/__init__.py +0 -0
  471. ccxt/static_dependencies/sympy/external/gmpy.py +345 -0
  472. ccxt/static_dependencies/sympy/external/importtools.py +187 -0
  473. ccxt/static_dependencies/sympy/external/ntheory.py +637 -0
  474. ccxt/static_dependencies/sympy/external/pythonmpq.py +341 -0
  475. ccxt/static_dependencies/typing_inspect/__init__.py +0 -0
  476. ccxt/static_dependencies/typing_inspect/typing_inspect.py +851 -0
  477. ccxt/test/{test_async.py → tests_async.py} +456 -391
  478. ccxt/test/tests_helpers.py +285 -0
  479. ccxt/test/tests_init.py +39 -0
  480. ccxt/test/{test_sync.py → tests_sync.py} +456 -393
  481. ccxt/timex.py +123 -70
  482. ccxt/tokocrypto.py +129 -93
  483. ccxt/tradeogre.py +39 -25
  484. ccxt/upbit.py +322 -113
  485. ccxt/vertex.py +2983 -0
  486. ccxt/wavesexchange.py +227 -173
  487. ccxt/wazirx.py +145 -65
  488. ccxt/whitebit.py +533 -138
  489. ccxt/woo.py +1137 -296
  490. ccxt/woofipro.py +2716 -0
  491. ccxt/xt.py +4627 -0
  492. ccxt/yobit.py +159 -92
  493. ccxt/zaif.py +80 -33
  494. ccxt/zonda.py +140 -69
  495. ccxt-4.4.49.dist-info/LICENSE.txt +21 -0
  496. ccxt-4.4.49.dist-info/METADATA +646 -0
  497. ccxt-4.4.49.dist-info/RECORD +669 -0
  498. {ccxt-4.2.77.dist-info → ccxt-4.4.49.dist-info}/WHEEL +1 -1
  499. ccxt/abstract/bitbay.py +0 -47
  500. ccxt/abstract/bitfinex2.py +0 -139
  501. ccxt/abstract/hitbtc3.py +0 -115
  502. ccxt/async_support/bitbay.py +0 -17
  503. ccxt/async_support/bitfinex2.py +0 -3496
  504. ccxt/async_support/flowbtc.py +0 -34
  505. ccxt/bitbay.py +0 -17
  506. ccxt/bitfinex2.py +0 -3496
  507. ccxt/flowbtc.py +0 -34
  508. ccxt/hitbtc3.py +0 -16
  509. ccxt/pro/bitfinex2.py +0 -1081
  510. ccxt/test/base/__init__.py +0 -28
  511. ccxt/test/base/test_account.py +0 -26
  512. ccxt/test/base/test_balance.py +0 -56
  513. ccxt/test/base/test_borrow_interest.py +0 -35
  514. ccxt/test/base/test_borrow_rate.py +0 -32
  515. ccxt/test/base/test_calculate_fee.py +0 -51
  516. ccxt/test/base/test_crypto.py +0 -127
  517. ccxt/test/base/test_currency.py +0 -76
  518. ccxt/test/base/test_datetime.py +0 -103
  519. ccxt/test/base/test_decimal_to_precision.py +0 -392
  520. ccxt/test/base/test_deep_extend.py +0 -68
  521. ccxt/test/base/test_deposit_withdrawal.py +0 -50
  522. ccxt/test/base/test_exchange_datetime_functions.py +0 -76
  523. ccxt/test/base/test_funding_rate_history.py +0 -29
  524. ccxt/test/base/test_last_price.py +0 -32
  525. ccxt/test/base/test_ledger_entry.py +0 -45
  526. ccxt/test/base/test_ledger_item.py +0 -48
  527. ccxt/test/base/test_leverage_tier.py +0 -33
  528. ccxt/test/base/test_margin_mode.py +0 -24
  529. ccxt/test/base/test_margin_modification.py +0 -35
  530. ccxt/test/base/test_market.py +0 -190
  531. ccxt/test/base/test_number.py +0 -411
  532. ccxt/test/base/test_ohlcv.py +0 -32
  533. ccxt/test/base/test_open_interest.py +0 -32
  534. ccxt/test/base/test_order.py +0 -64
  535. ccxt/test/base/test_order_book.py +0 -63
  536. ccxt/test/base/test_position.py +0 -60
  537. ccxt/test/base/test_shared_methods.py +0 -345
  538. ccxt/test/base/test_status.py +0 -24
  539. ccxt/test/base/test_throttle.py +0 -126
  540. ccxt/test/base/test_ticker.py +0 -86
  541. ccxt/test/base/test_trade.py +0 -47
  542. ccxt/test/base/test_trading_fee.py +0 -26
  543. ccxt/test/base/test_transaction.py +0 -39
  544. ccxt-4.2.77.dist-info/METADATA +0 -626
  545. ccxt-4.2.77.dist-info/RECORD +0 -534
  546. {ccxt-4.2.77.dist-info → ccxt-4.4.49.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2114 @@
1
+ """Field classes for various types of data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import copy
7
+ import datetime as dt
8
+ import decimal
9
+ import ipaddress
10
+ import math
11
+ import numbers
12
+ import typing
13
+ import uuid
14
+ import warnings
15
+ from collections.abc import Mapping as _Mapping
16
+ from enum import Enum as EnumType
17
+
18
+ from . import class_registry, types, utils, validate
19
+ from .base import FieldABC, SchemaABC
20
+ from .exceptions import (
21
+ FieldInstanceResolutionError,
22
+ StringNotCollectionError,
23
+ ValidationError,
24
+ )
25
+ from .utils import (
26
+ is_aware,
27
+ is_collection,
28
+ resolve_field_instance,
29
+ )
30
+ from .utils import (
31
+ missing as missing_,
32
+ )
33
+ from .validate import And, Length
34
+ from .warnings import RemovedInMarshmallow4Warning
35
+
36
+ __all__ = [
37
+ "Field",
38
+ "Raw",
39
+ "Nested",
40
+ "Mapping",
41
+ "Dict",
42
+ "List",
43
+ "Tuple",
44
+ "String",
45
+ "UUID",
46
+ "Number",
47
+ "Integer",
48
+ "Decimal",
49
+ "Boolean",
50
+ "Float",
51
+ "DateTime",
52
+ "NaiveDateTime",
53
+ "AwareDateTime",
54
+ "Time",
55
+ "Date",
56
+ "TimeDelta",
57
+ "Url",
58
+ "URL",
59
+ "Email",
60
+ "IP",
61
+ "IPv4",
62
+ "IPv6",
63
+ "IPInterface",
64
+ "IPv4Interface",
65
+ "IPv6Interface",
66
+ "Enum",
67
+ "Method",
68
+ "Function",
69
+ "Str",
70
+ "Bool",
71
+ "Int",
72
+ "Constant",
73
+ "Pluck",
74
+ ]
75
+
76
+ _T = typing.TypeVar("_T")
77
+
78
+
79
+ class Field(FieldABC):
80
+ """Basic field from which other fields should extend. It applies no
81
+ formatting by default, and should only be used in cases where
82
+ data does not need to be formatted before being serialized or deserialized.
83
+ On error, the name of the field will be returned.
84
+
85
+ :param dump_default: If set, this value will be used during serialization if the
86
+ input value is missing. If not set, the field will be excluded from the
87
+ serialized output if the input value is missing. May be a value or a callable.
88
+ :param load_default: Default deserialization value for the field if the field is not
89
+ found in the input data. May be a value or a callable.
90
+ :param data_key: The name of the dict key in the external representation, i.e.
91
+ the input of `load` and the output of `dump`.
92
+ If `None`, the key will match the name of the field.
93
+ :param attribute: The name of the key/attribute in the internal representation, i.e.
94
+ the output of `load` and the input of `dump`.
95
+ If `None`, the key/attribute will match the name of the field.
96
+ Note: This should only be used for very specific use cases such as
97
+ outputting multiple fields for a single attribute, or using keys/attributes
98
+ that are invalid variable names, unsuitable for field names. In most cases,
99
+ you should use ``data_key`` instead.
100
+ :param validate: Validator or collection of validators that are called
101
+ during deserialization. Validator takes a field's input value as
102
+ its only parameter and returns a boolean.
103
+ If it returns `False`, an :exc:`ValidationError` is raised.
104
+ :param required: Raise a :exc:`ValidationError` if the field value
105
+ is not supplied during deserialization.
106
+ :param allow_none: Set this to `True` if `None` should be considered a valid value during
107
+ validation/deserialization. If ``load_default=None`` and ``allow_none`` is unset,
108
+ will default to ``True``. Otherwise, the default is ``False``.
109
+ :param load_only: If `True` skip this field during serialization, otherwise
110
+ its value will be present in the serialized data.
111
+ :param dump_only: If `True` skip this field during deserialization, otherwise
112
+ its value will be present in the deserialized object. In the context of an
113
+ HTTP API, this effectively marks the field as "read-only".
114
+ :param dict error_messages: Overrides for `Field.default_error_messages`.
115
+ :param metadata: Extra information to be stored as field metadata.
116
+
117
+ .. versionchanged:: 2.0.0
118
+ Removed `error` parameter. Use ``error_messages`` instead.
119
+
120
+ .. versionchanged:: 2.0.0
121
+ Added `allow_none` parameter, which makes validation/deserialization of `None`
122
+ consistent across fields.
123
+
124
+ .. versionchanged:: 2.0.0
125
+ Added `load_only` and `dump_only` parameters, which allow field skipping
126
+ during the (de)serialization process.
127
+
128
+ .. versionchanged:: 2.0.0
129
+ Added `missing` parameter, which indicates the value for a field if the field
130
+ is not found during deserialization.
131
+
132
+ .. versionchanged:: 2.0.0
133
+ ``default`` value is only used if explicitly set. Otherwise, missing values
134
+ inputs are excluded from serialized output.
135
+
136
+ .. versionchanged:: 3.0.0b8
137
+ Add ``data_key`` parameter for the specifying the key in the input and
138
+ output data. This parameter replaced both ``load_from`` and ``dump_to``.
139
+ """
140
+
141
+ # Some fields, such as Method fields and Function fields, are not expected
142
+ # to exist as attributes on the objects to serialize. Set this to False
143
+ # for those fields
144
+ _CHECK_ATTRIBUTE = True
145
+
146
+ #: Default error messages for various kinds of errors. The keys in this dictionary
147
+ #: are passed to `Field.make_error`. The values are error messages passed to
148
+ #: :exc:`marshmallow.exceptions.ValidationError`.
149
+ default_error_messages = {
150
+ "required": "Missing data for required field.",
151
+ "null": "Field may not be null.",
152
+ "validator_failed": "Invalid value.",
153
+ }
154
+
155
+ def __init__(
156
+ self,
157
+ *,
158
+ load_default: typing.Any = missing_,
159
+ missing: typing.Any = missing_,
160
+ dump_default: typing.Any = missing_,
161
+ default: typing.Any = missing_,
162
+ data_key: str | None = None,
163
+ attribute: str | None = None,
164
+ validate: (
165
+ None
166
+ | typing.Callable[[typing.Any], typing.Any]
167
+ | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]
168
+ ) = None,
169
+ required: bool = False,
170
+ allow_none: bool | None = None,
171
+ load_only: bool = False,
172
+ dump_only: bool = False,
173
+ error_messages: dict[str, str] | None = None,
174
+ metadata: typing.Mapping[str, typing.Any] | None = None,
175
+ **additional_metadata,
176
+ ) -> None:
177
+ # handle deprecated `default` and `missing` parameters
178
+ if default is not missing_:
179
+ warnings.warn(
180
+ "The 'default' argument to fields is deprecated. "
181
+ "Use 'dump_default' instead.",
182
+ RemovedInMarshmallow4Warning,
183
+ stacklevel=2,
184
+ )
185
+ if dump_default is missing_:
186
+ dump_default = default
187
+ if missing is not missing_:
188
+ warnings.warn(
189
+ "The 'missing' argument to fields is deprecated. "
190
+ "Use 'load_default' instead.",
191
+ RemovedInMarshmallow4Warning,
192
+ stacklevel=2,
193
+ )
194
+ if load_default is missing_:
195
+ load_default = missing
196
+ self.dump_default = dump_default
197
+ self.load_default = load_default
198
+
199
+ self.attribute = attribute
200
+ self.data_key = data_key
201
+ self.validate = validate
202
+ if validate is None:
203
+ self.validators = []
204
+ elif callable(validate):
205
+ self.validators = [validate]
206
+ elif utils.is_iterable_but_not_string(validate):
207
+ self.validators = list(validate)
208
+ else:
209
+ raise ValueError(
210
+ "The 'validate' parameter must be a callable "
211
+ "or a collection of callables."
212
+ )
213
+
214
+ # If allow_none is None and load_default is None
215
+ # None should be considered valid by default
216
+ self.allow_none = load_default is None if allow_none is None else allow_none
217
+ self.load_only = load_only
218
+ self.dump_only = dump_only
219
+ if required is True and load_default is not missing_:
220
+ raise ValueError("'load_default' must not be set for required fields.")
221
+ self.required = required
222
+
223
+ metadata = metadata or {}
224
+ self.metadata = {**metadata, **additional_metadata}
225
+ if additional_metadata:
226
+ warnings.warn(
227
+ "Passing field metadata as keyword arguments is deprecated. Use the "
228
+ "explicit `metadata=...` argument instead. "
229
+ f"Additional metadata: {additional_metadata}",
230
+ RemovedInMarshmallow4Warning,
231
+ stacklevel=2,
232
+ )
233
+
234
+ # Collect default error message from self and parent classes
235
+ messages = {} # type: dict[str, str]
236
+ for cls in reversed(self.__class__.__mro__):
237
+ messages.update(getattr(cls, "default_error_messages", {}))
238
+ messages.update(error_messages or {})
239
+ self.error_messages = messages
240
+
241
+ def __repr__(self) -> str:
242
+ return (
243
+ f"<fields.{self.__class__.__name__}(dump_default={self.dump_default!r}, "
244
+ f"attribute={self.attribute!r}, "
245
+ f"validate={self.validate}, required={self.required}, "
246
+ f"load_only={self.load_only}, dump_only={self.dump_only}, "
247
+ f"load_default={self.load_default}, allow_none={self.allow_none}, "
248
+ f"error_messages={self.error_messages})>"
249
+ )
250
+
251
+ def __deepcopy__(self, memo):
252
+ return copy.copy(self)
253
+
254
+ def get_value(self, obj, attr, accessor=None, default=missing_):
255
+ """Return the value for a given key from an object.
256
+
257
+ :param object obj: The object to get the value from.
258
+ :param str attr: The attribute/key in `obj` to get the value from.
259
+ :param callable accessor: A callable used to retrieve the value of `attr` from
260
+ the object `obj`. Defaults to `marshmallow.utils.get_value`.
261
+ """
262
+ accessor_func = accessor or utils.get_value
263
+ check_key = attr if self.attribute is None else self.attribute
264
+ return accessor_func(obj, check_key, default)
265
+
266
+ def _validate(self, value):
267
+ """Perform validation on ``value``. Raise a :exc:`ValidationError` if validation
268
+ does not succeed.
269
+ """
270
+ self._validate_all(value)
271
+
272
+ @property
273
+ def _validate_all(self):
274
+ return And(*self.validators, error=self.error_messages["validator_failed"])
275
+
276
+ def make_error(self, key: str, **kwargs) -> ValidationError:
277
+ """Helper method to make a `ValidationError` with an error message
278
+ from ``self.error_messages``.
279
+ """
280
+ try:
281
+ msg = self.error_messages[key]
282
+ except KeyError as error:
283
+ class_name = self.__class__.__name__
284
+ message = (
285
+ f"ValidationError raised by `{class_name}`, but error key `{key}` does "
286
+ "not exist in the `error_messages` dictionary."
287
+ )
288
+ raise AssertionError(message) from error
289
+ if isinstance(msg, (str, bytes)):
290
+ msg = msg.format(**kwargs)
291
+ return ValidationError(msg)
292
+
293
+ def fail(self, key: str, **kwargs):
294
+ """Helper method that raises a `ValidationError` with an error message
295
+ from ``self.error_messages``.
296
+
297
+ .. deprecated:: 3.0.0
298
+ Use `make_error <marshmallow.fields.Field.make_error>` instead.
299
+ """
300
+ warnings.warn(
301
+ f'`Field.fail` is deprecated. Use `raise self.make_error("{key}", ...)` instead.',
302
+ RemovedInMarshmallow4Warning,
303
+ stacklevel=2,
304
+ )
305
+ raise self.make_error(key=key, **kwargs)
306
+
307
+ def _validate_missing(self, value):
308
+ """Validate missing values. Raise a :exc:`ValidationError` if
309
+ `value` should be considered missing.
310
+ """
311
+ if value is missing_ and self.required:
312
+ raise self.make_error("required")
313
+ if value is None and not self.allow_none:
314
+ raise self.make_error("null")
315
+
316
+ def serialize(
317
+ self,
318
+ attr: str,
319
+ obj: typing.Any,
320
+ accessor: typing.Callable[[typing.Any, str, typing.Any], typing.Any]
321
+ | None = None,
322
+ **kwargs,
323
+ ):
324
+ """Pulls the value for the given key from the object, applies the
325
+ field's formatting and returns the result.
326
+
327
+ :param attr: The attribute/key to get from the object.
328
+ :param obj: The object to access the attribute/key from.
329
+ :param accessor: Function used to access values from ``obj``.
330
+ :param kwargs: Field-specific keyword arguments.
331
+ """
332
+ if self._CHECK_ATTRIBUTE:
333
+ value = self.get_value(obj, attr, accessor=accessor)
334
+ if value is missing_:
335
+ default = self.dump_default
336
+ value = default() if callable(default) else default
337
+ if value is missing_:
338
+ return value
339
+ else:
340
+ value = None
341
+ return self._serialize(value, attr, obj, **kwargs)
342
+
343
+ def deserialize(
344
+ self,
345
+ value: typing.Any,
346
+ attr: str | None = None,
347
+ data: typing.Mapping[str, typing.Any] | None = None,
348
+ **kwargs,
349
+ ):
350
+ """Deserialize ``value``.
351
+
352
+ :param value: The value to deserialize.
353
+ :param attr: The attribute/key in `data` to deserialize.
354
+ :param data: The raw input data passed to `Schema.load`.
355
+ :param kwargs: Field-specific keyword arguments.
356
+ :raise ValidationError: If an invalid value is passed or if a required value
357
+ is missing.
358
+ """
359
+ # Validate required fields, deserialize, then validate
360
+ # deserialized value
361
+ self._validate_missing(value)
362
+ if value is missing_:
363
+ _miss = self.load_default
364
+ return _miss() if callable(_miss) else _miss
365
+ if self.allow_none and value is None:
366
+ return None
367
+ output = self._deserialize(value, attr, data, **kwargs)
368
+ self._validate(output)
369
+ return output
370
+
371
+ # Methods for concrete classes to override.
372
+
373
+ def _bind_to_schema(self, field_name, schema):
374
+ """Update field with values from its parent schema. Called by
375
+ :meth:`Schema._bind_field <marshmallow.Schema._bind_field>`.
376
+
377
+ :param str field_name: Field name set in schema.
378
+ :param Schema|Field schema: Parent object.
379
+ """
380
+ self.parent = self.parent or schema
381
+ self.name = self.name or field_name
382
+ self.root = self.root or (
383
+ self.parent.root if isinstance(self.parent, FieldABC) else self.parent
384
+ )
385
+
386
+ def _serialize(
387
+ self, value: typing.Any, attr: str | None, obj: typing.Any, **kwargs
388
+ ):
389
+ """Serializes ``value`` to a basic Python datatype. Noop by default.
390
+ Concrete :class:`Field` classes should implement this method.
391
+
392
+ Example: ::
393
+
394
+ class TitleCase(Field):
395
+ def _serialize(self, value, attr, obj, **kwargs):
396
+ if not value:
397
+ return ""
398
+ return str(value).title()
399
+
400
+ :param value: The value to be serialized.
401
+ :param str attr: The attribute or key on the object to be serialized.
402
+ :param object obj: The object the value was pulled from.
403
+ :param dict kwargs: Field-specific keyword arguments.
404
+ :return: The serialized value
405
+ """
406
+ return value
407
+
408
+ def _deserialize(
409
+ self,
410
+ value: typing.Any,
411
+ attr: str | None,
412
+ data: typing.Mapping[str, typing.Any] | None,
413
+ **kwargs,
414
+ ):
415
+ """Deserialize value. Concrete :class:`Field` classes should implement this method.
416
+
417
+ :param value: The value to be deserialized.
418
+ :param attr: The attribute/key in `data` to be deserialized.
419
+ :param data: The raw input data passed to the `Schema.load`.
420
+ :param kwargs: Field-specific keyword arguments.
421
+ :raise ValidationError: In case of formatting or validation failure.
422
+ :return: The deserialized value.
423
+
424
+ .. versionchanged:: 2.0.0
425
+ Added ``attr`` and ``data`` parameters.
426
+
427
+ .. versionchanged:: 3.0.0
428
+ Added ``**kwargs`` to signature.
429
+ """
430
+ return value
431
+
432
+ # Properties
433
+
434
+ @property
435
+ def context(self):
436
+ """The context dictionary for the parent :class:`Schema`."""
437
+ return self.parent.context
438
+
439
+ # the default and missing properties are provided for compatibility and
440
+ # emit warnings when they are accessed and set
441
+ @property
442
+ def default(self):
443
+ warnings.warn(
444
+ "The 'default' attribute of fields is deprecated. "
445
+ "Use 'dump_default' instead.",
446
+ RemovedInMarshmallow4Warning,
447
+ stacklevel=2,
448
+ )
449
+ return self.dump_default
450
+
451
+ @default.setter
452
+ def default(self, value):
453
+ warnings.warn(
454
+ "The 'default' attribute of fields is deprecated. "
455
+ "Use 'dump_default' instead.",
456
+ RemovedInMarshmallow4Warning,
457
+ stacklevel=2,
458
+ )
459
+ self.dump_default = value
460
+
461
+ @property
462
+ def missing(self):
463
+ warnings.warn(
464
+ "The 'missing' attribute of fields is deprecated. "
465
+ "Use 'load_default' instead.",
466
+ RemovedInMarshmallow4Warning,
467
+ stacklevel=2,
468
+ )
469
+ return self.load_default
470
+
471
+ @missing.setter
472
+ def missing(self, value):
473
+ warnings.warn(
474
+ "The 'missing' attribute of fields is deprecated. "
475
+ "Use 'load_default' instead.",
476
+ RemovedInMarshmallow4Warning,
477
+ stacklevel=2,
478
+ )
479
+ self.load_default = value
480
+
481
+
482
+ class Raw(Field):
483
+ """Field that applies no formatting."""
484
+
485
+
486
+ class Nested(Field):
487
+ """Allows you to nest a :class:`Schema <marshmallow.Schema>`
488
+ inside a field.
489
+
490
+ Examples: ::
491
+
492
+ class ChildSchema(Schema):
493
+ id = fields.Str()
494
+ name = fields.Str()
495
+ # Use lambda functions when you need two-way nesting or self-nesting
496
+ parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True)
497
+ siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name"))))
498
+
499
+
500
+ class ParentSchema(Schema):
501
+ id = fields.Str()
502
+ children = fields.List(
503
+ fields.Nested(ChildSchema(only=("id", "parent", "siblings")))
504
+ )
505
+ spouse = fields.Nested(lambda: ParentSchema(only=("id",)))
506
+
507
+ When passing a `Schema <marshmallow.Schema>` instance as the first argument,
508
+ the instance's ``exclude``, ``only``, and ``many`` attributes will be respected.
509
+
510
+ Therefore, when passing the ``exclude``, ``only``, or ``many`` arguments to `fields.Nested`,
511
+ you should pass a `Schema <marshmallow.Schema>` class (not an instance) as the first argument.
512
+
513
+ ::
514
+
515
+ # Yes
516
+ author = fields.Nested(UserSchema, only=("id", "name"))
517
+
518
+ # No
519
+ author = fields.Nested(UserSchema(), only=("id", "name"))
520
+
521
+ :param nested: `Schema` instance, class, class name (string), dictionary, or callable that
522
+ returns a `Schema` or dictionary. Dictionaries are converted with `Schema.from_dict`.
523
+ :param exclude: A list or tuple of fields to exclude.
524
+ :param only: A list or tuple of fields to marshal. If `None`, all fields are marshalled.
525
+ This parameter takes precedence over ``exclude``.
526
+ :param many: Whether the field is a collection of objects.
527
+ :param unknown: Whether to exclude, include, or raise an error for unknown
528
+ fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
529
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
530
+ """
531
+
532
+ #: Default error messages.
533
+ default_error_messages = {"type": "Invalid type."}
534
+
535
+ def __init__(
536
+ self,
537
+ nested: SchemaABC
538
+ | type
539
+ | str
540
+ | dict[str, Field | type]
541
+ | typing.Callable[[], SchemaABC | type | dict[str, Field | type]],
542
+ *,
543
+ dump_default: typing.Any = missing_,
544
+ default: typing.Any = missing_,
545
+ only: types.StrSequenceOrSet | None = None,
546
+ exclude: types.StrSequenceOrSet = (),
547
+ many: bool = False,
548
+ unknown: str | None = None,
549
+ **kwargs,
550
+ ):
551
+ # Raise error if only or exclude is passed as string, not list of strings
552
+ if only is not None and not is_collection(only):
553
+ raise StringNotCollectionError('"only" should be a collection of strings.')
554
+ if not is_collection(exclude):
555
+ raise StringNotCollectionError(
556
+ '"exclude" should be a collection of strings.'
557
+ )
558
+ if nested == "self":
559
+ warnings.warn(
560
+ "Passing 'self' to `Nested` is deprecated. "
561
+ "Use `Nested(lambda: MySchema(...))` instead.",
562
+ RemovedInMarshmallow4Warning,
563
+ stacklevel=2,
564
+ )
565
+ self.nested = nested
566
+ self.only = only
567
+ self.exclude = exclude
568
+ self.many = many
569
+ self.unknown = unknown
570
+ self._schema = None # Cached Schema instance
571
+ super().__init__(default=default, dump_default=dump_default, **kwargs)
572
+
573
+ @property
574
+ def schema(self):
575
+ """The nested Schema object.
576
+
577
+ .. versionchanged:: 1.0.0
578
+ Renamed from `serializer` to `schema`.
579
+ """
580
+ if not self._schema:
581
+ # Inherit context from parent.
582
+ context = getattr(self.parent, "context", {})
583
+ if callable(self.nested) and not isinstance(self.nested, type):
584
+ nested = self.nested()
585
+ else:
586
+ nested = self.nested
587
+ if isinstance(nested, dict):
588
+ # defer the import of `marshmallow.schema` to avoid circular imports
589
+ from .schema import Schema
590
+
591
+ nested = Schema.from_dict(nested)
592
+
593
+ if isinstance(nested, SchemaABC):
594
+ self._schema = copy.copy(nested)
595
+ self._schema.context.update(context)
596
+ # Respect only and exclude passed from parent and re-initialize fields
597
+ set_class = self._schema.set_class
598
+ if self.only is not None:
599
+ if self._schema.only is not None:
600
+ original = self._schema.only
601
+ else: # only=None -> all fields
602
+ original = self._schema.fields.keys()
603
+ self._schema.only = set_class(self.only) & set_class(original)
604
+ if self.exclude:
605
+ original = self._schema.exclude
606
+ self._schema.exclude = set_class(self.exclude) | set_class(original)
607
+ self._schema._init_fields()
608
+ else:
609
+ if isinstance(nested, type) and issubclass(nested, SchemaABC):
610
+ schema_class = nested
611
+ elif not isinstance(nested, (str, bytes)):
612
+ raise ValueError(
613
+ "`Nested` fields must be passed a "
614
+ f"`Schema`, not {nested.__class__}."
615
+ )
616
+ elif nested == "self":
617
+ schema_class = self.root.__class__
618
+ else:
619
+ schema_class = class_registry.get_class(nested)
620
+ self._schema = schema_class(
621
+ many=self.many,
622
+ only=self.only,
623
+ exclude=self.exclude,
624
+ context=context,
625
+ load_only=self._nested_normalized_option("load_only"),
626
+ dump_only=self._nested_normalized_option("dump_only"),
627
+ )
628
+ return self._schema
629
+
630
+ def _nested_normalized_option(self, option_name: str) -> list[str]:
631
+ nested_field = f"{self.name}."
632
+ return [
633
+ field.split(nested_field, 1)[1]
634
+ for field in getattr(self.root, option_name, set())
635
+ if field.startswith(nested_field)
636
+ ]
637
+
638
+ def _serialize(self, nested_obj, attr, obj, **kwargs):
639
+ # Load up the schema first. This allows a RegistryError to be raised
640
+ # if an invalid schema name was passed
641
+ schema = self.schema
642
+ if nested_obj is None:
643
+ return None
644
+ many = schema.many or self.many
645
+ return schema.dump(nested_obj, many=many)
646
+
647
+ def _test_collection(self, value):
648
+ many = self.schema.many or self.many
649
+ if many and not utils.is_collection(value):
650
+ raise self.make_error("type", input=value, type=value.__class__.__name__)
651
+
652
+ def _load(self, value, data, partial=None):
653
+ try:
654
+ valid_data = self.schema.load(value, unknown=self.unknown, partial=partial)
655
+ except ValidationError as error:
656
+ raise ValidationError(
657
+ error.messages, valid_data=error.valid_data
658
+ ) from error
659
+ return valid_data
660
+
661
+ def _deserialize(self, value, attr, data, partial=None, **kwargs):
662
+ """Same as :meth:`Field._deserialize` with additional ``partial`` argument.
663
+
664
+ :param bool|tuple partial: For nested schemas, the ``partial``
665
+ parameter passed to `Schema.load`.
666
+
667
+ .. versionchanged:: 3.0.0
668
+ Add ``partial`` parameter.
669
+ """
670
+ self._test_collection(value)
671
+ return self._load(value, data, partial=partial)
672
+
673
+
674
+ class Pluck(Nested):
675
+ """Allows you to replace nested data with one of the data's fields.
676
+
677
+ Example: ::
678
+
679
+ from . import Schema, fields
680
+
681
+
682
+ class ArtistSchema(Schema):
683
+ id = fields.Int()
684
+ name = fields.Str()
685
+
686
+
687
+ class AlbumSchema(Schema):
688
+ artist = fields.Pluck(ArtistSchema, "id")
689
+
690
+
691
+ in_data = {"artist": 42}
692
+ loaded = AlbumSchema().load(in_data) # => {'artist': {'id': 42}}
693
+ dumped = AlbumSchema().dump(loaded) # => {'artist': 42}
694
+
695
+ :param Schema nested: The Schema class or class name (string)
696
+ to nest, or ``"self"`` to nest the :class:`Schema` within itself.
697
+ :param str field_name: The key to pluck a value from.
698
+ :param kwargs: The same keyword arguments that :class:`Nested` receives.
699
+ """
700
+
701
+ def __init__(
702
+ self,
703
+ nested: SchemaABC | type | str | typing.Callable[[], SchemaABC],
704
+ field_name: str,
705
+ **kwargs,
706
+ ):
707
+ super().__init__(nested, only=(field_name,), **kwargs)
708
+ self.field_name = field_name
709
+
710
+ @property
711
+ def _field_data_key(self):
712
+ only_field = self.schema.fields[self.field_name]
713
+ return only_field.data_key or self.field_name
714
+
715
+ def _serialize(self, nested_obj, attr, obj, **kwargs):
716
+ ret = super()._serialize(nested_obj, attr, obj, **kwargs)
717
+ if ret is None:
718
+ return None
719
+ if self.many:
720
+ return utils.pluck(ret, key=self._field_data_key)
721
+ return ret[self._field_data_key]
722
+
723
+ def _deserialize(self, value, attr, data, partial=None, **kwargs):
724
+ self._test_collection(value)
725
+ if self.many:
726
+ value = [{self._field_data_key: v} for v in value]
727
+ else:
728
+ value = {self._field_data_key: value}
729
+ return self._load(value, data, partial=partial)
730
+
731
+
732
+ class List(Field):
733
+ """A list field, composed with another `Field` class or
734
+ instance.
735
+
736
+ Example: ::
737
+
738
+ numbers = fields.List(fields.Float())
739
+
740
+ :param cls_or_instance: A field class or instance.
741
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
742
+
743
+ .. versionchanged:: 2.0.0
744
+ The ``allow_none`` parameter now applies to deserialization and
745
+ has the same semantics as the other fields.
746
+
747
+ .. versionchanged:: 3.0.0rc9
748
+ Does not serialize scalar values to single-item lists.
749
+ """
750
+
751
+ #: Default error messages.
752
+ default_error_messages = {"invalid": "Not a valid list."}
753
+
754
+ def __init__(self, cls_or_instance: Field | type, **kwargs):
755
+ super().__init__(**kwargs)
756
+ try:
757
+ self.inner = resolve_field_instance(cls_or_instance)
758
+ except FieldInstanceResolutionError as error:
759
+ raise ValueError(
760
+ "The list elements must be a subclass or instance of "
761
+ "marshmallow.base.FieldABC."
762
+ ) from error
763
+ if isinstance(self.inner, Nested):
764
+ self.only = self.inner.only
765
+ self.exclude = self.inner.exclude
766
+
767
+ def _bind_to_schema(self, field_name, schema):
768
+ super()._bind_to_schema(field_name, schema)
769
+ self.inner = copy.deepcopy(self.inner)
770
+ self.inner._bind_to_schema(field_name, self)
771
+ if isinstance(self.inner, Nested):
772
+ self.inner.only = self.only
773
+ self.inner.exclude = self.exclude
774
+
775
+ def _serialize(self, value, attr, obj, **kwargs) -> list[typing.Any] | None:
776
+ if value is None:
777
+ return None
778
+ return [self.inner._serialize(each, attr, obj, **kwargs) for each in value]
779
+
780
+ def _deserialize(self, value, attr, data, **kwargs) -> list[typing.Any]:
781
+ if not utils.is_collection(value):
782
+ raise self.make_error("invalid")
783
+
784
+ result = []
785
+ errors = {}
786
+ for idx, each in enumerate(value):
787
+ try:
788
+ result.append(self.inner.deserialize(each, **kwargs))
789
+ except ValidationError as error:
790
+ if error.valid_data is not None:
791
+ result.append(error.valid_data)
792
+ errors.update({idx: error.messages})
793
+ if errors:
794
+ raise ValidationError(errors, valid_data=result)
795
+ return result
796
+
797
+
798
+ class Tuple(Field):
799
+ """A tuple field, composed of a fixed number of other `Field` classes or
800
+ instances
801
+
802
+ Example: ::
803
+
804
+ row = Tuple((fields.String(), fields.Integer(), fields.Float()))
805
+
806
+ .. note::
807
+ Because of the structured nature of `collections.namedtuple` and
808
+ `typing.NamedTuple`, using a Schema within a Nested field for them is
809
+ more appropriate than using a `Tuple` field.
810
+
811
+ :param Iterable[Field] tuple_fields: An iterable of field classes or
812
+ instances.
813
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
814
+
815
+ .. versionadded:: 3.0.0rc4
816
+ """
817
+
818
+ #: Default error messages.
819
+ default_error_messages = {"invalid": "Not a valid tuple."}
820
+
821
+ def __init__(self, tuple_fields, *args, **kwargs):
822
+ super().__init__(*args, **kwargs)
823
+ if not utils.is_collection(tuple_fields):
824
+ raise ValueError(
825
+ "tuple_fields must be an iterable of Field classes or " "instances."
826
+ )
827
+
828
+ try:
829
+ self.tuple_fields = [
830
+ resolve_field_instance(cls_or_instance)
831
+ for cls_or_instance in tuple_fields
832
+ ]
833
+ except FieldInstanceResolutionError as error:
834
+ raise ValueError(
835
+ 'Elements of "tuple_fields" must be subclasses or '
836
+ "instances of marshmallow.base.FieldABC."
837
+ ) from error
838
+
839
+ self.validate_length = Length(equal=len(self.tuple_fields))
840
+
841
+ def _bind_to_schema(self, field_name, schema):
842
+ super()._bind_to_schema(field_name, schema)
843
+ new_tuple_fields = []
844
+ for field in self.tuple_fields:
845
+ field = copy.deepcopy(field)
846
+ field._bind_to_schema(field_name, self)
847
+ new_tuple_fields.append(field)
848
+
849
+ self.tuple_fields = new_tuple_fields
850
+
851
+ def _serialize(self, value, attr, obj, **kwargs) -> tuple | None:
852
+ if value is None:
853
+ return None
854
+
855
+ return tuple(
856
+ field._serialize(each, attr, obj, **kwargs)
857
+ for field, each in zip(self.tuple_fields, value)
858
+ )
859
+
860
+ def _deserialize(self, value, attr, data, **kwargs) -> tuple:
861
+ if not utils.is_collection(value):
862
+ raise self.make_error("invalid")
863
+
864
+ self.validate_length(value)
865
+
866
+ result = []
867
+ errors = {}
868
+
869
+ for idx, (field, each) in enumerate(zip(self.tuple_fields, value)):
870
+ try:
871
+ result.append(field.deserialize(each, **kwargs))
872
+ except ValidationError as error:
873
+ if error.valid_data is not None:
874
+ result.append(error.valid_data)
875
+ errors.update({idx: error.messages})
876
+ if errors:
877
+ raise ValidationError(errors, valid_data=result)
878
+
879
+ return tuple(result)
880
+
881
+
882
+ class String(Field):
883
+ """A string field.
884
+
885
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
886
+ """
887
+
888
+ #: Default error messages.
889
+ default_error_messages = {
890
+ "invalid": "Not a valid string.",
891
+ "invalid_utf8": "Not a valid utf-8 string.",
892
+ }
893
+
894
+ def _serialize(self, value, attr, obj, **kwargs) -> str | None:
895
+ if value is None:
896
+ return None
897
+ return utils.ensure_text_type(value)
898
+
899
+ def _deserialize(self, value, attr, data, **kwargs) -> typing.Any:
900
+ if not isinstance(value, (str, bytes)):
901
+ raise self.make_error("invalid")
902
+ try:
903
+ return utils.ensure_text_type(value)
904
+ except UnicodeDecodeError as error:
905
+ raise self.make_error("invalid_utf8") from error
906
+
907
+
908
+ class UUID(String):
909
+ """A UUID field."""
910
+
911
+ #: Default error messages.
912
+ default_error_messages = {"invalid_uuid": "Not a valid UUID."}
913
+
914
+ def _validated(self, value) -> uuid.UUID | None:
915
+ """Format the value or raise a :exc:`ValidationError` if an error occurs."""
916
+ if value is None:
917
+ return None
918
+ if isinstance(value, uuid.UUID):
919
+ return value
920
+ try:
921
+ if isinstance(value, bytes) and len(value) == 16:
922
+ return uuid.UUID(bytes=value)
923
+ return uuid.UUID(value)
924
+ except (ValueError, AttributeError, TypeError) as error:
925
+ raise self.make_error("invalid_uuid") from error
926
+
927
+ def _deserialize(self, value, attr, data, **kwargs) -> uuid.UUID | None:
928
+ return self._validated(value)
929
+
930
+
931
+ class Number(Field):
932
+ """Base class for number fields.
933
+
934
+ :param bool as_string: If `True`, format the serialized value as a string.
935
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
936
+ """
937
+
938
+ num_type = float # type: typing.Type
939
+
940
+ #: Default error messages.
941
+ default_error_messages = {
942
+ "invalid": "Not a valid number.",
943
+ "too_large": "Number too large.",
944
+ }
945
+
946
+ def __init__(self, *, as_string: bool = False, **kwargs):
947
+ self.as_string = as_string
948
+ super().__init__(**kwargs)
949
+
950
+ def _format_num(self, value) -> typing.Any:
951
+ """Return the number value for value, given this field's `num_type`."""
952
+ return self.num_type(value)
953
+
954
+ def _validated(self, value) -> _T | None:
955
+ """Format the value or raise a :exc:`ValidationError` if an error occurs."""
956
+ if value is None:
957
+ return None
958
+ # (value is True or value is False) is ~5x faster than isinstance(value, bool)
959
+ if value is True or value is False:
960
+ raise self.make_error("invalid", input=value)
961
+ try:
962
+ return self._format_num(value)
963
+ except (TypeError, ValueError) as error:
964
+ raise self.make_error("invalid", input=value) from error
965
+ except OverflowError as error:
966
+ raise self.make_error("too_large", input=value) from error
967
+
968
+ def _to_string(self, value) -> str:
969
+ return str(value)
970
+
971
+ def _serialize(self, value, attr, obj, **kwargs) -> str | _T | None:
972
+ """Return a string if `self.as_string=True`, otherwise return this field's `num_type`."""
973
+ if value is None:
974
+ return None
975
+ ret = self._format_num(value) # type: _T
976
+ return self._to_string(ret) if self.as_string else ret
977
+
978
+ def _deserialize(self, value, attr, data, **kwargs) -> _T | None:
979
+ return self._validated(value)
980
+
981
+
982
+ class Integer(Number):
983
+ """An integer field.
984
+
985
+ :param strict: If `True`, only integer types are valid.
986
+ Otherwise, any value castable to `int` is valid.
987
+ :param kwargs: The same keyword arguments that :class:`Number` receives.
988
+ """
989
+
990
+ num_type = int
991
+
992
+ #: Default error messages.
993
+ default_error_messages = {"invalid": "Not a valid integer."}
994
+
995
+ def __init__(self, *, strict: bool = False, **kwargs):
996
+ self.strict = strict
997
+ super().__init__(**kwargs)
998
+
999
+ # override Number
1000
+ def _validated(self, value):
1001
+ if self.strict and not isinstance(value, numbers.Integral):
1002
+ raise self.make_error("invalid", input=value)
1003
+ return super()._validated(value)
1004
+
1005
+
1006
+ class Float(Number):
1007
+ """A double as an IEEE-754 double precision string.
1008
+
1009
+ :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,
1010
+ even though they are illegal according to the JSON specification.
1011
+ :param bool as_string: If `True`, format the value as a string.
1012
+ :param kwargs: The same keyword arguments that :class:`Number` receives.
1013
+ """
1014
+
1015
+ num_type = float
1016
+
1017
+ #: Default error messages.
1018
+ default_error_messages = {
1019
+ "special": "Special numeric values (nan or infinity) are not permitted."
1020
+ }
1021
+
1022
+ def __init__(self, *, allow_nan: bool = False, as_string: bool = False, **kwargs):
1023
+ self.allow_nan = allow_nan
1024
+ super().__init__(as_string=as_string, **kwargs)
1025
+
1026
+ def _validated(self, value):
1027
+ num = super()._validated(value)
1028
+ if self.allow_nan is False:
1029
+ if math.isnan(num) or num == float("inf") or num == float("-inf"):
1030
+ raise self.make_error("special")
1031
+ return num
1032
+
1033
+
1034
+ class Decimal(Number):
1035
+ """A field that (de)serializes to the Python ``decimal.Decimal`` type.
1036
+ It's safe to use when dealing with money values, percentages, ratios
1037
+ or other numbers where precision is critical.
1038
+
1039
+ .. warning::
1040
+
1041
+ This field serializes to a `decimal.Decimal` object by default. If you need
1042
+ to render your data as JSON, keep in mind that the `json` module from the
1043
+ standard library does not encode `decimal.Decimal`. Therefore, you must use
1044
+ a JSON library that can handle decimals, such as `simplejson`, or serialize
1045
+ to a string by passing ``as_string=True``.
1046
+
1047
+ .. warning::
1048
+
1049
+ If a JSON `float` value is passed to this field for deserialization it will
1050
+ first be cast to its corresponding `string` value before being deserialized
1051
+ to a `decimal.Decimal` object. The default `__str__` implementation of the
1052
+ built-in Python `float` type may apply a destructive transformation upon
1053
+ its input data and therefore cannot be relied upon to preserve precision.
1054
+ To avoid this, you can instead pass a JSON `string` to be deserialized
1055
+ directly.
1056
+
1057
+ :param places: How many decimal places to quantize the value. If `None`, does
1058
+ not quantize the value.
1059
+ :param rounding: How to round the value during quantize, for example
1060
+ `decimal.ROUND_UP`. If `None`, uses the rounding value from
1061
+ the current thread's context.
1062
+ :param allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed,
1063
+ even though they are illegal according to the JSON specification.
1064
+ :param as_string: If `True`, serialize to a string instead of a Python
1065
+ `decimal.Decimal` type.
1066
+ :param kwargs: The same keyword arguments that :class:`Number` receives.
1067
+
1068
+ .. versionadded:: 1.2.0
1069
+ """
1070
+
1071
+ num_type = decimal.Decimal
1072
+
1073
+ #: Default error messages.
1074
+ default_error_messages = {
1075
+ "special": "Special numeric values (nan or infinity) are not permitted."
1076
+ }
1077
+
1078
+ def __init__(
1079
+ self,
1080
+ places: int | None = None,
1081
+ rounding: str | None = None,
1082
+ *,
1083
+ allow_nan: bool = False,
1084
+ as_string: bool = False,
1085
+ **kwargs,
1086
+ ):
1087
+ self.places = (
1088
+ decimal.Decimal((0, (1,), -places)) if places is not None else None
1089
+ )
1090
+ self.rounding = rounding
1091
+ self.allow_nan = allow_nan
1092
+ super().__init__(as_string=as_string, **kwargs)
1093
+
1094
+ # override Number
1095
+ def _format_num(self, value):
1096
+ num = decimal.Decimal(str(value))
1097
+ if self.allow_nan:
1098
+ if num.is_nan():
1099
+ return decimal.Decimal("NaN") # avoid sNaN, -sNaN and -NaN
1100
+ if self.places is not None and num.is_finite():
1101
+ num = num.quantize(self.places, rounding=self.rounding)
1102
+ return num
1103
+
1104
+ # override Number
1105
+ def _validated(self, value):
1106
+ try:
1107
+ num = super()._validated(value)
1108
+ except decimal.InvalidOperation as error:
1109
+ raise self.make_error("invalid") from error
1110
+ if not self.allow_nan and (num.is_nan() or num.is_infinite()):
1111
+ raise self.make_error("special")
1112
+ return num
1113
+
1114
+ # override Number
1115
+ def _to_string(self, value):
1116
+ return format(value, "f")
1117
+
1118
+
1119
+ class Boolean(Field):
1120
+ """A boolean field.
1121
+
1122
+ :param truthy: Values that will (de)serialize to `True`. If an empty
1123
+ set, any non-falsy value will deserialize to `True`. If `None`,
1124
+ `marshmallow.fields.Boolean.truthy` will be used.
1125
+ :param falsy: Values that will (de)serialize to `False`. If `None`,
1126
+ `marshmallow.fields.Boolean.falsy` will be used.
1127
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
1128
+ """
1129
+
1130
+ #: Default truthy values.
1131
+ truthy = {
1132
+ "t",
1133
+ "T",
1134
+ "true",
1135
+ "True",
1136
+ "TRUE",
1137
+ "on",
1138
+ "On",
1139
+ "ON",
1140
+ "y",
1141
+ "Y",
1142
+ "yes",
1143
+ "Yes",
1144
+ "YES",
1145
+ "1",
1146
+ 1,
1147
+ # Equal to 1
1148
+ # True,
1149
+ }
1150
+ #: Default falsy values.
1151
+ falsy = {
1152
+ "f",
1153
+ "F",
1154
+ "false",
1155
+ "False",
1156
+ "FALSE",
1157
+ "off",
1158
+ "Off",
1159
+ "OFF",
1160
+ "n",
1161
+ "N",
1162
+ "no",
1163
+ "No",
1164
+ "NO",
1165
+ "0",
1166
+ 0,
1167
+ # Equal to 0
1168
+ # 0.0,
1169
+ # False,
1170
+ }
1171
+
1172
+ #: Default error messages.
1173
+ default_error_messages = {"invalid": "Not a valid boolean."}
1174
+
1175
+ def __init__(
1176
+ self,
1177
+ *,
1178
+ truthy: set | None = None,
1179
+ falsy: set | None = None,
1180
+ **kwargs,
1181
+ ):
1182
+ super().__init__(**kwargs)
1183
+
1184
+ if truthy is not None:
1185
+ self.truthy = set(truthy)
1186
+ if falsy is not None:
1187
+ self.falsy = set(falsy)
1188
+
1189
+ def _serialize(self, value, attr, obj, **kwargs):
1190
+ if value is None:
1191
+ return None
1192
+
1193
+ try:
1194
+ if value in self.truthy:
1195
+ return True
1196
+ if value in self.falsy:
1197
+ return False
1198
+ except TypeError:
1199
+ pass
1200
+
1201
+ return bool(value)
1202
+
1203
+ def _deserialize(self, value, attr, data, **kwargs):
1204
+ if not self.truthy:
1205
+ return bool(value)
1206
+ try:
1207
+ if value in self.truthy:
1208
+ return True
1209
+ if value in self.falsy:
1210
+ return False
1211
+ except TypeError as error:
1212
+ raise self.make_error("invalid", input=value) from error
1213
+ raise self.make_error("invalid", input=value)
1214
+
1215
+
1216
+ class DateTime(Field):
1217
+ """A formatted datetime string.
1218
+
1219
+ Example: ``'2014-12-22T03:12:58.019077+00:00'``
1220
+
1221
+ :param format: Either ``"rfc"`` (for RFC822), ``"iso"`` (for ISO8601),
1222
+ ``"timestamp"``, ``"timestamp_ms"`` (for a POSIX timestamp) or a date format string.
1223
+ If `None`, defaults to "iso".
1224
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
1225
+
1226
+ .. versionchanged:: 3.0.0rc9
1227
+ Does not modify timezone information on (de)serialization.
1228
+ .. versionchanged:: 3.19
1229
+ Add timestamp as a format.
1230
+ """
1231
+
1232
+ SERIALIZATION_FUNCS = {
1233
+ "iso": utils.isoformat,
1234
+ "iso8601": utils.isoformat,
1235
+ "rfc": utils.rfcformat,
1236
+ "rfc822": utils.rfcformat,
1237
+ "timestamp": utils.timestamp,
1238
+ "timestamp_ms": utils.timestamp_ms,
1239
+ } # type: typing.Dict[str, typing.Callable[[typing.Any], str | float]]
1240
+
1241
+ DESERIALIZATION_FUNCS = {
1242
+ "iso": utils.from_iso_datetime,
1243
+ "iso8601": utils.from_iso_datetime,
1244
+ "rfc": utils.from_rfc,
1245
+ "rfc822": utils.from_rfc,
1246
+ "timestamp": utils.from_timestamp,
1247
+ "timestamp_ms": utils.from_timestamp_ms,
1248
+ } # type: typing.Dict[str, typing.Callable[[str], typing.Any]]
1249
+
1250
+ DEFAULT_FORMAT = "iso"
1251
+
1252
+ OBJ_TYPE = "datetime"
1253
+
1254
+ SCHEMA_OPTS_VAR_NAME = "datetimeformat"
1255
+
1256
+ #: Default error messages.
1257
+ default_error_messages = {
1258
+ "invalid": "Not a valid {obj_type}.",
1259
+ "invalid_awareness": "Not a valid {awareness} {obj_type}.",
1260
+ "format": '"{input}" cannot be formatted as a {obj_type}.',
1261
+ }
1262
+
1263
+ def __init__(self, format: str | None = None, **kwargs) -> None:
1264
+ super().__init__(**kwargs)
1265
+ # Allow this to be None. It may be set later in the ``_serialize``
1266
+ # or ``_deserialize`` methods. This allows a Schema to dynamically set the
1267
+ # format, e.g. from a Meta option
1268
+ self.format = format
1269
+
1270
+ def _bind_to_schema(self, field_name, schema):
1271
+ super()._bind_to_schema(field_name, schema)
1272
+ self.format = (
1273
+ self.format
1274
+ or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)
1275
+ or self.DEFAULT_FORMAT
1276
+ )
1277
+
1278
+ def _serialize(self, value, attr, obj, **kwargs) -> str | float | None:
1279
+ if value is None:
1280
+ return None
1281
+ data_format = self.format or self.DEFAULT_FORMAT
1282
+ format_func = self.SERIALIZATION_FUNCS.get(data_format)
1283
+ if format_func:
1284
+ return format_func(value)
1285
+ return value.strftime(data_format)
1286
+
1287
+ def _deserialize(self, value, attr, data, **kwargs) -> dt.datetime:
1288
+ data_format = self.format or self.DEFAULT_FORMAT
1289
+ func = self.DESERIALIZATION_FUNCS.get(data_format)
1290
+ try:
1291
+ if func:
1292
+ return func(value)
1293
+ return self._make_object_from_format(value, data_format)
1294
+ except (TypeError, AttributeError, ValueError) as error:
1295
+ raise self.make_error(
1296
+ "invalid", input=value, obj_type=self.OBJ_TYPE
1297
+ ) from error
1298
+
1299
+ @staticmethod
1300
+ def _make_object_from_format(value, data_format) -> dt.datetime:
1301
+ return dt.datetime.strptime(value, data_format)
1302
+
1303
+
1304
+ class NaiveDateTime(DateTime):
1305
+ """A formatted naive datetime string.
1306
+
1307
+ :param format: See :class:`DateTime`.
1308
+ :param timezone: Used on deserialization. If `None`,
1309
+ aware datetimes are rejected. If not `None`, aware datetimes are
1310
+ converted to this timezone before their timezone information is
1311
+ removed.
1312
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
1313
+
1314
+ .. versionadded:: 3.0.0rc9
1315
+ """
1316
+
1317
+ AWARENESS = "naive"
1318
+
1319
+ def __init__(
1320
+ self,
1321
+ format: str | None = None,
1322
+ *,
1323
+ timezone: dt.timezone | None = None,
1324
+ **kwargs,
1325
+ ) -> None:
1326
+ super().__init__(format=format, **kwargs)
1327
+ self.timezone = timezone
1328
+
1329
+ def _deserialize(self, value, attr, data, **kwargs) -> dt.datetime:
1330
+ ret = super()._deserialize(value, attr, data, **kwargs)
1331
+ if is_aware(ret):
1332
+ if self.timezone is None:
1333
+ raise self.make_error(
1334
+ "invalid_awareness",
1335
+ awareness=self.AWARENESS,
1336
+ obj_type=self.OBJ_TYPE,
1337
+ )
1338
+ ret = ret.astimezone(self.timezone).replace(tzinfo=None)
1339
+ return ret
1340
+
1341
+
1342
+ class AwareDateTime(DateTime):
1343
+ """A formatted aware datetime string.
1344
+
1345
+ :param format: See :class:`DateTime`.
1346
+ :param default_timezone: Used on deserialization. If `None`, naive
1347
+ datetimes are rejected. If not `None`, naive datetimes are set this
1348
+ timezone.
1349
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
1350
+
1351
+ .. versionadded:: 3.0.0rc9
1352
+ """
1353
+
1354
+ AWARENESS = "aware"
1355
+
1356
+ def __init__(
1357
+ self,
1358
+ format: str | None = None,
1359
+ *,
1360
+ default_timezone: dt.tzinfo | None = None,
1361
+ **kwargs,
1362
+ ) -> None:
1363
+ super().__init__(format=format, **kwargs)
1364
+ self.default_timezone = default_timezone
1365
+
1366
+ def _deserialize(self, value, attr, data, **kwargs) -> dt.datetime:
1367
+ ret = super()._deserialize(value, attr, data, **kwargs)
1368
+ if not is_aware(ret):
1369
+ if self.default_timezone is None:
1370
+ raise self.make_error(
1371
+ "invalid_awareness",
1372
+ awareness=self.AWARENESS,
1373
+ obj_type=self.OBJ_TYPE,
1374
+ )
1375
+ ret = ret.replace(tzinfo=self.default_timezone)
1376
+ return ret
1377
+
1378
+
1379
+ class Time(DateTime):
1380
+ """A formatted time string.
1381
+
1382
+ Example: ``'03:12:58.019077'``
1383
+
1384
+ :param format: Either ``"iso"`` (for ISO8601) or a date format string.
1385
+ If `None`, defaults to "iso".
1386
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
1387
+ """
1388
+
1389
+ SERIALIZATION_FUNCS = {"iso": utils.to_iso_time, "iso8601": utils.to_iso_time}
1390
+
1391
+ DESERIALIZATION_FUNCS = {"iso": utils.from_iso_time, "iso8601": utils.from_iso_time}
1392
+
1393
+ DEFAULT_FORMAT = "iso"
1394
+
1395
+ OBJ_TYPE = "time"
1396
+
1397
+ SCHEMA_OPTS_VAR_NAME = "timeformat"
1398
+
1399
+ @staticmethod
1400
+ def _make_object_from_format(value, data_format):
1401
+ return dt.datetime.strptime(value, data_format).time()
1402
+
1403
+
1404
+ class Date(DateTime):
1405
+ """ISO8601-formatted date string.
1406
+
1407
+ :param format: Either ``"iso"`` (for ISO8601) or a date format string.
1408
+ If `None`, defaults to "iso".
1409
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
1410
+ """
1411
+
1412
+ #: Default error messages.
1413
+ default_error_messages = {
1414
+ "invalid": "Not a valid date.",
1415
+ "format": '"{input}" cannot be formatted as a date.',
1416
+ }
1417
+
1418
+ SERIALIZATION_FUNCS = {"iso": utils.to_iso_date, "iso8601": utils.to_iso_date}
1419
+
1420
+ DESERIALIZATION_FUNCS = {"iso": utils.from_iso_date, "iso8601": utils.from_iso_date}
1421
+
1422
+ DEFAULT_FORMAT = "iso"
1423
+
1424
+ OBJ_TYPE = "date"
1425
+
1426
+ SCHEMA_OPTS_VAR_NAME = "dateformat"
1427
+
1428
+ @staticmethod
1429
+ def _make_object_from_format(value, data_format):
1430
+ return dt.datetime.strptime(value, data_format).date()
1431
+
1432
+
1433
+ class TimeDelta(Field):
1434
+ """A field that (de)serializes a :class:`datetime.timedelta` object to an
1435
+ integer or float and vice versa. The integer or float can represent the
1436
+ number of days, seconds or microseconds.
1437
+
1438
+ :param precision: Influences how the integer or float is interpreted during
1439
+ (de)serialization. Must be 'days', 'seconds', 'microseconds',
1440
+ 'milliseconds', 'minutes', 'hours' or 'weeks'.
1441
+ :param serialization_type: Whether to (de)serialize to a `int` or `float`.
1442
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
1443
+
1444
+ Integer Caveats
1445
+ ---------------
1446
+ Any fractional parts (which depends on the precision used) will be truncated
1447
+ when serializing using `int`.
1448
+
1449
+ Float Caveats
1450
+ -------------
1451
+ Use of `float` when (de)serializing may result in data precision loss due
1452
+ to the way machines handle floating point values.
1453
+
1454
+ Regardless of the precision chosen, the fractional part when using `float`
1455
+ will always be truncated to microseconds.
1456
+ For example, `1.12345` interpreted as microseconds will result in `timedelta(microseconds=1)`.
1457
+
1458
+ .. versionchanged:: 2.0.0
1459
+ Always serializes to an integer value to avoid rounding errors.
1460
+ Add `precision` parameter.
1461
+ .. versionchanged:: 3.17.0
1462
+ Allow (de)serialization to `float` through use of a new `serialization_type` parameter.
1463
+ `int` is the default to retain previous behaviour.
1464
+ """
1465
+
1466
+ DAYS = "days"
1467
+ SECONDS = "seconds"
1468
+ MICROSECONDS = "microseconds"
1469
+ MILLISECONDS = "milliseconds"
1470
+ MINUTES = "minutes"
1471
+ HOURS = "hours"
1472
+ WEEKS = "weeks"
1473
+
1474
+ #: Default error messages.
1475
+ default_error_messages = {
1476
+ "invalid": "Not a valid period of time.",
1477
+ "format": "{input!r} cannot be formatted as a timedelta.",
1478
+ }
1479
+
1480
+ def __init__(
1481
+ self,
1482
+ precision: str = SECONDS,
1483
+ serialization_type: type[int | float] = int,
1484
+ **kwargs,
1485
+ ):
1486
+ precision = precision.lower()
1487
+ units = (
1488
+ self.DAYS,
1489
+ self.SECONDS,
1490
+ self.MICROSECONDS,
1491
+ self.MILLISECONDS,
1492
+ self.MINUTES,
1493
+ self.HOURS,
1494
+ self.WEEKS,
1495
+ )
1496
+
1497
+ if precision not in units:
1498
+ msg = 'The precision must be {} or "{}".'.format(
1499
+ ", ".join([f'"{each}"' for each in units[:-1]]), units[-1]
1500
+ )
1501
+ raise ValueError(msg)
1502
+
1503
+ if serialization_type not in (int, float):
1504
+ raise ValueError("The serialization type must be one of int or float")
1505
+
1506
+ self.precision = precision
1507
+ self.serialization_type = serialization_type
1508
+ super().__init__(**kwargs)
1509
+
1510
+ def _serialize(self, value, attr, obj, **kwargs):
1511
+ if value is None:
1512
+ return None
1513
+
1514
+ base_unit = dt.timedelta(**{self.precision: 1})
1515
+
1516
+ if self.serialization_type is int:
1517
+ delta = utils.timedelta_to_microseconds(value)
1518
+ unit = utils.timedelta_to_microseconds(base_unit)
1519
+ return delta // unit
1520
+ assert self.serialization_type is float
1521
+ return value.total_seconds() / base_unit.total_seconds()
1522
+
1523
+ def _deserialize(self, value, attr, data, **kwargs):
1524
+ try:
1525
+ value = self.serialization_type(value)
1526
+ except (TypeError, ValueError) as error:
1527
+ raise self.make_error("invalid") from error
1528
+
1529
+ kwargs = {self.precision: value}
1530
+
1531
+ try:
1532
+ return dt.timedelta(**kwargs)
1533
+ except OverflowError as error:
1534
+ raise self.make_error("invalid") from error
1535
+
1536
+
1537
+ class Mapping(Field):
1538
+ """An abstract class for objects with key-value pairs.
1539
+
1540
+ :param keys: A field class or instance for dict keys.
1541
+ :param values: A field class or instance for dict values.
1542
+ :param kwargs: The same keyword arguments that :class:`Field` receives.
1543
+
1544
+ .. note::
1545
+ When the structure of nested data is not known, you may omit the
1546
+ `keys` and `values` arguments to prevent content validation.
1547
+
1548
+ .. versionadded:: 3.0.0rc4
1549
+ """
1550
+
1551
+ mapping_type = dict
1552
+
1553
+ #: Default error messages.
1554
+ default_error_messages = {"invalid": "Not a valid mapping type."}
1555
+
1556
+ def __init__(
1557
+ self,
1558
+ keys: Field | type | None = None,
1559
+ values: Field | type | None = None,
1560
+ **kwargs,
1561
+ ):
1562
+ super().__init__(**kwargs)
1563
+ if keys is None:
1564
+ self.key_field = None
1565
+ else:
1566
+ try:
1567
+ self.key_field = resolve_field_instance(keys)
1568
+ except FieldInstanceResolutionError as error:
1569
+ raise ValueError(
1570
+ '"keys" must be a subclass or instance of '
1571
+ "marshmallow.base.FieldABC."
1572
+ ) from error
1573
+
1574
+ if values is None:
1575
+ self.value_field = None
1576
+ else:
1577
+ try:
1578
+ self.value_field = resolve_field_instance(values)
1579
+ except FieldInstanceResolutionError as error:
1580
+ raise ValueError(
1581
+ '"values" must be a subclass or instance of '
1582
+ "marshmallow.base.FieldABC."
1583
+ ) from error
1584
+ if isinstance(self.value_field, Nested):
1585
+ self.only = self.value_field.only
1586
+ self.exclude = self.value_field.exclude
1587
+
1588
+ def _bind_to_schema(self, field_name, schema):
1589
+ super()._bind_to_schema(field_name, schema)
1590
+ if self.value_field:
1591
+ self.value_field = copy.deepcopy(self.value_field)
1592
+ self.value_field._bind_to_schema(field_name, self)
1593
+ if isinstance(self.value_field, Nested):
1594
+ self.value_field.only = self.only
1595
+ self.value_field.exclude = self.exclude
1596
+ if self.key_field:
1597
+ self.key_field = copy.deepcopy(self.key_field)
1598
+ self.key_field._bind_to_schema(field_name, self)
1599
+
1600
+ def _serialize(self, value, attr, obj, **kwargs):
1601
+ if value is None:
1602
+ return None
1603
+ if not self.value_field and not self.key_field:
1604
+ return self.mapping_type(value)
1605
+
1606
+ #  Serialize keys
1607
+ if self.key_field is None:
1608
+ keys = {k: k for k in value.keys()}
1609
+ else:
1610
+ keys = {
1611
+ k: self.key_field._serialize(k, None, None, **kwargs)
1612
+ for k in value.keys()
1613
+ }
1614
+
1615
+ #  Serialize values
1616
+ result = self.mapping_type()
1617
+ if self.value_field is None:
1618
+ for k, v in value.items():
1619
+ if k in keys:
1620
+ result[keys[k]] = v
1621
+ else:
1622
+ for k, v in value.items():
1623
+ result[keys[k]] = self.value_field._serialize(v, None, None, **kwargs)
1624
+
1625
+ return result
1626
+
1627
+ def _deserialize(self, value, attr, data, **kwargs):
1628
+ if not isinstance(value, _Mapping):
1629
+ raise self.make_error("invalid")
1630
+ if not self.value_field and not self.key_field:
1631
+ return self.mapping_type(value)
1632
+
1633
+ errors = collections.defaultdict(dict)
1634
+
1635
+ #  Deserialize keys
1636
+ if self.key_field is None:
1637
+ keys = {k: k for k in value.keys()}
1638
+ else:
1639
+ keys = {}
1640
+ for key in value.keys():
1641
+ try:
1642
+ keys[key] = self.key_field.deserialize(key, **kwargs)
1643
+ except ValidationError as error:
1644
+ errors[key]["key"] = error.messages
1645
+
1646
+ #  Deserialize values
1647
+ result = self.mapping_type()
1648
+ if self.value_field is None:
1649
+ for k, v in value.items():
1650
+ if k in keys:
1651
+ result[keys[k]] = v
1652
+ else:
1653
+ for key, val in value.items():
1654
+ try:
1655
+ deser_val = self.value_field.deserialize(val, **kwargs)
1656
+ except ValidationError as error:
1657
+ errors[key]["value"] = error.messages
1658
+ if error.valid_data is not None and key in keys:
1659
+ result[keys[key]] = error.valid_data
1660
+ else:
1661
+ if key in keys:
1662
+ result[keys[key]] = deser_val
1663
+
1664
+ if errors:
1665
+ raise ValidationError(errors, valid_data=result)
1666
+
1667
+ return result
1668
+
1669
+
1670
+ class Dict(Mapping):
1671
+ """A dict field. Supports dicts and dict-like objects. Extends
1672
+ Mapping with dict as the mapping_type.
1673
+
1674
+ Example: ::
1675
+
1676
+ numbers = fields.Dict(keys=fields.Str(), values=fields.Float())
1677
+
1678
+ :param kwargs: The same keyword arguments that :class:`Mapping` receives.
1679
+
1680
+ .. versionadded:: 2.1.0
1681
+ """
1682
+
1683
+ mapping_type = dict
1684
+
1685
+
1686
+ class Url(String):
1687
+ """An URL field.
1688
+
1689
+ :param default: Default value for the field if the attribute is not set.
1690
+ :param relative: Whether to allow relative URLs.
1691
+ :param require_tld: Whether to reject non-FQDN hostnames.
1692
+ :param schemes: Valid schemes. By default, ``http``, ``https``,
1693
+ ``ftp``, and ``ftps`` are allowed.
1694
+ :param kwargs: The same keyword arguments that :class:`String` receives.
1695
+ """
1696
+
1697
+ #: Default error messages.
1698
+ default_error_messages = {"invalid": "Not a valid URL."}
1699
+
1700
+ def __init__(
1701
+ self,
1702
+ *,
1703
+ relative: bool = False,
1704
+ absolute: bool = True,
1705
+ schemes: types.StrSequenceOrSet | None = None,
1706
+ require_tld: bool = True,
1707
+ **kwargs,
1708
+ ):
1709
+ super().__init__(**kwargs)
1710
+
1711
+ self.relative = relative
1712
+ self.absolute = absolute
1713
+ self.require_tld = require_tld
1714
+ # Insert validation into self.validators so that multiple errors can be stored.
1715
+ validator = validate.URL(
1716
+ relative=self.relative,
1717
+ absolute=self.absolute,
1718
+ schemes=schemes,
1719
+ require_tld=self.require_tld,
1720
+ error=self.error_messages["invalid"],
1721
+ )
1722
+ self.validators.insert(0, validator)
1723
+
1724
+
1725
+ class Email(String):
1726
+ """An email field.
1727
+
1728
+ :param args: The same positional arguments that :class:`String` receives.
1729
+ :param kwargs: The same keyword arguments that :class:`String` receives.
1730
+ """
1731
+
1732
+ #: Default error messages.
1733
+ default_error_messages = {"invalid": "Not a valid email address."}
1734
+
1735
+ def __init__(self, *args, **kwargs) -> None:
1736
+ super().__init__(*args, **kwargs)
1737
+ # Insert validation into self.validators so that multiple errors can be stored.
1738
+ validator = validate.Email(error=self.error_messages["invalid"])
1739
+ self.validators.insert(0, validator)
1740
+
1741
+
1742
+ class IP(Field):
1743
+ """A IP address field.
1744
+
1745
+ :param bool exploded: If `True`, serialize ipv6 address in long form, ie. with groups
1746
+ consisting entirely of zeros included.
1747
+
1748
+ .. versionadded:: 3.8.0
1749
+ """
1750
+
1751
+ default_error_messages = {"invalid_ip": "Not a valid IP address."}
1752
+
1753
+ DESERIALIZATION_CLASS = None # type: typing.Optional[typing.Type]
1754
+
1755
+ def __init__(self, *args, exploded=False, **kwargs):
1756
+ super().__init__(*args, **kwargs)
1757
+ self.exploded = exploded
1758
+
1759
+ def _serialize(self, value, attr, obj, **kwargs) -> str | None:
1760
+ if value is None:
1761
+ return None
1762
+ if self.exploded:
1763
+ return value.exploded
1764
+ return value.compressed
1765
+
1766
+ def _deserialize(
1767
+ self, value, attr, data, **kwargs
1768
+ ) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
1769
+ if value is None:
1770
+ return None
1771
+ try:
1772
+ return (self.DESERIALIZATION_CLASS or ipaddress.ip_address)(
1773
+ utils.ensure_text_type(value)
1774
+ )
1775
+ except (ValueError, TypeError) as error:
1776
+ raise self.make_error("invalid_ip") from error
1777
+
1778
+
1779
+ class IPv4(IP):
1780
+ """A IPv4 address field.
1781
+
1782
+ .. versionadded:: 3.8.0
1783
+ """
1784
+
1785
+ default_error_messages = {"invalid_ip": "Not a valid IPv4 address."}
1786
+
1787
+ DESERIALIZATION_CLASS = ipaddress.IPv4Address
1788
+
1789
+
1790
+ class IPv6(IP):
1791
+ """A IPv6 address field.
1792
+
1793
+ .. versionadded:: 3.8.0
1794
+ """
1795
+
1796
+ default_error_messages = {"invalid_ip": "Not a valid IPv6 address."}
1797
+
1798
+ DESERIALIZATION_CLASS = ipaddress.IPv6Address
1799
+
1800
+
1801
+ class IPInterface(Field):
1802
+ """A IPInterface field.
1803
+
1804
+ IP interface is the non-strict form of the IPNetwork type where arbitrary host
1805
+ addresses are always accepted.
1806
+
1807
+ IPAddress and mask e.g. '192.168.0.2/24' or '192.168.0.2/255.255.255.0'
1808
+
1809
+ see https://python.readthedocs.io/en/latest/library/ipaddress.html#interface-objects
1810
+
1811
+ :param bool exploded: If `True`, serialize ipv6 interface in long form, ie. with groups
1812
+ consisting entirely of zeros included.
1813
+ """
1814
+
1815
+ default_error_messages = {"invalid_ip_interface": "Not a valid IP interface."}
1816
+
1817
+ DESERIALIZATION_CLASS = None # type: typing.Optional[typing.Type]
1818
+
1819
+ def __init__(self, *args, exploded: bool = False, **kwargs):
1820
+ super().__init__(*args, **kwargs)
1821
+ self.exploded = exploded
1822
+
1823
+ def _serialize(self, value, attr, obj, **kwargs) -> str | None:
1824
+ if value is None:
1825
+ return None
1826
+ if self.exploded:
1827
+ return value.exploded
1828
+ return value.compressed
1829
+
1830
+ def _deserialize(self, value, attr, data, **kwargs) -> None | (
1831
+ ipaddress.IPv4Interface | ipaddress.IPv6Interface
1832
+ ):
1833
+ if value is None:
1834
+ return None
1835
+ try:
1836
+ return (self.DESERIALIZATION_CLASS or ipaddress.ip_interface)(
1837
+ utils.ensure_text_type(value)
1838
+ )
1839
+ except (ValueError, TypeError) as error:
1840
+ raise self.make_error("invalid_ip_interface") from error
1841
+
1842
+
1843
+ class IPv4Interface(IPInterface):
1844
+ """A IPv4 Network Interface field."""
1845
+
1846
+ default_error_messages = {"invalid_ip_interface": "Not a valid IPv4 interface."}
1847
+
1848
+ DESERIALIZATION_CLASS = ipaddress.IPv4Interface
1849
+
1850
+
1851
+ class IPv6Interface(IPInterface):
1852
+ """A IPv6 Network Interface field."""
1853
+
1854
+ default_error_messages = {"invalid_ip_interface": "Not a valid IPv6 interface."}
1855
+
1856
+ DESERIALIZATION_CLASS = ipaddress.IPv6Interface
1857
+
1858
+
1859
+ class Enum(Field):
1860
+ """An Enum field (de)serializing enum members by symbol (name) or by value.
1861
+
1862
+ :param enum Enum: Enum class
1863
+ :param boolean|Schema|Field by_value: Whether to (de)serialize by value or by name,
1864
+ or Field class or instance to use to (de)serialize by value. Defaults to False.
1865
+
1866
+ If `by_value` is `False` (default), enum members are (de)serialized by symbol (name).
1867
+ If it is `True`, they are (de)serialized by value using :class:`Field`.
1868
+ If it is a field instance or class, they are (de)serialized by value using this field.
1869
+
1870
+ .. versionadded:: 3.18.0
1871
+ """
1872
+
1873
+ default_error_messages = {
1874
+ "unknown": "Must be one of: {choices}.",
1875
+ }
1876
+
1877
+ def __init__(
1878
+ self,
1879
+ enum: type[EnumType],
1880
+ *,
1881
+ by_value: bool | Field | type = False,
1882
+ **kwargs,
1883
+ ):
1884
+ super().__init__(**kwargs)
1885
+ self.enum = enum
1886
+ self.by_value = by_value
1887
+
1888
+ # Serialization by name
1889
+ if by_value is False:
1890
+ self.field: Field = String()
1891
+ self.choices_text = ", ".join(
1892
+ str(self.field._serialize(m, None, None)) for m in enum.__members__
1893
+ )
1894
+ # Serialization by value
1895
+ else:
1896
+ if by_value is True:
1897
+ self.field = Field()
1898
+ else:
1899
+ try:
1900
+ self.field = resolve_field_instance(by_value)
1901
+ except FieldInstanceResolutionError as error:
1902
+ raise ValueError(
1903
+ '"by_value" must be either a bool or a subclass or instance of '
1904
+ "marshmallow.base.FieldABC."
1905
+ ) from error
1906
+ self.choices_text = ", ".join(
1907
+ str(self.field._serialize(m.value, None, None)) for m in enum
1908
+ )
1909
+
1910
+ def _serialize(self, value, attr, obj, **kwargs):
1911
+ if value is None:
1912
+ return None
1913
+ if self.by_value:
1914
+ val = value.value
1915
+ else:
1916
+ val = value.name
1917
+ return self.field._serialize(val, attr, obj, **kwargs)
1918
+
1919
+ def _deserialize(self, value, attr, data, **kwargs):
1920
+ val = self.field._deserialize(value, attr, data, **kwargs)
1921
+ if self.by_value:
1922
+ try:
1923
+ return self.enum(val)
1924
+ except ValueError as error:
1925
+ raise self.make_error("unknown", choices=self.choices_text) from error
1926
+ try:
1927
+ return getattr(self.enum, val)
1928
+ except AttributeError as error:
1929
+ raise self.make_error("unknown", choices=self.choices_text) from error
1930
+
1931
+
1932
+ class Method(Field):
1933
+ """A field that takes the value returned by a `Schema` method.
1934
+
1935
+ :param str serialize: The name of the Schema method from which
1936
+ to retrieve the value. The method must take an argument ``obj``
1937
+ (in addition to self) that is the object to be serialized.
1938
+ :param str deserialize: Optional name of the Schema method for deserializing
1939
+ a value The method must take a single argument ``value``, which is the
1940
+ value to deserialize.
1941
+
1942
+ .. versionchanged:: 2.0.0
1943
+ Removed optional ``context`` parameter on methods. Use ``self.context`` instead.
1944
+
1945
+ .. versionchanged:: 2.3.0
1946
+ Deprecated ``method_name`` parameter in favor of ``serialize`` and allow
1947
+ ``serialize`` to not be passed at all.
1948
+
1949
+ .. versionchanged:: 3.0.0
1950
+ Removed ``method_name`` parameter.
1951
+ """
1952
+
1953
+ _CHECK_ATTRIBUTE = False
1954
+
1955
+ def __init__(
1956
+ self,
1957
+ serialize: str | None = None,
1958
+ deserialize: str | None = None,
1959
+ **kwargs,
1960
+ ):
1961
+ # Set dump_only and load_only based on arguments
1962
+ kwargs["dump_only"] = bool(serialize) and not bool(deserialize)
1963
+ kwargs["load_only"] = bool(deserialize) and not bool(serialize)
1964
+ super().__init__(**kwargs)
1965
+ self.serialize_method_name = serialize
1966
+ self.deserialize_method_name = deserialize
1967
+ self._serialize_method = None
1968
+ self._deserialize_method = None
1969
+
1970
+ def _bind_to_schema(self, field_name, schema):
1971
+ if self.serialize_method_name:
1972
+ self._serialize_method = utils.callable_or_raise(
1973
+ getattr(schema, self.serialize_method_name)
1974
+ )
1975
+
1976
+ if self.deserialize_method_name:
1977
+ self._deserialize_method = utils.callable_or_raise(
1978
+ getattr(schema, self.deserialize_method_name)
1979
+ )
1980
+
1981
+ super()._bind_to_schema(field_name, schema)
1982
+
1983
+ def _serialize(self, value, attr, obj, **kwargs):
1984
+ if self._serialize_method is not None:
1985
+ return self._serialize_method(obj)
1986
+ return missing_
1987
+
1988
+ def _deserialize(self, value, attr, data, **kwargs):
1989
+ if self._deserialize_method is not None:
1990
+ return self._deserialize_method(value)
1991
+ return value
1992
+
1993
+
1994
+ class Function(Field):
1995
+ """A field that takes the value returned by a function.
1996
+
1997
+ :param serialize: A callable from which to retrieve the value.
1998
+ The function must take a single argument ``obj`` which is the object
1999
+ to be serialized. It can also optionally take a ``context`` argument,
2000
+ which is a dictionary of context variables passed to the serializer.
2001
+ If no callable is provided then the ```load_only``` flag will be set
2002
+ to True.
2003
+ :param deserialize: A callable from which to retrieve the value.
2004
+ The function must take a single argument ``value`` which is the value
2005
+ to be deserialized. It can also optionally take a ``context`` argument,
2006
+ which is a dictionary of context variables passed to the deserializer.
2007
+ If no callable is provided then ```value``` will be passed through
2008
+ unchanged.
2009
+
2010
+ .. versionchanged:: 2.3.0
2011
+ Deprecated ``func`` parameter in favor of ``serialize``.
2012
+
2013
+ .. versionchanged:: 3.0.0a1
2014
+ Removed ``func`` parameter.
2015
+ """
2016
+
2017
+ _CHECK_ATTRIBUTE = False
2018
+
2019
+ def __init__(
2020
+ self,
2021
+ serialize: (
2022
+ None
2023
+ | typing.Callable[[typing.Any], typing.Any]
2024
+ | typing.Callable[[typing.Any, dict], typing.Any]
2025
+ ) = None,
2026
+ deserialize: (
2027
+ None
2028
+ | typing.Callable[[typing.Any], typing.Any]
2029
+ | typing.Callable[[typing.Any, dict], typing.Any]
2030
+ ) = None,
2031
+ **kwargs,
2032
+ ):
2033
+ # Set dump_only and load_only based on arguments
2034
+ kwargs["dump_only"] = bool(serialize) and not bool(deserialize)
2035
+ kwargs["load_only"] = bool(deserialize) and not bool(serialize)
2036
+ super().__init__(**kwargs)
2037
+ self.serialize_func = serialize and utils.callable_or_raise(serialize)
2038
+ self.deserialize_func = deserialize and utils.callable_or_raise(deserialize)
2039
+
2040
+ def _serialize(self, value, attr, obj, **kwargs):
2041
+ return self._call_or_raise(self.serialize_func, obj, attr)
2042
+
2043
+ def _deserialize(self, value, attr, data, **kwargs):
2044
+ if self.deserialize_func:
2045
+ return self._call_or_raise(self.deserialize_func, value, attr)
2046
+ return value
2047
+
2048
+ def _call_or_raise(self, func, value, attr):
2049
+ if len(utils.get_func_args(func)) > 1:
2050
+ if self.parent.context is None:
2051
+ msg = f"No context available for Function field {attr!r}"
2052
+ raise ValidationError(msg)
2053
+ return func(value, self.parent.context)
2054
+ return func(value)
2055
+
2056
+
2057
+ class Constant(Field):
2058
+ """A field that (de)serializes to a preset constant. If you only want the
2059
+ constant added for serialization or deserialization, you should use
2060
+ ``dump_only=True`` or ``load_only=True`` respectively.
2061
+
2062
+ :param constant: The constant to return for the field attribute.
2063
+
2064
+ .. versionadded:: 2.0.0
2065
+ """
2066
+
2067
+ _CHECK_ATTRIBUTE = False
2068
+
2069
+ def __init__(self, constant: typing.Any, **kwargs):
2070
+ super().__init__(**kwargs)
2071
+ self.constant = constant
2072
+ self.load_default = constant
2073
+ self.dump_default = constant
2074
+
2075
+ def _serialize(self, value, *args, **kwargs):
2076
+ return self.constant
2077
+
2078
+ def _deserialize(self, value, *args, **kwargs):
2079
+ return self.constant
2080
+
2081
+
2082
+ class Inferred(Field):
2083
+ """A field that infers how to serialize, based on the value type.
2084
+
2085
+ .. warning::
2086
+
2087
+ This class is treated as private API.
2088
+ Users should not need to use this class directly.
2089
+ """
2090
+
2091
+ def __init__(self):
2092
+ super().__init__()
2093
+ # We memoize the fields to avoid creating and binding new fields
2094
+ # every time on serialization.
2095
+ self._field_cache = {}
2096
+
2097
+ def _serialize(self, value, attr, obj, **kwargs):
2098
+ field_cls = self.root.TYPE_MAPPING.get(type(value))
2099
+ if field_cls is None:
2100
+ field = super()
2101
+ else:
2102
+ field = self._field_cache.get(field_cls)
2103
+ if field is None:
2104
+ field = field_cls()
2105
+ field._bind_to_schema(self.name, self.parent)
2106
+ self._field_cache[field_cls] = field
2107
+ return field._serialize(value, attr, obj, **kwargs)
2108
+
2109
+
2110
+ # Aliases
2111
+ URL = Url
2112
+ Str = String
2113
+ Bool = Boolean
2114
+ Int = Integer