Skip to content

Commit

Permalink
Merge 0187914 into 169a122
Browse files Browse the repository at this point in the history
  • Loading branch information
bboe committed Mar 7, 2019
2 parents 169a122 + 0187914 commit 60d87d6
Show file tree
Hide file tree
Showing 112 changed files with 5,456 additions and 4,046 deletions.
5 changes: 3 additions & 2 deletions .pylintrc
Expand Up @@ -33,7 +33,8 @@ load-plugins=
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
disable=C0111,I0011,I0012,W0142,W0212,R0205,R1705
#disable=C0111,I0011,I0012,W0142,W0212,R0205,R1705
disable=C0111,C0330,R0205,W0212


[REPORTS]
Expand Down Expand Up @@ -101,7 +102,7 @@ variable-rgx=[a-z_][a-z0-9_]{2,30}$
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$

# Good variable names which should always be accepted, separated by a comma
good-names=i,j,k,ex,Run,_
good-names=i,id,_

# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
Expand Down
7 changes: 3 additions & 4 deletions .travis.yml
Expand Up @@ -2,7 +2,7 @@ after_success: coveralls
cache: pip
install:
- yes | pip uninstall py pytest
- pip install coveralls flake8 flake8-quotes pydocstyle sphinx sphinx_rtd_theme
- pip install coveralls flake8 pydocstyle sphinx sphinx_rtd_theme
- python setup.py install
language: python
matrix:
Expand All @@ -11,13 +11,12 @@ matrix:
fast_finish: true
python:
- 2.7
- 3.4
- 3.5
- 3.6
- nightly
- 3.7
sudo: false
script:
- flake8 --exclude=docs,.eggs
- flake8 --exclude=.eggs,build,docs
- pydocstyle praw
- sphinx-build -W docs/ /tmp/foo
- coverage run --source=praw setup.py test
50 changes: 28 additions & 22 deletions docs/conf.py
@@ -1,42 +1,48 @@
import os
import sys
sys.path.insert(0, '..')

sys.path.insert(0, "..")

from praw import __version__

copyright = '2017, Bryce Boe'
exclude_patterns = ['_build']
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
html_static_path = ['_static']
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
'collapse_navigation': True
}
htmlhelp_basename = 'PRAW'
intersphinx_mapping = {'python': ('https://docs.python.org/3.6', None)}
master_doc = 'index'
copyright = "2017, Bryce Boe"
exclude_patterns = ["_build"]
extensions = ["sphinx.ext.autodoc", "sphinx.ext.intersphinx"]
html_static_path = ["_static"]
html_theme = "sphinx_rtd_theme"
html_theme_options = {"collapse_navigation": True}
htmlhelp_basename = "PRAW"
intersphinx_mapping = {"python": ("https://docs.python.org/3.6", None)}
master_doc = "index"
nitpicky = True
project = 'PRAW'
pygments_style = 'sphinx'
project = "PRAW"
pygments_style = "sphinx"
release = __version__
source_suffix = '.rst'
suppress_warnings = ['image.nonlocal_uri']
version = '.'.join(__version__.split('.', 2)[:2])
source_suffix = ".rst"
suppress_warnings = ["image.nonlocal_uri"]
version = ".".join(__version__.split(".", 2)[:2])


# Use RTD theme locally
if not os.environ.get('READTHEDOCS'):
if not os.environ.get("READTHEDOCS"):
import sphinx_rtd_theme

html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]


def skip(app, what, name, obj, skip, options):
if name in {'__call__', '__contains__', '__getitem__', '__init__',
'__iter__', '__len__'}:
if name in {
"__call__",
"__contains__",
"__getitem__",
"__init__",
"__iter__",
"__len__",
}:
return False
return skip


def setup(app):
app.connect('autodoc-skip-member', skip)
app.add_stylesheet('theme_override.css')
app.connect("autodoc-skip-member", skip)
app.add_stylesheet("theme_override.css")
22 changes: 13 additions & 9 deletions docs/examples/lmgtfy_bot.py
Expand Up @@ -2,16 +2,20 @@

import praw

QUESTIONS = ['what is', 'who is', 'what are']
REPLY_TEMPLATE = '[Let me google that for you](http://lmgtfy.com/?q={})'
QUESTIONS = ["what is", "who is", "what are"]
REPLY_TEMPLATE = "[Let me google that for you](http://lmgtfy.com/?q={})"


