E527
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
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
This commit enhances the Capsolver class by adding support for custom API endpoints. Users can now specify an alternative API URL when initializing the Capsolver instance, allowing for greater flexibility when working with different Capsolver API providers or self-hosted solutions.
Key changes:
api_url
create_task
get_task_result
Example usage:
# Standard API solver = Capsolver(api_key='your_api_key') # Custom API endpoint solver = Capsolver( api_key='your_api_key', api_url='https://custom-api.capsolver.com' )
New Features:
Sorry, something went wrong.
Add configurable API URL support for Capsolver captcha solver
7557ad3
This pull request introduces the ability to configure the base URL for the Capsolver API. A new api_url parameter has been added to the Capsolver class constructor, allowing users to specify a custom API endpoint. The create_task and get_task_result methods have been updated to use the configured api_url. Trailing slash handling was added to ensure proper URL formatting.
sequenceDiagram participant User participant Capsolver participant Custom API User->>Capsolver: get_task_result(task_id) Capsolver->>Custom API: POST /getTaskResult with task_id Custom API-->>Capsolver: Response (solution or status) Capsolver-->>User: Response (solution or status)
twikit/_captcha/capsolver.py
@sourcery-ai review
@sourcery-ai issue
@sourcery-ai
@sourcery-ai title
@sourcery-ai summary
@sourcery-ai guide
@sourcery-ai resolve
@sourcery-ai dismiss
@sourcery-ai plan
Access your dashboard to:
The update in twikit/_captcha/capsolver.py introduces a new parameter, api_url, in the Capsolver class. The parameter is added to the constructor signature and the class documentation, with a default value of 'https://api.capsolver.com'. Trailing slashes in the provided URL are removed upon initialization. Both the create_task and get_task_result methods now build their endpoint URLs dynamically using the api_url value instead of relying on hardcoded URLs.
Capsolver
'https://api.capsolver.com'
sequenceDiagram participant U as User participant C as Capsolver participant A as API Server U->>C: Initialize Capsolver(api_url) U->>C: Call create_task(parameters) C->>A: POST {api_url}/create_task A-->>C: Respond with task_id U->>C: Call get_task_result(task_id) C->>A: GET {api_url}/get_task_result with task_id A-->>C: Respond with task result C-->>U: Return task result
Hopping through the code so light, I’ve tweaked the URLs just right. With a dash of slash removed, My API calls are smoothly approved. A rabbit’s hop in every byte, so bright! 🐇💻
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
There are 3 ways to chat with CodeRabbit:
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.
@coderabbitai
@coderabbitai generate unit testing code for this file.
@coderabbitai modularize this function.
@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.
@coderabbitai pause
@coderabbitai resume
@coderabbitai review
@coderabbitai full review
@coderabbitai summary
@coderabbitai generate docstrings
@coderabbitai resolve
@coderabbitai configuration
@coderabbitai help
@coderabbitai ignore
.coderabbit.yaml
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Hey @izzzzzi - I've reviewed your changes - here's some feedback:
Overall Comments:
Actionable comments posted: 0
twikit/_captcha/capsolver.py (2) 44-51: Consider adding URL validation The current implementation accepts any string as the API URL without validation. Consider adding basic URL format validation to ensure proper URL structure. def __init__( self, api_key: str, max_attempts: int = 3, get_result_interval: float = 1.0, use_blob_data: bool = False, api_url: str = 'https://api.capsolver.com' ) -> None: self.api_key = api_key self.get_result_interval = get_result_interval self.max_attempts = max_attempts self.use_blob_data = use_blob_data + # Basic validation to ensure the URL starts with http:// or https:// + if not api_url.startswith(('http://', 'https://')): + raise ValueError("API URL must start with 'http://' or 'https://'") self.api_url = api_url.rstrip('/') 58-63: Consider adding error handling for API requests The code should handle HTTP exceptions that might occur when making requests to custom API endpoints. def create_task(self, task_data: dict) -> dict: data = { 'clientKey': self.api_key, 'task': task_data } - response = httpx.post( - f'{self.api_url}/createTask', - json=data, - headers={'content-type': 'application/json'} - ).json() + try: + response = httpx.post( + f'{self.api_url}/createTask', + json=data, + headers={'content-type': 'application/json'}, + timeout=30 # Add a reasonable timeout + ) + response.raise_for_status() # Raise exception for HTTP errors + return response.json() + except httpx.HTTPError as e: + raise RuntimeError(f"API request failed: {str(e)}") - return response Similar changes should be applied to the get_task_result method as well. Also applies to: 70-75
44-51: Consider adding URL validation The current implementation accepts any string as the API URL without validation. Consider adding basic URL format validation to ensure proper URL structure. def __init__( self, api_key: str, max_attempts: int = 3, get_result_interval: float = 1.0, use_blob_data: bool = False, api_url: str = 'https://api.capsolver.com' ) -> None: self.api_key = api_key self.get_result_interval = get_result_interval self.max_attempts = max_attempts self.use_blob_data = use_blob_data + # Basic validation to ensure the URL starts with http:// or https:// + if not api_url.startswith(('http://', 'https://')): + raise ValueError("API URL must start with 'http://' or 'https://'") self.api_url = api_url.rstrip('/') 58-63: Consider adding error handling for API requests The code should handle HTTP exceptions that might occur when making requests to custom API endpoints. def create_task(self, task_data: dict) -> dict: data = { 'clientKey': self.api_key, 'task': task_data } - response = httpx.post( - f'{self.api_url}/createTask', - json=data, - headers={'content-type': 'application/json'} - ).json() + try: + response = httpx.post( + f'{self.api_url}/createTask', + json=data, + headers={'content-type': 'application/json'}, + timeout=30 # Add a reasonable timeout + ) + response.raise_for_status() # Raise exception for HTTP errors + return response.json() + except httpx.HTTPError as e: + raise RuntimeError(f"API request failed: {str(e)}") - return response Similar changes should be applied to the get_task_result method as well. Also applies to: 70-75
44-51: Consider adding URL validation
44-51
The current implementation accepts any string as the API URL without validation. Consider adding basic URL format validation to ensure proper URL structure.
def __init__( self, api_key: str, max_attempts: int = 3, get_result_interval: float = 1.0, use_blob_data: bool = False, api_url: str = 'https://api.capsolver.com' ) -> None: self.api_key = api_key self.get_result_interval = get_result_interval self.max_attempts = max_attempts self.use_blob_data = use_blob_data + # Basic validation to ensure the URL starts with http:// or https:// + if not api_url.startswith(('http://', 'https://')): + raise ValueError("API URL must start with 'http://' or 'https://'") self.api_url = api_url.rstrip('/')
58-63: Consider adding error handling for API requests
58-63
The code should handle HTTP exceptions that might occur when making requests to custom API endpoints.
def create_task(self, task_data: dict) -> dict: data = { 'clientKey': self.api_key, 'task': task_data } - response = httpx.post( - f'{self.api_url}/createTask', - json=data, - headers={'content-type': 'application/json'} - ).json() + try: + response = httpx.post( + f'{self.api_url}/createTask', + json=data, + headers={'content-type': 'application/json'}, + timeout=30 # Add a reasonable timeout + ) + response.raise_for_status() # Raise exception for HTTP errors + return response.json() + except httpx.HTTPError as e: + raise RuntimeError(f"API request failed: {str(e)}") - return response
Similar changes should be applied to the get_task_result method as well.
Also applies to: 70-75
Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro
Reviewing files that changed from the base of the PR and between 3818195 and 7557ad3.
twikit/_captcha/capsolver.py (6) 35-36: Documentation looks good! The new parameter is well documented with a clear description of its purpose and default value. 44-45: Parameter addition implemented correctly The new api_url parameter has been added to the method signature with an appropriate default value, maintaining backward compatibility. 51-51: Good handling of trailing slashes The code properly strips any trailing slashes from the URL to ensure consistent formatting when constructing endpoint URLs later. 59-59: URL construction is correct Using f-string to combine the base API URL with the endpoint path is efficient. 71-71: URL construction is correct Consistent approach to URL construction as in the create_task method. 45-45: ❓ Verification inconclusive Update tests for the new parameter Ensure that unit tests are updated to cover the new configurable API URL functionality. 🏁 Script executed: #!/bin/bash # Check if there are any test files that might need to be updated fd -e py "test.*capsolver" -x cat {} \; 2>/dev/null || echo "No test files found for Capsolver" # Check if there are any test files in the project fd -e py "test" -x grep -l "Capsolver" {} \; 2>/dev/null || echo "No test files with Capsolver references found" Length of output: 90 ACTION: Update unit tests for the new configurable API URL Our automated search did not turn up any test files referencing Capsolver or its API URL configuration. Please verify manually whether: There are any tests covering the behavior of the new configurable API URL in twikit/_captcha/capsolver.py (line 45) The test suite needs new test cases or updates to ensure that changes to the API URL are properly validated If tests exist under a different naming convention or in unexpected locations, please update or add tests accordingly.
35-36: Documentation looks good!
35-36
The new parameter is well documented with a clear description of its purpose and default value.
44-45: Parameter addition implemented correctly
44-45
The new api_url parameter has been added to the method signature with an appropriate default value, maintaining backward compatibility.
51-51: Good handling of trailing slashes
51-51
The code properly strips any trailing slashes from the URL to ensure consistent formatting when constructing endpoint URLs later.
59-59: URL construction is correct
59-59
Using f-string to combine the base API URL with the endpoint path is efficient.
71-71: URL construction is correct
71-71
Consistent approach to URL construction as in the create_task method.
45-45:
45-45
Update tests for the new parameter
Ensure that unit tests are updated to cover the new configurable API URL functionality.
🏁 Script executed:
#!/bin/bash # Check if there are any test files that might need to be updated fd -e py "test.*capsolver" -x cat {} \; 2>/dev/null || echo "No test files found for Capsolver" # Check if there are any test files in the project fd -e py "test" -x grep -l "Capsolver" {} \; 2>/dev/null || echo "No test files with Capsolver references found"
Length of output: 90
ACTION: Update unit tests for the new configurable API URL
Our automated search did not turn up any test files referencing Capsolver or its API URL configuration. Please verify manually whether:
If tests exist under a different naming convention or in unexpected locations, please update or add tests accordingly.
@izzzzzi Напиши в телеграм плиз: @unstable6
@izzzzzi Приветствую, добавляя api_url - вы желаете дать пользователям возможность втыкать свои апи? Если так,то на каждом(почти) каптча сервисе роуты,аргументы разные.Если вы желаете для создания локальных апи - capsolver не предоставляет таких возможностей
@dwqekc я использую 3-4 сервиса для решения капчи и у всех апи идентичное
для поддержания объектирования либо делай абстракции либо реализации под все нужны тебе сервисы
ну или блин просто форк свой поддерживай)),тут мержи не быстро принимают)))))
но кстати, абстракции - тут мастхев можно в будущем di сделать короче более правильный чем щас обычно пихают))
Верхние уровни не будут знать о низших из за конечной реализации абстракции
sourcery-ai[bot] sourcery-ai[bot] left review comments
coderabbitai[bot] coderabbitai[bot] left review comments
Successfully merging this pull request may close these issues.