Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

177 upgrade pydantic version #179

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open

Conversation

Antonyjin
Copy link
Member

No description provided.

Antonyjin and others added 8 commits October 4, 2024 10:59
- Migrated to Pydantic v2:
  - Replaced deprecated `parse_obj()` and `parse_raw()` with
`model_validate()` and `model_validate_json()`.
  - Replaced `.dict()` with `.model_dump()` for serializing models to dictionaries.
  - Updated `validator` to `field_validator` and `root_validator` to
`model_validator` to comply with Pydantic v2 syntax changes.

- Fixed asyncio issues:
  - Added `await` for asynchronous methods like `raise_for_status()`
in `RemoteAccount` and other HTTP operations to avoid `RuntimeWarning`.

- Updated config handling:
  - Used `ClassVar` for constants in `Settings` and other configuration classes.
  - Replaced `Config` with `ConfigDict` in Pydantic models
to follow v2 conventions.
  - Added default values for missing fields in chain configurations
(`CHAINS_SEPOLIA_ACTIVE`, etc.).

- Adjusted signature handling:
  - Updated the signing logic to prepend `0x` in the `BaseAccount` signature
generation to ensure correct Ethereum address formatting.

- Minor fixes:
  - Resolved issue with extra fields not being allowed by default
by specifying `extra="allow"` or `extra="forbid"` where necessary.
  - Fixed tests to account for changes in model validation and
serialization behavior.
  - Added `pydantic-settings` as a new dependency for configuration management.
- Updated all instances of **extra_fields to ensure proper handling of
Optional dictionaries using `(extra_fields or {})` pattern.
- Added proper return statements in `AlephHttpClient.get_message_status`
to return parsed JSON data as a `MessageStatus` object.
- Updated `Settings` class in `conf.py` to correct DNS resolvers type
and simplify the `model_config` definition.
- Refactored `parse_volume` to ensure correct handling of Mapping types
and MachineVolume types, avoiding TypeErrors.
- Improved field validation and model validation in `SignedPubKeyHeader` by
using correct Pydantic v2 validation decorators and ensuring compatibility with the new model behavior.
- Applied formatting and consistency fixes for `model_dump` usage and indentation improvements in test files.
* Missing chain field on auth

* Fix Signature of Solana operation for CRN

* Add export_private_key func for accounts

* Improve _load_account

* Add chain arg to _load_account

* Increase default HTTP_REQUEST_TIMEOUT

* Typing

---------

Co-authored-by: Olivier Le Thanh Duong <olivier@lethanh.be>
- Migrated to Pydantic v2:
  - Replaced deprecated `parse_obj()` and `parse_raw()` with
`model_validate()` and `model_validate_json()`.
  - Replaced `.dict()` with `.model_dump()` for serializing models to dictionaries.
  - Updated `validator` to `field_validator` and `root_validator` to
`model_validator` to comply with Pydantic v2 syntax changes.

- Fixed asyncio issues:
  - Added `await` for asynchronous methods like `raise_for_status()`
in `RemoteAccount` and other HTTP operations to avoid `RuntimeWarning`.

- Updated config handling:
  - Used `ClassVar` for constants in `Settings` and other configuration classes.
  - Replaced `Config` with `ConfigDict` in Pydantic models
to follow v2 conventions.
  - Added default values for missing fields in chain configurations
(`CHAINS_SEPOLIA_ACTIVE`, etc.).

- Adjusted signature handling:
  - Updated the signing logic to prepend `0x` in the `BaseAccount` signature
generation to ensure correct Ethereum address formatting.

- Minor fixes:
  - Resolved issue with extra fields not being allowed by default
by specifying `extra="allow"` or `extra="forbid"` where necessary.
  - Fixed tests to account for changes in model validation and
serialization behavior.
  - Added `pydantic-settings` as a new dependency for configuration management.
…Pydantic v2 requirements

