Skip to content

Commit

Permalink
Merge pull request #6 from MarzaElise/main
Browse files Browse the repository at this point in the history
Added context manager support and fixed bugs
  • Loading branch information
TheGenocides authored Sep 26, 2021
2 parents 46b0792 + 5dcd293 commit e42a103
Show file tree
Hide file tree
Showing 8 changed files with 332 additions and 162 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
*__pycache__
venv/
**/__pycache__
venv/
test.md
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

An Api Wrapper for extracting info from: quran api and bible api. I didn\'t made the document for this so for now read the file to find all functions there. I will add more holybooks in the future!

# Installation
## Installation

Find the module in here [Module](https://pypi.org/project/holybooks/)
Find the module in here [Module](https://pypi.org/project/holybooks/)

```bash
pip install holybooks
```

# Usage
## Usage

```python
# To return a verse(s) info inside the surah(Chapter)
Expand All @@ -35,7 +35,7 @@ for verse in bible_verses.verses:
verse.citation, # The citation of the current verse
verse # executes the __str__ method of the ChapterVerse class (it returns the verse itself)
)

#===============================================================================================================================

from holybooks import Torah
Expand All @@ -52,20 +52,20 @@ for verse in torah_verses.verses:
)
```

# API That I Used
## API That I Used

[Qur'an](https://alquran.cloud/api)

[Bible](https://bible-api.com/)

[Torah](https://bible-api.com/)

# Contributing
## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

# License
## License

[MIT](https://choosealicense.com/licenses/mit/)
1 change: 1 addition & 0 deletions holybooks/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .quran import *
from .bible import *
from .torah import *
from .errors import *
72 changes: 49 additions & 23 deletions holybooks/bible.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
__all__ = ("ApiError", "NotFound", "ChapterVerse", "Bible")
from .errors import ApiError, NotFound


class ApiError(Exception):
def __init__(self, status: int, msg: str) -> None:
super().__init__(f"Api has an error, return code: {status}.\n{msg}")


class NotFound(Exception):
def __init__(self, book: str, chapter: int, verse: str) -> None:
super().__init__(
f"Book {book}, Chapter {chapter}, Verse(s) {verse} Wasn't Found."
)
__all__ = ("ChapterVerse", "Bible")


def _build_verse(start: int, end: int = None) -> str:
Expand Down Expand Up @@ -39,10 +29,21 @@ def citation(self) -> str:
class Bible:
def __init__(self, book: str) -> None:
self.book = book
self._session = None
self._async_session = None
self.json = None
self.verses = None
self.raw_verse = None
self._request = None

@classmethod
def request(
cls, book: str, *, chapter: int, starting_verse: int, ending_verse: int = None
cls,
book: str,
*,
chapter: int,
starting_verse: int,
ending_verse: int = None,
):
try:
import requests
Expand All @@ -54,15 +55,21 @@ def request(
self = cls(book)
verse = _build_verse(starting_verse, ending_verse)

self.request = requests.get(f"https://bible-api.com/{book}+{chapter}:{verse}")
if self.request.status_code == 404:
if not self._session:
self._session = requests.Session()

self._request = self._session.get(
f"https://bible-api.com/{book}+{chapter}:{verse}"
)
if self._request.status_code == 404:
raise NotFound(book, chapter, verse)
elif self.request.status_code > 202:
elif self._request.status_code > 202:
raise ApiError(
self.request.status_code, self.request.json().get("error", "")
self._request.status_code,
self._request.json().get("error", ""),
)

self.json = self.request.json()
self.json = self._request.json()
self.verses = [ChapterVerse(i) for i in self.json["verses"]]

return self
Expand All @@ -87,26 +94,45 @@ async def async_request(
self = cls(book)
verse = _build_verse(starting_verse, ending_verse)

async with aiohttp.ClientSession(loop=loop) as session:
if not self._async_session:
self._async_session = aiohttp.ClientSession(loop=loop)

async with self._async_session as session:
async with session.get(
f"https://bible-api.com/{book}+{chapter}:{verse}"
) as resp:
self.request = resp
self._request = resp
self.json = await resp.json()

self.verses = [ChapterVerse(i) for i in self.json["verses"]]
self.raw_verse = self.json["text"]
if self.request.status == 404:
if self._request.status == 404:
raise NotFound(book, chapter, verse)
elif self.request.status > 202:
raise ApiError(self.request.status, self.json.get("error", ""))
elif self._request.status > 202:
raise ApiError(self._request.status, self.json.get("error", ""))

return self

@property
def citation(self) -> str:
if not self.json:
return None
return self.json["reference"]

@property
def translation(self) -> str:
if not self.json:
return None
return self.json["translation_name"]

def __enter__(self):
return self

def __exit__(self, *args):
return

async def __aenter__(self):
return self

async def __aexit__(self, *args):
return
67 changes: 67 additions & 0 deletions holybooks/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from typing import TYPE_CHECKING
from typing import Optional, Union

__all__ = (
"ApiError",
"ContentTypeError",
"NumberError",
"WrongLang",
"NotFound",
"BibleOnly",
)


class ApiError(Exception):
def __init__(self, status: int, msg: str) -> None:
super().__init__(f"Api has an error, return code: {status}.\n{msg}")


class ContentTypeError(Exception):
def __init__(
self,
class_: str,
mode: str,
first_query: Optional[Union[str, int]],
second_query: Optional[Union[str, int]],
) -> None:
super().__init__(
f"Attempt to decode JSON with unexpected mimetype: Return code: None\nlink: http://api.alquran.cloud/v1/{mode}/{first_query}:{second_query}/en.asad"
if class_ == "Ayah"
else f"Attempt to decode JSON with unexpected mimetype: Return code: None\nlink: http://api.alquran.cloud/v1/{mode}/{first_query}/{second_query}/en.asad"
)


class NumberError(Exception):
def __init__(
self,
mode: int,
obj: str,
first_query: int,
second_query: Optional[Union[str, int]],
) -> None:
super().__init__(
f"{obj} must above {first_query}"
if mode == 0
else f"{obj} must be between {first_query} to {second_query}"
)


class WrongLang(Exception):
def __init__(self, lang: str) -> None:
super().__init__(
f"The lang '{lang}' is not supported, it only support arabic(ar) and english(eng)"
)


class NotFound(Exception):
def __init__(self, book: str, chapter: int, verse: str) -> None:
super().__init__(
f"Book {book}, Chapter {chapter}, Verse(s) {verse} Wasn't Found."
)


class BibleOnly(Exception):
def __init__(self, book: str) -> None:
super().__init__(
f"The book {book} wasn't found because its available only in Bible"
)
Loading

0 comments on commit e42a103

Please sign in to comment.