def main():
reddit = praw.Reddit(user_agent='LMGTFY (by /u/USERNAME)',
client_id='CLIENT_ID', client_secret='CLIENT_SECRET',
username='USERNAME', password='PASSWORD')

subreddit = reddit.subreddit('AskReddit')
reddit = praw.Reddit(
user_agent="LMGTFY (by /u/USERNAME)",
client_id="CLIENT_ID",
client_secret="CLIENT_SECRET",
username="USERNAME",
password="PASSWORD",
)

subreddit = reddit.subreddit("AskReddit")
for submission in subreddit.stream.submissions():
process_submission(submission)

Expand All @@ -27,11 +31,11 @@ def process_submission(submission):
if question_phrase in normalized_title:
url_title = quote_plus(submission.title)
reply_text = REPLY_TEMPLATE.format(url_title)
print('Replying to: {}'.format(submission.title))
print("Replying to: {}".format(submission.title))
submission.reply(reply_text)
# A reply has been made so do not attempt to match other phrases.
break


if __name__ == '__main__':
if __name__ == "__main__":
main()
95 changes: 57 additions & 38 deletions docs/examples/obtain_refresh_token.py
Expand Up @@ -23,7 +23,7 @@ def receive_connection():
"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('localhost', 8080))
server.bind(("localhost", 8080))
server.listen(1)
client = server.accept()[0]
server.close()
Expand All @@ -33,57 +33,76 @@ def receive_connection():
def send_message(client, message):
"""Send message to client and close the connection."""
print(message)
client.send('HTTP/1.1 200 OK\r\n\r\n{}'.format(message).encode('utf-8'))
client.send("HTTP/1.1 200 OK\r\n\r\n{}".format(message).encode("utf-8"))
client.close()


def main():
"""Provide the program's entry point when directly executed."""
print('Go here while logged into the account you want to create a '
'token for: https://www.reddit.com/prefs/apps/')
print('Click the create an app button. Put something in the name '
'field and select the script radio button.')
print('Put http://localhost:8080 in the redirect uri field and '
'click create app')
client_id = input('Enter the client ID, it\'s the line just under '
'Personal use script at the top: ')
client_secret = input('Enter the client secret, it\'s the line next '
'to secret: ')
commaScopes = input('Now enter a comma separated list of scopes, or '
'all for all tokens: ')

if commaScopes.lower() == 'all':
scopes = ['*']
print(
"Go here while logged into the account you want to create a "
"token for: https://www.reddit.com/prefs/apps/"
)
print(
"Click the create an app button. Put something in the name "
"field and select the script radio button."
)
print(
"Put http://localhost:8080 in the redirect uri field and "
"click create app"
)
client_id = input(
"Enter the client ID, it's the line just under "
"Personal use script at the top: "
)
client_secret = input(
"Enter the client secret, it's the line next " "to secret: "
)
commaScopes = input(
"Now enter a comma separated list of scopes, or "
"all for all tokens: "
)

if commaScopes.lower() == "all":
scopes = ["*"]
else:
scopes = commaScopes.strip().split(',')

reddit = praw.Reddit(client_id=client_id.strip(),
client_secret=client_secret.strip(),
redirect_uri='http://localhost:8080',
user_agent='praw_refresh_token_example')
scopes = commaScopes.strip().split(",")

reddit = praw.Reddit(
client_id=client_id.strip(),
client_secret=client_secret.strip(),
redirect_uri="http://localhost:8080",
user_agent="praw_refresh_token_example",
)
state = str(random.randint(0, 65000))
url = reddit.auth.url(scopes, state, 'permanent')
print('Now open this url in your browser: '+url)
url = reddit.auth.url(scopes, state, "permanent")
print("Now open this url in your browser: " + url)
sys.stdout.flush()

client = receive_connection()
data = client.recv(1024).decode('utf-8')
param_tokens = data.split(' ', 2)[1].split('?', 1)[1].split('&')
params = {key: value for (key, value) in [token.split('=')
for token in param_tokens]}

if state != params['state']:
send_message(client, 'State mismatch. Expected: {} Received: {}'
.format(state, params['state']))
data = client.recv(1024).decode("utf-8")
param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
params = {
key: value
for (key, value) in [token.split("=") for token in param_tokens]
}

