INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Select user flair or link flair on subreddits.
def select_flair(self, item, flair_template_id='', flair_text=''): """Select user flair or link flair on subreddits. This can only be used for assigning your own name flair or link flair on your own submissions. For assigning other's flairs using moderator access, see :meth:`~praw.__ini...
Set the credentials used for OAuth2 authentication.
def set_access_credentials(self, scope, access_token, refresh_token=None, update_user=True): """Set the credentials used for OAuth2 authentication. Calling this function will overwrite any currently existing access credentials. :param scope: A set of redd...
Create a new subreddit.
def create_subreddit(self, name, title, description='', language='en', subreddit_type='public', content_options='any', over_18=False, default_set=True, show_media=False, domain='', wikimode='disabled', captcha=None, **kw...
Delete an image from the subreddit.
def delete_image(self, subreddit, name=None, header=False): """Delete an image from the subreddit. :param name: The name of the image if removing a CSS image. :param header: When true, delete the subreddit header. :returns: The json response from the server. """ subredd...
Set the settings for the given subreddit.
def set_settings(self, subreddit, title, public_description='', description='', language='en', subreddit_type='public', content_options='any', over_18=False, default_set=True, show_media=False, domain='', domain_css=False, domain_sideba...
Set stylesheet for the given subreddit.
def set_stylesheet(self, subreddit, stylesheet): """Set stylesheet for the given subreddit. :returns: The json response from the server. """ subreddit = six.text_type(subreddit) data = {'r': subreddit, 'stylesheet_contents': stylesheet, 'op': 'sa...
Upload an image to the subreddit.
def upload_image(self, subreddit, image_path, name=None, header=False, upload_as=None): """Upload an image to the subreddit. :param image_path: A path to the jpg or png image you want to upload. :param name: The name to provide the image. When None the name will be ...
Update only the given settings for the given subreddit.
def update_settings(self, subreddit, **kwargs): """Update only the given settings for the given subreddit. The settings to update must be given by keyword and match one of the parameter names in `set_settings`. :returns: The json response from the server. """ settings ...
Add a flair template to the given subreddit.
def add_flair_template(self, subreddit, text='', css_class='', text_editable=False, is_link=False): """Add a flair template to the given subreddit. :returns: The json response from the server. """ data = {'r': six.text_type(subreddit), 'text':...
Clear flair templates for the given subreddit.
def clear_flair_templates(self, subreddit, is_link=False): """Clear flair templates for the given subreddit. :returns: The json response from the server. """ data = {'r': six.text_type(subreddit), 'flair_type': 'LINK_FLAIR' if is_link else 'USER_FLAIR'} return s...
Configure the flair setting for the given subreddit.
def configure_flair(self, subreddit, flair_enabled=False, flair_position='right', flair_self_assign=False, link_flair_enabled=False, link_flair_position='left', link_flair_self_assign=False): ...
Delete the flair for the given user on the given subreddit.
def delete_flair(self, subreddit, user): """Delete the flair for the given user on the given subreddit. :returns: The json response from the server. """ data = {'r': six.text_type(subreddit), 'name': six.text_type(user)} return self.request_json(self.config['del...
Return a get_content generator of flair mappings.
def get_flair_list(self, subreddit, *args, **kwargs): """Return a get_content generator of flair mappings. :param subreddit: Either a Subreddit object or the name of the subreddit to return the flair list for. The additional parameters are passed directly into :meth:`.get_c...
Set flair for the user in the given subreddit.
def set_flair(self, subreddit, item, flair_text='', flair_css_class=''): """Set flair for the user in the given subreddit. `item` can be a string, Redditor object, or Submission object. If `item` is a string it will be treated as the name of a Redditor. This method can only be called b...
Set flair for a group of users in the given subreddit.
def set_flair_csv(self, subreddit, flair_mapping): """Set flair for a group of users in the given subreddit. flair_mapping should be a list of dictionaries with the following keys: `user`: the user name, `flair_text`: the flair text for the user (optional), `flair_css_clas...
Return a get_content generator for moderation log items.
def get_mod_log(self, subreddit, mod=None, action=None, *args, **kwargs): """Return a get_content generator for moderation log items. :param subreddit: Either a Subreddit object or the name of the subreddit to return the modlog for. :param mod: If given, only return the actions made...
Return a get_content generator of banned users for the subreddit.
def get_banned(self, subreddit, user_only=True, *args, **kwargs): """Return a get_content generator of banned users for the subreddit. :param subreddit: The subreddit to get the banned user list for. :param user_only: When False, the generator yields a dictionary of data associated ...
Return a get_content generator of contributors for the given subreddit.
def get_contributors(self, subreddit, *args, **kwargs): """ Return a get_content generator of contributors for the given subreddit. If it's a public subreddit, then authentication as a moderator of the subreddit is required. For protected/private subreddits only access is requir...
Return a get_content generator of edited items.
def get_edited(self, subreddit='mod', *args, **kwargs): """Return a get_content generator of edited items. :param subreddit: Either a Subreddit object or the name of the subreddit to return the edited items for. Defaults to `mod` which includes items for all the subreddits you m...
Return the stylesheet and images for the given subreddit.
def get_stylesheet(self, subreddit, **params): """Return the stylesheet and images for the given subreddit.""" url = self.config['stylesheet'].format( subreddit=six.text_type(subreddit)) return self.request_json(url, params=params)['data']
Abdicate moderator status in a subreddit. Use with care.
def leave_moderator(self, subreddit): """Abdicate moderator status in a subreddit. Use with care. :param subreddit: The name of the subreddit to leave `status` from. :returns: the json response from the server. """ self.evict(self.config['my_mod_subreddits']) return sel...
Abdicate status in a subreddit.
def _leave_status(self, subreddit, statusurl): """Abdicate status in a subreddit. :param subreddit: The name of the subreddit to leave `status` from. :param statusurl: The API URL which will be used in the leave request. Please use :meth:`leave_contributor` or :meth:`leave_moderator...
Copy a multireddit.
def copy_multireddit(self, from_redditor, from_name, to_name=None, *args, **kwargs): """Copy a multireddit. :param from_redditor: The username or Redditor object for the user who owns the original multireddit :param from_name: The name of the multireddit, be...
Create a new multireddit.
def create_multireddit(self, name, description_md=None, icon_name=None, key_color=None, subreddits=None, visibility=None, weighting_scheme=None, overwrite=False, *args, **kwargs): # pylint: disable=W0613 """Create a new multireddi...
Delete a Multireddit.
def delete_multireddit(self, name, *args, **kwargs): """Delete a Multireddit. Any additional parameters are passed directly into :meth:`~praw.__init__.BaseReddit.request` """ url = self.config['multireddit_about'].format(user=self.user.name, ...
Edit a multireddit or create one if it doesn t already exist.
def edit_multireddit(self, *args, **kwargs): """Edit a multireddit, or create one if it doesn't already exist. See :meth:`create_multireddit` for accepted parameters. """ return self.create_multireddit(*args, overwrite=True, **kwargs)
Return a Multireddit object for the author and name specified.
def get_multireddit(self, redditor, multi, *args, **kwargs): """Return a Multireddit object for the author and name specified. :param redditor: The username or Redditor object of the user who owns the multireddit. :param multi: The name of the multireddit to fetch. The addi...
Return a list of multireddits belonging to a redditor.
def get_multireddits(self, redditor, *args, **kwargs): """Return a list of multireddits belonging to a redditor. :param redditor: The username or Redditor object to find multireddits from. :returns: The json response from the server The additional parameters are passed dire...
Rename a Multireddit.
def rename_multireddit(self, current_name, new_name, *args, **kwargs): """Rename a Multireddit. :param current_name: The name of the multireddit to rename :param new_name: The new name to assign to this multireddit The additional parameters are passed directly into :meth:`~praw...
Return a get_content generator of subreddits.
def get_my_contributions(self, *args, **kwargs): """Return a get_content generator of subreddits. The Subreddits generated are those where the session's user is a contributor. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter can...
Return a get_content generator of subreddits.
def get_my_moderation(self, *args, **kwargs): """Return a get_content generator of subreddits. The Subreddits generated are those where the session's user is a moderator. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot b...
Return a get_content generator of subreddits.
def get_my_subreddits(self, *args, **kwargs): """Return a get_content generator of subreddits. The subreddits generated are those that hat the session's user is subscribed to. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter can...
Mark each of the supplied thing_ids as ( un ) read.
def _mark_as_read(self, thing_ids, unread=False): """Mark each of the supplied thing_ids as (un)read. :returns: The json response from the server. """ data = {'id': ','.join(thing_ids)} key = 'unread_message' if unread else 'read_message' response = self.request_json(se...
Return a get_content generator for inboxed comment replies.
def get_comment_replies(self, *args, **kwargs): """Return a get_content generator for inboxed comment replies. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ return self.get_content(self.config['comment_...
Return a get_content generator for inbox ( messages and comments ).
def get_inbox(self, *args, **kwargs): """Return a get_content generator for inbox (messages and comments). The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ return self.get_content(self.config['inbox'], *ar...
Return a Message object corresponding to the given ID.
def get_message(self, message_id, *args, **kwargs): """Return a Message object corresponding to the given ID. :param message_id: The ID or Fullname for a Message The additional parameters are passed directly into :meth:`~praw.objects.Message.from_id` of Message, and subsequently into ...
Return a get_content generator for inbox ( messages only ).
def get_messages(self, *args, **kwargs): """Return a get_content generator for inbox (messages only). The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ return self.get_content(self.config['messages'], *args...
Return a get_content generator for inboxed submission replies.
def get_post_replies(self, *args, **kwargs): """Return a get_content generator for inboxed submission replies. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ return self.get_content(self.config['post_rep...
Return a get_content generator for sent messages.
def get_sent(self, *args, **kwargs): """Return a get_content generator for sent messages. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ return self.get_content(self.config['sent'], *args, **kwargs)
Return a get_content generator for unread messages.
def get_unread(self, unset_has_mail=False, update_user=False, *args, **kwargs): """Return a get_content generator for unread messages. :param unset_has_mail: When True, clear the has_mail flag (orangered) for the user. :param update_user: If both `unset_has_mail` ...
Return a get_content generator for username mentions.
def get_mentions(self, *args, **kwargs): """Return a get_content generator for username mentions. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ return self.get_content(self.config['mentions'], *args, **...
Send a message to a redditor or a subreddit s moderators ( mod mail ).
def send_message(self, recipient, subject, message, from_sr=None, captcha=None, **kwargs): """Send a message to a redditor or a subreddit's moderators (mod mail). :param recipient: A Redditor or Subreddit instance to send a message to. A string can also be used in which...
Hide one or multiple objects in the context of the logged in user.
def hide(self, thing_id, _unhide=False): """Hide one or multiple objects in the context of the logged in user. :param thing_id: A single fullname or list of fullnames, representing objects which will be hidden. :param _unhide: If True, unhide the object(s) instead. Use :...
Comment on the given thing with the given text.
def _add_comment(self, thing_id, text): """Comment on the given thing with the given text. :returns: A Comment object for the newly created comment. """ def add_comment_helper(self, thing_id, text): data = {'thing_id': thing_id, 'text': text} ...
Submit a new link to the given subreddit.
def submit(self, subreddit, title, text=None, url=None, captcha=None, save=None, send_replies=None, resubmit=None, **kwargs): """Submit a new link to the given subreddit. Accepts either a Subreddit object or a str containing the subreddit's display name. :param resubmit:...
Subscribe to the given subreddit.
def subscribe(self, subreddit, unsubscribe=False): """Subscribe to the given subreddit. :param subreddit: Either the subreddit name or a subreddit object. :param unsubscribe: When True, unsubscribe. :returns: The json response from the server. """ data = {'action': 'uns...
Some custom patches on top of the python webbrowser module to fix user reported bugs and limitations of the module.
def patch_webbrowser(): """ Some custom patches on top of the python webbrowser module to fix user reported bugs and limitations of the module. """ # https://bugs.python.org/issue31014 # https://github.com/michael-lazar/rtv/issues/588 def register_patch(name, klass, instance=None, update_tr...
Setup terminal and initialize curses. Most of this copied from curses. wrapper in order to convert the wrapper into a context manager.
def curses_session(): """ Setup terminal and initialize curses. Most of this copied from curses.wrapper in order to convert the wrapper into a context manager. """ try: # Curses must wait for some time after the Escape key is pressed to # check if it is the beginning of an escape se...
Move the cursor up or down by the given increment.
def move(self, direction, n_windows): """ Move the cursor up or down by the given increment. Params: direction (int): `1` will move the cursor down one item and `-1` will move the cursor up one item. n_windows (int): The number of items that are currently...
Move the page down ( positive direction ) or up ( negative direction ).
def move_page(self, direction, n_windows): """ Move the page down (positive direction) or up (negative direction). Paging down: The post on the bottom of the page becomes the post at the top of the page and the cursor is moved to the top. Paging up: T...
Flip the orientation of the page.
def flip(self, n_windows): """ Flip the orientation of the page. """ assert n_windows >= 0 self.page_index += (self.step * n_windows) self.cursor_index = n_windows self.inverted = not self.inverted self.top_item_height = None
Parse a key represented by a string and return its character code.
def parse(cls, key): """ Parse a key represented by a string and return its character code. """ try: if isinstance(key, int): return key elif re.match('[<]KEY_.*[>]', key): # Curses control character return getattr(...
Guess based on the file extension.
def get_mimetype(url): """ Guess based on the file extension. Args: url (text): Web url that was linked to by a reddit submission. Returns: modified_url (text): The url (or filename) that will be used when constructing the command to run. ...
Re - download all submissions and reset the page index
def refresh_content(self, order=None, name=None): """ Re-download all submissions and reset the page index """ order = order or self.content.order # Preserve the query if staying on the current page if name is None: query = self.content.query else: ...
Open a prompt to search the given subreddit
def search_subreddit(self, name=None): """ Open a prompt to search the given subreddit """ name = name or self.content.name query = self.term.prompt_input('Search {0}: '.format(name)) if not query: return with self.term.loader('Searching'): ...
If on a subreddit remember it and head back to the front page. If this was pressed on the front page go back to the last subreddit.
def show_frontpage(self): """ If on a subreddit, remember it and head back to the front page. If this was pressed on the front page, go back to the last subreddit. """ if self.content.name != '/r/front': target = '/r/front' self.toggled_subreddit = self.c...
Select the current submission to view posts.
def open_submission(self, url=None): """ Select the current submission to view posts. """ if url is None: data = self.get_selected_item() url = data['permalink'] if data.get('url_type') == 'selfpost': self.config.history.add(data['url_f...
Open a link with the webbrowser
def open_link(self): """ Open a link with the webbrowser """ data = self.get_selected_item() if data['url_type'] == 'selfpost': self.open_submission() elif data['url_type'] == 'x-post subreddit': self.refresh_content(order='ignore', name=data['xpo...
Post a new submission to the given subreddit.
def post_submission(self): """ Post a new submission to the given subreddit. """ # Check that the subreddit can be submitted to name = self.content.name if '+' in name or name in ('/r/all', '/r/front', '/r/me', '/u/saved'): self.term.show_notification("Can't p...
Re - download comments and reset the page index
def refresh_content(self, order=None, name=None): """ Re-download comments and reset the page index """ order = order or self.content.order url = name or self.content.name # Hack to allow an order specified in the name by prompt_subreddit() to # override the curr...
Toggle the selected comment tree between visible and hidden
def toggle_comment(self): """ Toggle the selected comment tree between visible and hidden """ current_index = self.nav.absolute_index self.content.toggle(current_index) # This logic handles a display edge case after a comment toggle. We # want to make sure that w...
Open the link contained in the selected item.
def open_link(self): """ Open the link contained in the selected item. If there is more than one link contained in the item, prompt the user to choose which link to open. """ data = self.get_selected_item() if data['type'] == 'Submission': link = self...
Open the selected item with the system s pager
def open_pager(self): """ Open the selected item with the system's pager """ n_rows, n_cols = self.term.stdscr.getmaxyx() if self.config['max_pager_cols'] is not None: n_cols = min(n_cols, self.config['max_pager_cols']) data = self.get_selected_item() ...
Open the selected comment with the URL viewer
def comment_urlview(self): """ Open the selected comment with the URL viewer """ data = self.get_selected_item() comment = data.get('body') or data.get('text') or data.get('url_full') if comment: self.term.open_urlview(comment) else: self.t...
Move the cursor up to the comment s parent. If the comment is top - level jump to the previous top - level comment.
def move_parent_up(self): """ Move the cursor up to the comment's parent. If the comment is top-level, jump to the previous top-level comment. """ cursor = self.nav.absolute_index if cursor > 0: level = max(self.content.get(cursor)['level'], 1) whi...
Jump to the next comment that s at the same level as the selected comment and shares the same parent.
def move_sibling_next(self): """ Jump to the next comment that's at the same level as the selected comment and shares the same parent. """ cursor = self.nav.absolute_index if cursor >= 0: level = self.content.get(cursor)['level'] try: ...
Return function to generate Redditor listings.
def _get_redditor_listing(subpath=''): """Return function to generate Redditor listings.""" def _listing(self, sort='new', time='all', *args, **kwargs): """Return a get_content generator for some RedditContentObject type. :param sort: Specify the sort order of the results if applicable ...
Return function to generate specific subreddit Submission listings.
def _get_sorter(subpath='', **defaults): """Return function to generate specific subreddit Submission listings.""" @restrict_access(scope='read') def _sorted(self, *args, **kwargs): """Return a get_content generator for some RedditContentObject type. The additional parameters are passed dir...
Return a function for relationship modification.
def _modify_relationship(relationship, unlink=False, is_sub=False): """Return a function for relationship modification. Used to support friending (user-to-user), as well as moderating, contributor creating, and banning (user-to-subreddit). """ # The API uses friend and unfriend to manage all of th...
Return a requests Request object that can be prepared.
def _prepare_request(reddit_session, url, params, data, auth, files, method=None): """Return a requests Request object that can be "prepared".""" # Requests using OAuth for authorization must switch to using the oauth # domain. if getattr(reddit_session, '_use_oauth', False): ...
Return the new url or None if there are no redirects.
def _raise_redirect_exceptions(response): """Return the new url or None if there are no redirects. Raise exceptions if appropriate. """ if response.status_code not in [301, 302, 307]: return None new_url = urljoin(response.url, response.headers['location']) if 'reddits/search' in new_u...
Raise specific errors on some status codes.
def _raise_response_exceptions(response): """Raise specific errors on some status codes.""" if not response.ok and 'www-authenticate' in response.headers: msg = response.headers['www-authenticate'] if 'insufficient_scope' in msg: raise OAuthInsufficientScope('insufficient_scope', res...
Return an argument converted to a reddit - formatted list.
def _to_reddit_list(arg): """Return an argument converted to a reddit-formatted list. The returned format is a comma deliminated list. Each element is a string representation of an object. Either given as a string or as an object that is then converted to its string representation. """ if (isin...
Prompt user for captcha solution and return a prepared result.
def _get_captcha(reddit_session, captcha_id): """Prompt user for captcha solution and return a prepared result.""" url = urljoin(reddit_session.config['captcha'], captcha_id + '.png') sys.stdout.write('Captcha URL: {0}\nCaptcha: '.format(url)) sys.stdout.flush() raw = sys.stdin.rea...
Return a decorator that enforces API request limit guidelines.
def rate_limit(function): """Return a decorator that enforces API request limit guidelines. We are allowed to make a API request every api_request_delay seconds as specified in praw.ini. This value may differ from reddit to reddit. For reddit.com it is 2. Any function decorated with thi...
Responsible for dispatching the request and returning the result.
def request(self, request, proxies, timeout, verify, **_): """Responsible for dispatching the request and returning the result. Network level exceptions should be raised and only ``requests.Response`` should be returned. :param request: A ``requests.PreparedRequest`` object containing ...
Return a decorator that interacts with a handler s cache.
def with_cache(function): """Return a decorator that interacts with a handler's cache. This decorator must be applied to a DefaultHandler class method or instance method as it assumes `cache`, `ca_lock` and `timeouts` are available. """ @wraps(function) def wrap...
Remove items from cache matching URLs.
def evict(cls, urls): """Remove items from cache matching URLs. Return the number of items removed. """ if isinstance(urls, text_type): urls = [urls] urls = set(normalize_url(url) for url in urls) retval = 0 with cls.ca_lock: for key in l...
Send the request through the server and return the HTTP response.
def _relay(self, **kwargs): """Send the request through the server and return the HTTP response.""" retval = None delay_time = 2 # For connection retries read_attempts = 0 # For reading from socket while retval is None: # Evict can return False sock = socket.socket...
Attempt to load settings from various praw. ini files.
def _load_configuration(): """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 ...
Bind the theme s colors to curses s internal color pair map.
def bind_curses(self): """ Bind the theme's colors to curses's internal color pair map. This method must be called once (after curses has been initialized) before any element attributes can be accessed. Color codes and other special attributes will be mixed bitwise into a single...
Returns the curses attribute code for the given element.
def get(self, element, selected=False): """ Returns the curses attribute code for the given element. """ if self._attribute_map is None: raise RuntimeError('Attempted to access theme attribute before ' 'calling initialize_curses_theme()') ...
Compile all of the themes configuration files in the search path.
def list_themes(cls, path=THEMES): """ Compile all of the themes configuration files in the search path. """ themes, errors = [], OrderedDict() def load_themes(path, source): """ Load all themes in the given path. """ if os.path.is...
Prints a human - readable summary of the installed themes to stdout.
def print_themes(cls, path=THEMES): """ Prints a human-readable summary of the installed themes to stdout. This is intended to be used as a command-line utility, outside of the main curses display loop. """ themes, errors = cls.list_themes(path=path + '/') print...
Search for the given theme on the filesystem and attempt to load it.
def from_name(cls, name, path=THEMES): """ Search for the given theme on the filesystem and attempt to load it. Directories will be checked in a pre-determined order. If the name is provided as an absolute file path, it will be loaded directly. """ if os.path.isfile(nam...
Load a theme from the specified configuration file.
def from_file(cls, filename, source): """ Load a theme from the specified configuration file. Parameters: filename: The name of the filename to load. source: A description of where the theme was loaded from. """ _logger.info('Loading theme %s', filename) ...
Parse a single line from a theme file.
def _parse_line(cls, element, line, filename=None): """ Parse a single line from a theme file. Format: <element>: <foreground> <background> <attributes> """ items = line.split() if len(items) == 2: fg, bg, attrs = items[0], items[1], '' e...
Helper function used to set the fallback attributes of an element when they are defined by the configuration as None or -.
def _set_fallback(elements, src_field, fallback, dest_field=None): """ Helper function used to set the fallback attributes of an element when they are defined by the configuration as "None" or "-". """ if dest_field is None: dest_field = src_field if isinstan...
Converts hex RGB to the 6x6x6 xterm color space
def rgb_to_ansi(color): """ Converts hex RGB to the 6x6x6 xterm color space Args: color (str): RGB color string in the format "#RRGGBB" Returns: str: ansi color string in the format "ansi_n", where n is between 16 and 230 Reference: ...
Traverse the list in the given direction and return the next theme
def _step(self, theme, direction): """ Traverse the list in the given direction and return the next theme """ if not self.themes: self.reload() # Try to find the starting index key = (theme.source, theme.name) for i, val in enumerate(self.themes): ...
The entry point from the praw - multiprocess utility.
def run(): """The entry point from the praw-multiprocess utility.""" parser = OptionParser(version='%prog {0}'.format(__version__)) parser.add_option('-a', '--addr', default='localhost', help=('The address or host to listen on. Specify -a ' '0.0.0.0 to liste...
Mute tracebacks of common errors.
def handle_error(_, client_addr): """Mute tracebacks of common errors.""" exc_type, exc_value, _ = sys.exc_info() if exc_type is socket.error and exc_value[0] == 32: pass elif exc_type is cPickle.UnpicklingError: sys.stderr.write('Invalid connection from {0}\n' ...
Dispatch the actual request and return the result.
def do_request(self, request, proxies, timeout, **_): """Dispatch the actual request and return the result.""" print('{0} {1}'.format(request.method, request.url)) response = self.http.send(request, proxies=proxies, timeout=timeout, allow_redirects=False) ...
Parse the RPC make the call and pickle up the return value.
def handle(self): """Parse the RPC, make the call, and pickle up the return value.""" data = cPickle.load(self.rfile) # pylint: disable=E1101 method = data.pop('method') try: retval = getattr(self, 'do_{0}'.format(method))(**data) except Exception as e: #...
Copy a file from the repo to the user s home directory.
def _copy_settings_file(source, destination, name): """ Copy a file from the repo to the user's home directory. """ if os.path.exists(destination): try: ch = six.moves.input( 'File %s already exists, overwrite? y/[n]):' % destination) if ch not in ('Y', '...
Load settings from the command line.
def get_args(): """ Load settings from the command line. """ parser = build_parser() args = vars(parser.parse_args()) # Overwrite the deprecated "-l" option into the link variable if args['link_deprecated'] and args['link'] is None: args['link'] = ar...
Load settings from an rtv configuration file.
def get_file(cls, filename=None): """ Load settings from an rtv configuration file. """ if filename is None: filename = CONFIG config = configparser.ConfigParser() if os.path.exists(filename): with codecs.open(filename, encoding='utf-8') as fp: ...
Ensure that the directory exists before trying to write to the file.
def _ensure_filepath(filename): """ Ensure that the directory exists before trying to write to the file. """ filepath = os.path.dirname(filename) if not os.path.exists(filepath): os.makedirs(filepath)
Open the subscription and submission pages subwindows but close the current page if any other type of page is selected.
def handle_selected_page(self): """ Open the subscription and submission pages subwindows, but close the current page if any other type of page is selected. """ if not self.selected_page: pass if self.selected_page.name in ('subscription', 'submission'): ...
Mark the selected message or comment as seen.
def mark_seen(self): """ Mark the selected message or comment as seen. """ data = self.get_selected_item() if data['is_new']: with self.term.loader('Marking as read'): data['object'].mark_as_read() if not self.term.loader.exception: ...