Pydantic v2 requires explicit type annotations for fields, so added `float`
to ensure proper validation of HTTP_REQUEST_TIMEOUT.
@Antonyjin Antonyjin linked an issue Oct 15, 2024 that may be closed by this pull request
Antonyjin and others added 2 commits October 15, 2024 05:07
There were changes made on aleph-message on the main branch about
pydantic version. Using the version by the url and then change it
later after the release.
@Antonyjin Antonyjin marked this pull request as ready for review October 21, 2024 14:59
@Antonyjin Antonyjin requested a review from hoh October 21, 2024 14:59
Copy link

Failed to retrieve llama text: POST 504:

504 Gateway Time-out


The server didn't respond in time.

"coincurve; python_version<'3.11'",
"coincurve>=19; python_version>='3.11'",
"eth-abi>=4; python_version>='3.11'",
"eth-typing==4.3.1",
"jwcrypto==1.5.6",
"pynacl==1.5", # Needed now as default with _load_account changement
"pydantic-settings>=2",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this dependency ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

By moving to pydantic v2, the settings management has been moved to a separate package called pydantic-settings so if we don't import it, it causes some errors

@@ -72,7 +72,7 @@ async def sign_message(self, message: Dict) -> Dict:
"""
message = self._setup_sender(message)
signature = await self.sign_raw(get_verification_buffer(message))
message["signature"] = signature.hex()
message["signature"] = "0x" + signature.hex()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this added here ?

Copy link
Member Author

@Antonyjin Antonyjin Oct 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, my mistake. Normally, .hex() should not remove the 0x at the beginning of the signature, but after the changes made for the Pydantic upgrade, it remove it.
I was just missing this, so I added it temporarily to check if everything would pass and completely forgot to correct it.

I'll debug to see why the hex remove the 0x

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found out that with python3>=3.5 .hex() should remove the 0x prefix from the string.
My branch does it so it causes some errors in the tests but on the main branch it seems that the prefix is not removed even though the python version is 3.11.5

@@ -52,7 +52,7 @@ async def from_crypto_host(
session = aiohttp.ClientSession(connector=connector)

async with session.get(f"{host}/properties") as response:
response.raise_for_status()
await response.raise_for_status()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this related to pydantic ? Should this use await or should the implementation not be async ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not related to pydantic, just saw some warning when lauching the tests, so I tried to fix some of them because it wasn't a lot of work.

@@ -75,7 +75,7 @@ def private_key(self):
async def sign_message(self, message: Dict) -> Dict:
"""Sign a message inplace."""
async with self._session.post(f"{self._host}/sign", json=message) as response:
response.raise_for_status()
await response.raise_for_status()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same: Is this related to pydantic ? Should this use await or should the implementation not be async ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same: This is not related to pydantic, just saw some warning when lauching the tests, so I tried to fix some of them because it wasn't a lot of work.

@@ -467,3 +467,6 @@ async def get_message_status(self, item_hash: str) -> MessageStatus:
if resp.status == HTTPNotFound.status_code:
raise MessageNotFoundError(f"No such hash {item_hash}")
resp.raise_for_status()

data = await resp.json()
return MessageStatus(**data)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was there no return before ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. When I initially tested upgrading to Pydantic v2, I encountered an error saying that a return value was required, so I added it. I just checked again, and the error is no longer there, so I may have done it incorrectly. I'll remove it in the next push.

@root_validator(pre=False, skip_on_failure=True)
def check_expiry(cls, values) -> Dict[str, bytes]:
@model_validator(mode="after")
def check_expiry(cls, values: "SignedPubKeyHeader") -> "SignedPubKeyHeader":
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why quotes on the type annotations ? What about from __futures__ import annotations ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Completely forgot about this. I've added it to the code, it works fine and it will be included in the next push.

@Antonyjin Antonyjin requested a review from hoh October 29, 2024 08:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Upgrade Pydantic version
4 participants