if state != params["state"]:
send_message(
client,
"State mismatch. Expected: {} Received: {}".format(
state, params["state"]
),
)
return 1
elif 'error' in params:
send_message(client, params['error'])
elif "error" in params:
send_message(client, params["error"])
return 1

refresh_token = reddit.auth.authorize(params['code'])
send_message(client, 'Refresh token: {}'.format(refresh_token))
refresh_token = reddit.auth.authorize(params["code"])
send_message(client, "Refresh token: {}".format(refresh_token))
return 0


if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main())
62 changes: 39 additions & 23 deletions praw/config.py
Expand Up @@ -14,7 +14,7 @@ def __bool__(self):
__nonzero__ = __bool__

def __str__(self):
return 'NotSet'
return "NotSet"


class Config(object):
Expand All @@ -28,32 +28,32 @@ class Config(object):
def _config_boolean(item):
if isinstance(item, bool):
return item
return item.lower() in {'1', 'yes', 'true', 'on'}
return item.lower() in {"1", "yes", "true", "on"}

@classmethod
def _load_config(cls):
"""Attempt to load settings from various praw.ini files."""
config = configparser.RawConfigParser()
module_dir = os.path.dirname(sys.modules[__name__].__file__)
if 'APPDATA' in os.environ: # Windows
os_config_path = os.environ['APPDATA']
elif 'XDG_CONFIG_HOME' in os.environ: # Modern Linux
os_config_path = os.environ['XDG_CONFIG_HOME']
elif 'HOME' in os.environ: # Legacy Linux
os_config_path = os.path.join(os.environ['HOME'], '.config')
if "APPDATA" in os.environ: # Windows
os_config_path = os.environ["APPDATA"]
elif "XDG_CONFIG_HOME" in os.environ: # Modern Linux
os_config_path = os.environ["XDG_CONFIG_HOME"]
elif "HOME" in os.environ: # Legacy Linux
os_config_path = os.path.join(os.environ["HOME"], ".config")
else:
os_config_path = None
locations = [os.path.join(module_dir, 'praw.ini'), 'praw.ini']
locations = [os.path.join(module_dir, "praw.ini"), "praw.ini"]
if os_config_path is not None:
locations.insert(1, os.path.join(os_config_path, 'praw.ini'))
locations.insert(1, os.path.join(os_config_path, "praw.ini"))
config.read(locations)
cls.CONFIG = config

@property
def short_url(self):
"""Return the short url or raise a ClientException when not set."""
if self._short_url is self.CONFIG_NOT_SET:
raise ClientException('No short domain specified.')
raise ClientException("No short domain specified.")
return self._short_url

def __init__(self, site_name, **settings):
Expand Down Expand Up @@ -85,25 +85,41 @@ def _fetch_or_not_set(self, key):
if key in self._settings: # Passed in values have the highest priority
return self._fetch(key)

env_value = os.getenv('praw_{}'.format(key))
env_value = os.getenv("praw_{}".format(key))
ini_value = self._fetch_default(key) # Needed to remove from custom

# Environment variables have higher priority than praw.ini settings
return env_value or ini_value or self.CONFIG_NOT_SET

def _initialize_attributes(self):
self._short_url = self._fetch_default('short_url') \
or self.CONFIG_NOT_SET
self._short_url = (
self._fetch_default("short_url") or self.CONFIG_NOT_SET
)
self.check_for_updates = self._config_boolean(
self._fetch_or_not_set('check_for_updates'))
self.kinds = {x: self._fetch('{}_kind'.format(x)) for x in
['comment', 'message', 'redditor', 'submission',
'subreddit', 'trophy']}

for attribute in ('client_id', 'client_secret', 'redirect_uri',
'refresh_token', 'password', 'user_agent',
'username'):
self._fetch_or_not_set("check_for_updates")
)
self.kinds = {
x: self._fetch("{}_kind".format(x))
for x in [
"comment",
"message",
"redditor",
"submission",
"subreddit",
"trophy",
]
}

for attribute in (
"client_id",
"client_secret",
"redirect_uri",
"refresh_token",
"password",
"user_agent",
"username",
):
setattr(self, attribute, self._fetch_or_not_set(attribute))

for required_attribute in ('oauth_url', 'reddit_url'):
for required_attribute in ("oauth_url", "reddit_url"):
setattr(self, required_attribute, self._fetch(required_attribute))

0 comments on commit 60d87d6

Please sign in to comment.