-
Notifications
You must be signed in to change notification settings - Fork 7
grepper-python pull request #1
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
Open
CantCode023
wants to merge
41
commits into
CodeGrepper:main
Choose a base branch
from
CantCode023:mybranch
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 12 commits
Commits
Show all changes
41 commits
Select commit
Hold shift + click to select a range
0ddbba5
initial commit
CantCode023 50ea955
added Grepper to __init__ for importing
CantCode023 208af5d
removed line 83 which i had for debugging but forgot to remove from t…
CantCode023 0eb8e8c
added fetch_answer to retrieve an answer by id
CantCode023 6dc0461
Added update_answer to update an answer with specified id.
CantCode023 bf656b4
Changed class TestGrepper to Test
CantCode023 d3c7dbe
added unittest.main() to run tests
CantCode023 cf542b0
changed from grepper_python.main to from grepper_python
CantCode023 8bf68c1
added test for fetch_answer
CantCode023 fdfa092
added unittest for update_answer
CantCode023 edbc4ab
added pip support
CantCode023 8790f11
removed class VersionInfo
CantCode023 d79aaa4
deleted unnecessary stuffs and added __all__
CantCode023 6321d98
added exception base class for raising exceptions
CantCode023 911ab3f
changed import * to prevent errors
CantCode023 8c1927c
changed __api_key to _api_key since there is no need for double under…
CantCode023 540d09e
made the error message more customizable
CantCode023 5b376ec
changed str(response code) to just response code
CantCode023 f0004cb
changed for i to for answer for readability
CantCode023 b50fa04
changed msg from str to any
CantCode023 3d10b53
optimized raising exception
CantCode023 9f1966d
added pyproject.toml
CantCode023 854cd58
updated
CantCode023 48e4af4
wrote exceptions in a tuple
CantCode023 376cfb0
changed version to static instead of dynamic
CantCode023 3d5f2a2
changed exception_handler to support int instead of just string
CantCode023 389477b
nvm changign back to dynamic
CantCode023 8e02f5f
changed import * to avoid problems
CantCode023 e2d649e
removed comments
CantCode023 9be5d0f
changed from importing all exceptions to only NotFound
CantCode023 9412220
renamed DocDefaultException to GrepperDefaultException
CantCode023 8ce2625
changed relative imports to absolute imports
CantCode023 333203f
updated docs for 2 methods
TanvishGG 0480e8f
added 3rd method docs
TanvishGG 1f8ef9c
Merge pull request #1 from Bharath1910/tanvish
Bharath1910 10b2884
Commit the sequel.
gaghackz 8665dc4
fixed consistency issues and added better example for search
Bharath1910 5c76689
fixed consistency issues
Bharath1910 ada403e
fixed spacing
Bharath1910 0f0190a
Merge pull request #1 from Bharath1910/mybranch
CantCode023 fd8b118
Update README.md
CantCode023 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
The MIT License | ||
|
||
Copyright (c) 2010-2023 Grepper, Inc. (https://www.grepper.com) | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,25 @@ | ||
# grepper-python | ||
python client library | ||
# Grepper Python Client | ||
The Grepper Python library provides convenient access to the Grepper API from applications written in the Python language. | ||
|
||
## Requirements | ||
Python 3.7 and later. | ||
|
||
## PIP | ||
``` | ||
pip install grepper-python | ||
``` | ||
|
||
## Manual Installation | ||
```bash | ||
git clone https://github.com/CantCode023/grepper-python | ||
cd grepper-python | ||
python setup.py install | ||
``` | ||
|
||
## Getting Started | ||
Simple usage: | ||
```py | ||
grepper = Grepper("your-grepper-api-key") | ||
answers = grepper.search("query") | ||
print(answers) | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
""" | ||
Python Grepper API | ||
~~~~~~~~~~~~~~~~~~~ | ||
An API wrapper for the Grepper API. | ||
""" | ||
|
||
__title__ = "grepper-python" | ||
__author__ = "CodeGrepper" | ||
__license__ = "MIT" | ||
__copyright__ = "Copyright 2010-2023 Grepper, Inc." | ||
__version__ = "0.0.1a" | ||
|
||
__path__ = __import__("pkgutil").extend_path(__path__, __name__) | ||
|
||
import logging | ||
from typing import NamedTuple, Literal | ||
|
||
from .answer import GrepperAnswer | ||
from .main import Grepper | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
logging.getLogger(__name__).addHandler(logging.NullHandler()) | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
del ( | ||
logging, | ||
NamedTuple, | ||
Literal, | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
from dataclasses import dataclass | ||
|
||
|
||
@dataclass | ||
class GrepperAnswer: | ||
id: int | ||
content: str | ||
author_name: str | ||
author_profile_url: str | ||
title: str | ||
upvotes: int | ||
downvotes: int |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
""" | ||
grepper-python.exceptions | ||
~~~~~~~~~~~~~~~~~~~ | ||
This module contains the set of grepper-python's exceptions. | ||
""" | ||
|
||
|
||
# 400 | ||
class BadRequest: | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Your request is invalid.""" | ||
|
||
|
||
# 401 | ||
class Unauthorized: | ||
"""Your API key is wrong.""" | ||
|
||
|
||
# 403 | ||
class Forbidden: | ||
"""You do not have access to the requested resource.""" | ||
|
||
|
||
# 404 | ||
class NotFound: | ||
"""The specified enpoint could not be found.""" | ||
|
||
|
||
# 405 | ||
class MethodNotAllowed: | ||
"""You tried to access an enpoint with an invalid method.""" | ||
|
||
|
||
# 429 | ||
class TooManyRequests: | ||
"""You're making too many requests! Slow down!""" | ||
|
||
|
||
# 500 | ||
class InternalServerError: | ||
"""We had a problem with our server. Try again later.""" | ||
|
||
|
||
# 503 | ||
class ServiceUnavailable: | ||
"""We're temporarily offline for maintenance. Please try again later.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
""" | ||
The MIT License | ||
|
||
Copyright (c) 2010-2023 Grepper, Inc. (https://www.grepper.com) | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. | ||
""" | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Optional | ||
|
||
from .answer import GrepperAnswer | ||
from .exceptions import * | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
import requests | ||
|
||
|
||
def exception_handler(status_code: str): | ||
if status_code == "400": | ||
return BadRequest | ||
elif status_code == "401": | ||
return Unauthorized | ||
elif status_code == "403": | ||
return Forbidden | ||
elif status_code == "404": | ||
return NotFound | ||
elif status_code == "405": | ||
return MethodNotAllowed | ||
elif status_code == "429": | ||
return TooManyRequests | ||
elif status_code == "500": | ||
return InternalServerError | ||
elif status_code == "503": | ||
return ServiceUnavailable | ||
|
||
|
||
class Grepper: | ||
""" | ||
Python Grepper API Wrapper | ||
""" | ||
|
||
def __init__(self, __api_key: str): | ||
self.__api_key = __api_key | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def search( | ||
self, query: str = False, similarity: Optional[int] = 60 | ||
): | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""This function searches all answers based on a query. | ||
|
||
Args: | ||
query (str, optional): Query to search through answer titles. ex: "Javascript loop array backwords". Defaults to False. | ||
similarity (Optional[int], optional): How similar the query has to be to the answer title. 1-100 where 1 is really loose matching and 100 is really strict/tight match. Defaults to 60. | ||
|
||
Returns: | ||
GrepperAnswer | ||
""" | ||
response = requests.get( | ||
"https://api.grepper.com/v1/answers/search", | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
params={"query": query, "similarity": similarity}, | ||
auth=(self.__api_key, ""), | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) | ||
if str(response.status_code) != "200": | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
exception = exception_handler(str(response.status_code)) | ||
raise exception(exception.__doc__) | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
json_response = response.json() | ||
data = [] | ||
for i in json_response["data"]: | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
new_answer = GrepperAnswer( | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
id=i["id"], | ||
content=i["content"], | ||
author_name=i["author_name"], | ||
author_profile_url=i["author_profile_url"], | ||
title=i["title"], | ||
upvotes=i["upvotes"], | ||
downvotes=i["downvotes"], | ||
) | ||
data.append(new_answer) | ||
return data | ||
|
||
def fetch_answer( | ||
self, id: int | ||
): | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""This function returns an answer specified by the id. | ||
|
||
Args: | ||
id (int, required): The id for the specified answer. ex: "560676 ". | ||
|
||
Returns: | ||
GrepperAnswer | ||
""" | ||
response = requests.get( | ||
f"https://api.grepper.com/v1/answers/{id}", | ||
auth=(self.__api_key, "") | ||
) | ||
if str(response.status_code) != "200": | ||
exception = exception_handler(str(response.status_code)) | ||
raise exception(exception.__doc__) | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
json_response = response.json() | ||
answer = GrepperAnswer( | ||
id=json_response["id"], | ||
content=json_response["content"], | ||
author_name=json_response["author_name"], | ||
author_profile_url=json_response["author_profile_url"], | ||
title=json_response["title"], | ||
upvotes=json_response["upvotes"], | ||
downvotes=json_response["downvotes"], | ||
) | ||
return answer | ||
|
||
def update_answer( | ||
self, id: int, answer: str | ||
): | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""This function returns an answer specified by the id. | ||
|
||
Args: | ||
id (int, required): The id for the specified answer. ex: "560676 ". | ||
answer (str, required): The answer you want it to update to. ex "new answer content here". | ||
|
||
Returns: | ||
Dict | ||
""" | ||
headers = { | ||
'Content-Type': 'application/x-www-form-urlencoded', | ||
} | ||
data = f"""answer[content]={answer}""" | ||
response = requests.post( | ||
f"https://api.grepper.com/v1/answers/{id}", | ||
headers=headers, | ||
data=data | ||
) | ||
if str(response.status_code) != "200": | ||
exception = exception_handler(str(response.status_code)) | ||
raise exception(exception.__doc__) | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
else: | ||
return response.json() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import setuptools | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
with open("README.md", "r", encoding="utf-8") as fh: | ||
long_description = fh.read() | ||
|
||
setup_info = { | ||
"name": "grepper-python", | ||
"version": "0.0.1a", | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"author": "CodedGrepper", | ||
"author_email": "[email protected]", | ||
"description": "An API wrapper for the Grepper API.", | ||
"long_description": long_description, | ||
"long_description_content_type": "text/markdown", | ||
"url": "https://github.com/CodeGrepper/grepper-python", | ||
"packages": setuptools.find_packages(), | ||
"install_requires": ["requests", "urllib3"], | ||
"classifiers": [ | ||
"Programming Language :: Python :: 3", | ||
], | ||
"python_requires": '>=3.7' | ||
} | ||
|
||
|
||
setuptools.setup(**setup_info) |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import unittest | ||
from unittest.mock import patch | ||
|
||
from grepper_python import Grepper | ||
from grepper_python.exceptions import * | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
class Test(unittest.TestCase): | ||
def setUp(self): | ||
self.api_key = "my_api_key" # Replace with your actual API key | ||
CantCode023 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.grepper = Grepper(self.api_key) | ||
|
||
@patch("requests.get") | ||
def test_fetch_answer_success(self, mock_get): | ||
# Mock successful API response | ||
mock_response = mock_get.return_value | ||
mock_response.status_code = 200 | ||
mock_response.json.return_value = { | ||
"id": 12345, | ||
"title": "Sample answer title", | ||
"content": "Sample answer content", | ||
"author_name": "John Doe", | ||
"author_profile_url": "https://www.example.com/johndoe", | ||
"upvotes": 10, | ||
"downvotes": 0, | ||
} | ||
|
||
# Call the function | ||
answer = self.grepper.fetch_answer(12345) | ||
|
||
# Assertions | ||
self.assertEqual(answer.id, 12345) | ||
self.assertEqual(answer.title, "Sample answer title") | ||
self.assertEqual(answer.content, "Sample answer content") | ||
self.assertEqual(answer.author_name, "John Doe") | ||
self.assertEqual(answer.author_profile_url, "https://www.example.com/johndoe") | ||
self.assertEqual(answer.upvotes, 10) | ||
self.assertEqual(answer.downvotes, 0) | ||
|
||
@patch("requests.get") | ||
def test_fetch_answer_not_found(self, mock_get): | ||
# Mock API response with 404 status code | ||
mock_response = mock_get.return_value | ||
mock_response.status_code = 404 | ||
mock_response.text = "Not Found" | ||
|
||
# Call the function and expect an exception | ||
with self.assertRaises(NotFound) as cm: | ||
self.grepper.fetch_answer(12345) | ||
|
||
self.assertEqual(str(cm.exception), "HTTPException: Not Found") | ||
|
||
@patch("requests.get") | ||
def test_fetch_answer_other_error(self, mock_get): | ||
# Mock API response with unexpected status code | ||
mock_response = mock_get.return_value | ||
mock_response.status_code = 500 | ||
mock_response.text = "Internal Server Error" | ||
|
||
# Call the function and expect an exception | ||
with self.assertRaises(Exception) as cm: | ||
self.grepper.fetch_answer(12345) | ||
|
||
self.assertEqual( | ||
str(cm.exception), | ||
"HTTPException: Unexpected status code: 500 (Internal Server Error)", | ||
) | ||
|
||
|
||
if __name__ == "__main__": | ||
unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.