Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions reader/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Usage:
------
$ realpython [options] [<id>]
$ realpython [options] [id] [id ...]
List the latest tutorials:
Expand Down Expand Up @@ -44,7 +44,7 @@
from reader import viewer


def main() -> None:
def main(): # type: () -> None
"""Read the Real Python article feed"""
args = [a for a in sys.argv[1:] if not a.startswith("-")]
opts = [o for o in sys.argv[1:] if o.startswith("-")]
Expand All @@ -55,7 +55,7 @@ def main() -> None:
return

# Should links be shown in the text
show_links = ("-l" in opts or "--show-links" in opts)
show_links = "-l" in opts or "--show-links" in opts

# An article ID is given, show article
if args:
Expand Down
21 changes: 11 additions & 10 deletions reader/feed.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,39 @@
"""Interact with the Real Python feed"""
# Standard library imports
from typing import Dict, List
from typing import Dict, List # noqa

# Third party imports
import feedparser
import html2text

# Reader imports
from reader import URL
_CACHED_FEEDS: Dict[str, feedparser.FeedParserDict] = dict()

_CACHED_FEEDS = dict() # type: Dict[str, feedparser.FeedParserDict]

def _feed() -> feedparser.FeedParserDict:

def _feed(): # type: () -> feedparser.FeedParserDict
"""Cache contents of the feed, so it's only read once"""
if URL not in _CACHED_FEEDS:
_CACHED_FEEDS[URL] = feedparser.parse(URL)
return _CACHED_FEEDS[URL]


def get_site() -> str:
def get_site(): # type: () -> str
"""Get name and link to web site of the feed"""
info = _feed().feed
return f"{info.title} ({info.link})"
return "{info.title} ({info.link})".format(info=info)


def get_article(article_id: str, links: bool = False) -> str:
def get_article(article_id, links=False): # type: (str, bool) -> str
"""Get article from feed with the given ID"""
articles = _feed().entries
try:
article = articles[int(article_id)]
except (IndexError, ValueError):
max_id = len(articles) - 1
msg = f"Unknown article ID, use ID from 0 to {max_id}"
raise SystemExit(f"Error: {msg}")
msg = "Unknown article ID, use ID from 0 to {}".format(max_id)
raise SystemExit("Error: {}".format(msg))

# Get article as HTML
try:
Expand All @@ -45,10 +46,10 @@ def get_article(article_id: str, links: bool = False) -> str:
to_text.ignore_links = not links
text = to_text.handle(html)

return f"# {article.title}\n\n{text}"
return u"# {}\n\n{}".format(article.title, text)


def get_titles() -> List[str]:
def get_titles(): # type: () -> List[str]
"""List titles in feed"""
articles = _feed().entries
return [a.title for a in articles]
13 changes: 8 additions & 5 deletions reader/viewer.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
"""Functions for displaying the Real Python feed"""

# Support Python 2
from __future__ import print_function

# Standard library imports
from typing import List
from typing import List # noqa


def show(article: str) -> None:
def show(article): # type: (str) -> None
"""Show one article"""
print(article)


def show_list(site: str, titles: List[str]) -> None:
def show_list(site, titles): # type: (str, List[str]) -> None
"""Show list of articles"""
print(f"The latest tutorials from {site}")
print("The latest tutorials from {}".format(site))
for article_id, title in enumerate(titles):
print(f"{article_id:>3} {title}")
print("{:>3} {}".format(article_id, title))
9 changes: 3 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,10 @@
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
],
packages=["reader"],
install_requires=["feedparser", "html2text"],
entry_points={
"console_scripts": [
"realpython=reader.__main__:main",
]
},
install_requires=["feedparser", "html2text", "typing"],
entry_points={"console_scripts": ["realpython=reader.__main__:main"]},
)
8 changes: 4 additions & 4 deletions tests/test_feed.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Tests for the reader.feed module"""
# Standard library imports
import pathlib
import os.path

# Third party imports
import pytest
Expand All @@ -9,21 +9,21 @@
from reader import feed

# Current directory
HERE = pathlib.Path(__file__).parent
HERE = os.path.dirname(__file__)


@pytest.fixture
def monkeypatch_feed(monkeypatch):
"""Use local file instead of downloading feed from web"""
local_path = HERE / "realpython_20180919.xml"
local_path = os.path.join(HERE, "realpython_20180919.xml")
monkeypatch.setattr(feed, "URL", local_path)
return local_path


@pytest.fixture
def monkeypatch_summary_feed(monkeypatch):
"""Use local file instead of downloading feed from web"""
local_path = HERE / "realpython_descriptions_20180919.xml"
local_path = os.path.join(HERE, "realpython_descriptions_20180919.xml")
monkeypatch.setattr(feed, "URL", local_path)
return local_path

Expand Down
10 changes: 5 additions & 5 deletions tests/test_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ def test_show_list(capsys):
assert stderr == ""

# Site name is shown in header
header, *lines = stdout.split("\n")
assert site in header
lines = stdout.split("\n")
assert site in lines[0]

# Each thing is listed preceded by a number
for thing, line in zip(things, lines):
line_id, *_ = line.split()
assert line_id.isnumeric()
for thing, line in zip(things, lines[1:]):
line_parts = line.split()
assert line_parts[0].isnumeric()
assert thing in line