Skip to content

Commit

Permalink
Merge pull request #26 from IHosseini083/refactoring
Browse files Browse the repository at this point in the history
Refactor sdk and cli.
  • Loading branch information
lnxpy authored Aug 24, 2022
2 parents 021e145 + 59c23a1 commit fbe88c3
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 46 deletions.
Empty file added src/__init__.py
Empty file.
4 changes: 2 additions & 2 deletions src/pasteme_cli/__main__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Entrypoint module, in case you use `python -mpasteme_cli`.
Entrypoint module, in case you use `python -m pasteme_cli`.
Why does this file exist, and why __main__? For more info, read:
Expand All @@ -8,7 +8,7 @@
- https://docs.python.org/2/using/cmdline.html#cmdoption-m
- https://docs.python.org/3/using/cmdline.html#cmdoption-m
"""
from pasteme_cli.cli import main
from .cli import main

if __name__ == "__main__":
main()
31 changes: 14 additions & 17 deletions src/pasteme_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mpasteme_cli` python will execute
- When you run `python -m pasteme_cli` python will execute
``__main__.py`` as a script. That means there won't be any
``pasteme_cli.__main__`` in ``sys.modules``.
- When you import __main__ it will get executed again (as a module) because
Expand All @@ -16,23 +16,22 @@
"""
import argparse
import sys
from typing import Optional, Sequence

from requests.exceptions import ConnectionError

from pasteme_cli.sdk import Snippet

from .constants import (
CONNECTION_ISSUE_HINT,
EPILOG_DESCRIPTION,
EXPIRY_TIME,
EXPIRY_TIME_HINT,
LANGUAGES,
LANGUAGES_HINT,
PASTEME_API_URL,
PASTEME_SERVICE_URL,
THEMES,
THEMES_HINT,
)
from .sdk import PasteMe

parser = argparse.ArgumentParser(
description=f'A CLI pastebin tool interacting with PasteMe ({PASTEME_SERVICE_URL}) RESTful APIs.',
Expand Down Expand Up @@ -101,13 +100,13 @@
)


def main(args=None):
def main(args: Optional[Sequence[str]] = None) -> None:
args = parser.parse_args(args=args)

with args.file as source_code:
code_lines = source_code.readlines()

args.end = args.end if args.end else len(code_lines)
args.end = args.end or len(code_lines)

code_lines = code_lines[int(args.start) - 1 : int(args.end)]

Expand All @@ -120,18 +119,16 @@ def main(args=None):
"1m": 30,
}

context = {
'title': args.title,
'body': ''.join(code_lines),
'language': args.language,
'theme': args.theme,
'expiry_time': expiry_days[args.expiry_time],
}

try:
snippet = Snippet(**context)
context = snippet.push(PASTEME_API_URL, args.verbose).json()
print(f'PASTE --> {context["url"]}')
snippet = PasteMe(args.verbose)
resp = snippet.create(
title=args.title,
body=''.join(code_lines),
language=args.language,
theme=args.theme,
expiry_time=expiry_days[args.expiry_time],
)
print(f'PASTE --> {resp.url}')
sys.exit()
except ConnectionError:
sys.exit(CONNECTION_ISSUE_HINT)
8 changes: 3 additions & 5 deletions src/pasteme_cli/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,23 @@

# Hint for using the available languages
LANGUAGES_HINT = f'''snippet language (available languages:
{", ".join([_ for _ in LANGUAGES.keys()])})
{", ".join(LANGUAGES.keys())})
'''

# Hint for using the available themes
THEMES_HINT = f'''theme (available themes:
{", ".join([_ for _ in THEMES.keys()])})
{", ".join(THEMES.keys())})
'''

# Hint for using the available expiry times
EXPIRY_TIME_HINT = f'''expiry time (available expiry times:
{", ".join([_ for _ in EXPIRY_TIME.keys()])}) (default: 1w/1week)
{", ".join(EXPIRY_TIME.keys())}) (default: 1w/1week)
'''

# Actual service information

PASTEME_SERVICE_URL = 'https://pasteme.pythonanywhere.com'

PASTEME_API_URL = 'https://pasteme.pythonanywhere.com/api/v1/paste/'

# Traceback messages

CONNECTION_ISSUE_HINT = 'Check your network connection. Make sure the PasteMe service is up and running.'
Expand Down
6 changes: 4 additions & 2 deletions src/pasteme_cli/sdk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from .pasteme import Snippet
from .pasteme import PasteMe

__all__ = ("Snippet",)
__all__ = [
"PasteMe",
]
40 changes: 25 additions & 15 deletions src/pasteme_cli/sdk/pasteme.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,40 @@
import json
from typing import ClassVar
from urllib.parse import urljoin

import requests
from pygments import formatters, highlight, lexers

from ..constants import PASTEME_SERVICE_URL
from .types import APIResponse

JSON_TEMPLATE = '''-> {}
{}'''


class Snippet:
def __init__(self, title, body, language, theme, expiry_time) -> None:
self.snippet = {
'title': title,
'body': body,
'language': language,
'theme': theme,
'expires_in': expiry_time,
}
class PasteMe:
BASE_URL: ClassVar[str] = PASTEME_SERVICE_URL
API_URL: ClassVar[str] = urljoin(BASE_URL, "/api/v1/paste/")

def __init__(self, verbose: bool = False) -> None:
self.verbose = verbose

def push(self, url, is_verbose=False) -> requests.Response:
response = requests.post(url=url, data=self.snippet)
def create(self, **context) -> APIResponse:
response = requests.post(self.API_URL, data=context)

if is_verbose:
if self.verbose:
response_json = response.json()
sent_data = highlight(json.dumps(self.snippet, indent=3), lexers.JsonLexer(), formatters.TerminalFormatter())
response_data = highlight(json.dumps(response_json, indent=3), lexers.JsonLexer(), formatters.TerminalFormatter())
sent_data = highlight(
json.dumps(context, indent=3),
lexers.JsonLexer(),
formatters.TerminalFormatter(),
)
response_data = highlight(
json.dumps(response_json, indent=3),
lexers.JsonLexer(),
formatters.TerminalFormatter(),
)
print(JSON_TEMPLATE.format('Posted Data', sent_data))
print(JSON_TEMPLATE.format('Returned Payload', response_data))

return response
return APIResponse(**response.json())
13 changes: 13 additions & 0 deletions src/pasteme_cli/sdk/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""Types representing API responses from PasteMe."""
from dataclasses import dataclass


@dataclass
class APIResponse:
id: str
title: str
body: str
language: str
theme: str
expires_in: str
url: str
9 changes: 4 additions & 5 deletions tests/test_snippet.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import unittest

from pasteme_cli.constants import PASTEME_API_URL
from pasteme_cli.sdk.pasteme import Snippet
from src.pasteme_cli.constants import PASTEME_SERVICE_URL
from src.pasteme_cli.sdk.pasteme import PasteMe


class SnippetTestCase(unittest.TestCase):
Expand All @@ -16,9 +16,8 @@ def setUp(self) -> None:

# TODO: Using mocks
def test_push_snippet(self):
response = Snippet(**self.sample).push(PASTEME_API_URL)
self.assertEqual(response.status_code, 201)
self.assertIn('url', response.json().keys())
resp = PasteMe().create(**self.sample)
self.assertIn(PASTEME_SERVICE_URL, resp.url)


if __name__ == '__main__':
Expand Down

0 comments on commit fbe88c3

Please sign in to comment.