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

[UPX-6] Replace requests with httpx #5

Merged
merged 1 commit into from
Feb 13, 2025

Conversation

farmisen
Copy link
Owner

@farmisen farmisen commented Feb 13, 2025

Replace requests HTTP client library with httpx for HTTP operations

Switches the HTTP client implementation from requests to httpx for making HTTP requests. This change modernizes the HTTP client layer while maintaining similar functionality with async-compatible tooling.

Changes

  • Replaces requests/requests-toolbelt dependencies with httpx/anyio in poetry.lock
  • Updates client.py to use httpx.Client() instead of requests
  • Modifies test fixtures to use respx instead of responses for mocking HTTP calls

Impact

  • Changes HTTP client behavior to use httpx's connection pooling and timeout handling
  • Removes dependencies on requests, requests-toolbelt, urllib3, and charset-normalizer
  • Adds new dependencies on httpx, anyio, h11, and sniffio
  • May have slightly different connection handling characteristics due to httpx's implementation

Summary by CodeRabbit

  • Chores

    • Updated project dependencies by replacing legacy HTTP libraries with a modern alternative for improved functionality.
  • Refactor

    • Transitioned HTTP request handling to the new client, enhancing error management and overall performance.
  • Tests

    • Revamped the test suite to adopt updated HTTP mocking techniques, ensuring alignment and reliability with the enhanced client implementation.

Copy link

coderabbitai bot commented Feb 13, 2025

Walkthrough

The changes update the project's dependencies and testing framework by replacing the requests-based approach with httpx and its associated mocking library respx. In the configuration file (pyproject.toml), several dependencies are removed and new ones added with specific version constraints. Correspondingly, the test suite in tests/test_client.py is refactored to use respx for HTTP request mocking, including updates to test function signatures and error handling. In upyloadthing/client.py, the internal HTTP client operations are modified to utilize httpx.Client() and to handle exceptions via httpx.HTTPError.

Changes

File(s) Change Summary
pyproject.toml Updated dependencies for the project "upyloadthing": removed requests, requests-toolbelt, responses, and pytest-responses; added httpx and respx with specific version constraints; retained inflection.
tests/test_client.py Replaced the responses library with respx for HTTP request mocking. Test function signatures now include respx_mock: respx.MockRouter and use httpx.Response. Error handling now raises httpx.HTTPError.
upyloadthing/client.py Modified the UTApi class to use httpx.Client() for HTTP requests and updated exception handling to raise httpx.HTTPError instead of using the old requests exception.

Sequence Diagram(s)

sequenceDiagram
    participant U as UTApi
    participant X as httpx Client
    participant S as Server

    U->>X: Initiate HTTP request
    X->>S: Send request
    S-->>X: Return HTTP response
    X-->>U: Provide response
    U->>U: Handle exceptions (raise httpx.HTTPError)
Loading
sequenceDiagram
    participant T as Test Suite
    participant U as UTApi
    participant R as respx Mock Router
    participant X as httpx Client

    T->>U: Call API method
    U->>X: Send HTTP request
    R->>X: Intercept request & supply mock response
    X-->>U: Return mocked response
    U-->>T: Deliver result
Loading

Poem

I'm a rabbit hopping through the code,
Replacing old tales with something bold.
HTTPx now leads the way,
While Respx makes our tests play.
With carrots 🥕 and bytes so bright,
I celebrate these changes in pure delight!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@farmisen farmisen force-pushed the farmisen/upy-6-replace-requests-with-httpx branch from bae87ee to 945e9e2 Compare February 13, 2025 17:20
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/test_client.py (1)

72-72: Remove debug print statement.

The print statement print(type(respx_mock)) appears to be a debugging artifact and should be removed.

-    print(type(respx_mock))
upyloadthing/client.py (1)

116-128: Consider adding timeout configuration for httpx client.

While the migration to httpx is correct, it's recommended to configure timeouts explicitly to prevent hanging requests. httpx provides comprehensive timeout controls.

 with httpx.Client() as client:
     if data is None:
         response = client.request(
-            method=method, url=url, headers=headers
+            method=method, url=url, headers=headers,
+            timeout=httpx.Timeout(10.0, connect=5.0)
         )
     elif has_files:
         response = client.request(
-            method=method, url=url, headers=headers, files=data
+            method=method, url=url, headers=headers, files=data,
+            timeout=httpx.Timeout(30.0, connect=5.0)  # Longer timeout for file uploads
         )
     else:
         response = client.request(
-            method=method, url=url, headers=headers, json=data
+            method=method, url=url, headers=headers, json=data,
+            timeout=httpx.Timeout(10.0, connect=5.0)
         )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 26439a4 and 945e9e2.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • pyproject.toml (2 hunks)
  • tests/test_client.py (10 hunks)
  • upyloadthing/client.py (3 hunks)
🔇 Additional comments (3)
tests/test_client.py (1)

68-222: LGTM! Test suite successfully migrated to respx.

The migration from responses to respx is complete and well-implemented:

  • All test functions correctly use the @respx.mock() decorator
  • Type hints added for respx_mock parameter
  • Test coverage remains comprehensive
🧰 Tools
🪛 Gitleaks (8.21.2)

165-165: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

pyproject.toml (2)

11-17: LGTM! Dependencies successfully updated.

The migration from requests to httpx is properly reflected in the dependencies:

  • Removed requests and requests-toolbelt
  • Added httpx with appropriate version constraint
  • Updated test dependencies from responses to respx

Also applies to: 24-30


16-16:

✅ Verification successful

Verify httpx version constraint.

Let's verify that we're using the latest stable version of httpx.


🌐 Web query:

What is the latest stable version of httpx?

💡 Result:

The latest stable versions of httpx depend on which specific package you're referring to:

For Python's HTTPX client library (encode/httpx):

  • Version: 0.28.1
  • Release Date: December 6th, 2024[1][5]
  • Key changes:
    • Deprecated SSL configuration parameters (verify as string argument and cert)[1]
    • Removed deprecated proxies and app arguments[1]
    • Improved URL percent escaping based on WHATWG spec[1]

For ProjectDiscovery's network scanner (projectdiscovery/httpx):

  • Version: v1.6.10
  • Release Date: October 20th, 2024[7]
  • Key updates:
    • Fixed probe functionality with JSON/CSV outputs[7]
    • Added screenshot idle configuration support[7]
    • CPU optimization via fastdialer v0.3 update[7]

These are two distinct projects sharing the same name but serving different purposes:

  • The Python library focuses on HTTP client functionality
  • The Go-based tool specializes in network reconnaissance and scanning

Always verify which package you're using through context clues like programming language (Python vs Go) or documentation references[5][7].

Citations:


HTTPX Dependency Version Confirmed

After verifying that the latest stable version of Python's HTTPX client is 0.28.1, the dependency specification in your pyproject.toml (i.e., "httpx (>=0.28.1,<0.29.0)") is accurate and up-to-date.

@farmisen farmisen merged commit 801e6fd into main Feb 13, 2025
3 checks passed
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.

1 participant