Back to index

python3.2  3.2.2
Classes | Functions | Variables
nntplib Namespace Reference

Classes

class  NNTPError
class  NNTPReplyError
class  NNTPTemporaryError
class  NNTPPermanentError
class  NNTPProtocolError
class  NNTPDataError
class  _NNTPBase
class  NNTP
class  NNTP_SSL

Functions

def decode_header
def _parse_overview_fmt
def _parse_overview
def _parse_datetime
def _unparse_datetime
def _encrypt_on
def cut

Variables

 _have_ssl = False
list __all__
int NNTP_PORT = 119
int NNTP_SSL_PORT = 563
dictionary _LONGRESP
list _DEFAULT_OVERVIEW_FMT
dictionary _OVERVIEW_FMT_ALTERNATIVES
string _CRLF = '\r\n'
tuple GroupInfo
tuple ArticleInfo
tuple parser
string help = 'group to fetch messages from (default: %(default)s)'
tuple args = parser.parse_args()
 port = args.port
tuple s = NNTP(host=args.server, port=port)
tuple caps = s.getcapabilities()
tuple first = str(int(last) - args.nb_articles + 1)
tuple author = decode_header(over['from'])
tuple subject = decode_header(over['subject'])
tuple lines = int(over[':lines'])

Detailed Description

An NNTP client class based on:
- RFC 977: Network News Transfer Protocol
- RFC 2980: Common NNTP Extensions
- RFC 3977: Network News Transfer Protocol (version 2)

Example:

>>> from nntplib import NNTP
>>> s = NNTP('news')
>>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
Group comp.lang.python has 51 articles, range 5770 to 5821
>>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last))
>>> resp = s.quit()
>>>

Here 'resp' is the server response line.
Error responses are turned into exceptions.

To post an article from a file:
>>> f = open(filename, 'rb') # file containing article, including header
>>> resp = s.post(f)
>>>

For descriptions of all methods, read the comments in the code below.
Note that all arguments and return values representing article numbers
are strings, not numbers, since they are rarely used for calculations.

Function Documentation

def nntplib._encrypt_on (   sock,
  context 
) [private]
Wrap a socket in SSL/TLS. Arguments:
- sock: Socket to wrap
- context: SSL context to use for the encrypted connection
Returns:
- sock: New, encrypted socket.

Definition at line 275 of file nntplib.py.

00275 
00276     def _encrypt_on(sock, context):
00277         """Wrap a socket in SSL/TLS. Arguments:
00278         - sock: Socket to wrap
00279         - context: SSL context to use for the encrypted connection
00280         Returns:
00281         - sock: New, encrypted socket.
00282         """
00283         # Generate a default SSL context if none was passed.
00284         if context is None:
00285             context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
00286             # SSLv2 considered harmful.
00287             context.options |= ssl.OP_NO_SSLv2
00288         return context.wrap_socket(sock)
00289 
00290 
# The classes themselves
def nntplib._parse_datetime (   date_str,
  time_str = None 
) [private]
Parse a pair of (date, time) strings, and return a datetime object.
If only the date is given, it is assumed to be date and time
concatenated together (e.g. response to the DATE command).

Definition at line 225 of file nntplib.py.

00225 
00226 def _parse_datetime(date_str, time_str=None):
00227     """Parse a pair of (date, time) strings, and return a datetime object.
00228     If only the date is given, it is assumed to be date and time
00229     concatenated together (e.g. response to the DATE command).
00230     """
00231     if time_str is None:
00232         time_str = date_str[-6:]
00233         date_str = date_str[:-6]
00234     hours = int(time_str[:2])
00235     minutes = int(time_str[2:4])
00236     seconds = int(time_str[4:])
00237     year = int(date_str[:-4])
00238     month = int(date_str[-4:-2])
00239     day = int(date_str[-2:])
00240     # RFC 3977 doesn't say how to interpret 2-char years.  Assume that
00241     # there are no dates before 1970 on Usenet.
00242     if year < 70:
00243         year += 2000
00244     elif year < 100:
00245         year += 1900
00246     return datetime.datetime(year, month, day, hours, minutes, seconds)

Here is the caller graph for this function:

def nntplib._parse_overview (   lines,
  fmt,
  data_process_func = None 
) [private]
Parse the response to a OVER or XOVER command according to the
overview format `fmt`.

Definition at line 196 of file nntplib.py.

00196 
00197 def _parse_overview(lines, fmt, data_process_func=None):
00198     """Parse the response to a OVER or XOVER command according to the
00199     overview format `fmt`."""
00200     n_defaults = len(_DEFAULT_OVERVIEW_FMT)
00201     overview = []
00202     for line in lines:
00203         fields = {}
00204         article_number, *tokens = line.split('\t')
00205         article_number = int(article_number)
00206         for i, token in enumerate(tokens):
00207             if i >= len(fmt):
00208                 # XXX should we raise an error? Some servers might not
00209                 # support LIST OVERVIEW.FMT and still return additional
00210                 # headers.
00211                 continue
00212             field_name = fmt[i]
00213             is_metadata = field_name.startswith(':')
00214             if i >= n_defaults and not is_metadata:
00215                 # Non-default header names are included in full in the response
00216                 # (unless the field is totally empty)
00217                 h = field_name + ": "
00218                 if token and token[:len(h)].lower() != h:
00219                     raise NNTPDataError("OVER/XOVER response doesn't include "
00220                                         "names of additional headers")
00221                 token = token[len(h):] if token else None
00222             fields[fmt[i]] = token
00223         overview.append((article_number, fields))
00224     return overview

Here is the call graph for this function:

Here is the caller graph for this function:

def nntplib._parse_overview_fmt (   lines) [private]
Parse a list of string representing the response to LIST OVERVIEW.FMT
and return a list of header/metadata names.
Raises NNTPDataError if the response is not compliant
(cf. RFC 3977, section 8.4).

Definition at line 171 of file nntplib.py.

00171 
00172 def _parse_overview_fmt(lines):
00173     """Parse a list of string representing the response to LIST OVERVIEW.FMT
00174     and return a list of header/metadata names.
00175     Raises NNTPDataError if the response is not compliant
00176     (cf. RFC 3977, section 8.4)."""
00177     fmt = []
00178     for line in lines:
00179         if line[0] == ':':
00180             # Metadata name (e.g. ":bytes")
00181             name, _, suffix = line[1:].partition(':')
00182             name = ':' + name
00183         else:
00184             # Header name (e.g. "Subject:" or "Xref:full")
00185             name, _, suffix = line.partition(':')
00186         name = name.lower()
00187         name = _OVERVIEW_FMT_ALTERNATIVES.get(name, name)
00188         # Should we do something with the suffix?
00189         fmt.append(name)
00190     defaults = _DEFAULT_OVERVIEW_FMT
00191     if len(fmt) < len(defaults):
00192         raise NNTPDataError("LIST OVERVIEW.FMT response too short")
00193     if fmt[:len(defaults)] != defaults:
00194         raise NNTPDataError("LIST OVERVIEW.FMT redefines default fields")
00195     return fmt

Here is the caller graph for this function:

def nntplib._unparse_datetime (   dt,
  legacy = False 
) [private]
Format a date or datetime object as a pair of (date, time) strings
in the format required by the NEWNEWS and NEWGROUPS commands.  If a
date object is passed, the time is assumed to be midnight (00h00).

The returned representation depends on the legacy flag:
* if legacy is False (the default):
  date has the YYYYMMDD format and time the HHMMSS format
* if legacy is True:
  date has the YYMMDD format and time the HHMMSS format.
RFC 3977 compliant servers should understand both formats; therefore,
legacy is only needed when talking to old servers.

Definition at line 247 of file nntplib.py.

00247 
00248 def _unparse_datetime(dt, legacy=False):
00249     """Format a date or datetime object as a pair of (date, time) strings
00250     in the format required by the NEWNEWS and NEWGROUPS commands.  If a
00251     date object is passed, the time is assumed to be midnight (00h00).
00252 
00253     The returned representation depends on the legacy flag:
00254     * if legacy is False (the default):
00255       date has the YYYYMMDD format and time the HHMMSS format
00256     * if legacy is True:
00257       date has the YYMMDD format and time the HHMMSS format.
00258     RFC 3977 compliant servers should understand both formats; therefore,
00259     legacy is only needed when talking to old servers.
00260     """
00261     if not isinstance(dt, datetime.datetime):
00262         time_str = "000000"
00263     else:
00264         time_str = "{0.hour:02d}{0.minute:02d}{0.second:02d}".format(dt)
00265     y = dt.year
00266     if legacy:
00267         y = y % 100
00268         date_str = "{0:02d}{1.month:02d}{1.day:02d}".format(y, dt)
00269     else:
00270         date_str = "{0:04d}{1.month:02d}{1.day:02d}".format(y, dt)
00271     return date_str, time_str
00272 

Here is the caller graph for this function:

def nntplib.cut (   s,
  lim 
)

Definition at line 1086 of file nntplib.py.

01086 
01087     def cut(s, lim):
01088         if len(s) > lim:
01089             s = s[:lim - 4] + "..."
01090         return s

def nntplib.decode_header (   header_str)
Takes an unicode string representing a munged header value
and decodes it as a (possibly non-ASCII) readable value.

Definition at line 160 of file nntplib.py.

00160 
00161 def decode_header(header_str):
00162     """Takes an unicode string representing a munged header value
00163     and decodes it as a (possibly non-ASCII) readable value."""
00164     parts = []
00165     for v, enc in _email_decode_header(header_str):
00166         if isinstance(v, bytes):
00167             parts.append(v.decode(enc or 'ascii'))
00168         else:
00169             parts.append(v)
00170     return ' '.join(parts)

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ["NNTP",
00002            "NNTPReplyError", "NNTPTemporaryError", "NNTPPermanentError",
00003            "NNTPProtocolError", "NNTPDataError",
00004            "decode_header",
00005            ]

Definition at line 82 of file nntplib.py.

Definition at line 150 of file nntplib.py.

Initial value:
00001 [
00002     "subject", "from", "date", "message-id", "references", ":bytes", ":lines"]

Definition at line 140 of file nntplib.py.

Definition at line 75 of file nntplib.py.

Initial value:
00001 {
00002     '100',   # HELP
00003     '101',   # CAPABILITIES
00004     '211',   # LISTGROUP   (also not multi-line with GROUP)
00005     '215',   # LIST
00006     '220',   # ARTICLE
00007     '221',   # HEAD, XHDR
00008     '222',   # BODY
00009     '224',   # OVER, XOVER
00010     '225',   # HDR
00011     '230',   # NEWNEWS
00012     '231',   # NEWGROUPS
00013     '282',   # XGTITLE
00014 }

Definition at line 124 of file nntplib.py.

Initial value:
00001 {
00002     'bytes': ':bytes',
00003     'lines': ':lines',
00004 }

Definition at line 144 of file nntplib.py.

tuple nntplib.args = parser.parse_args()

Definition at line 1068 of file nntplib.py.

Initial value:
00001 collections.namedtuple('ArticleInfo',
00002                                      ['number', 'message_id', 'lines'])

Definition at line 155 of file nntplib.py.

tuple nntplib.author = decode_header(over['from'])

Definition at line 1094 of file nntplib.py.

tuple nntplib.caps = s.getcapabilities()

Definition at line 1080 of file nntplib.py.

tuple nntplib.first = str(int(last) - args.nb_articles + 1)

Definition at line 1091 of file nntplib.py.

Initial value:
00001 collections.namedtuple('GroupInfo',
00002                                    ['group', 'last', 'first', 'flag'])

Definition at line 152 of file nntplib.py.

string nntplib.help = 'group to fetch messages from (default: %(default)s)'

Definition at line 1059 of file nntplib.py.

tuple nntplib.lines = int(over[':lines'])

Definition at line 1096 of file nntplib.py.

Definition at line 120 of file nntplib.py.

Definition at line 121 of file nntplib.py.

Initial value:
00001 argparse.ArgumentParser(description="""\
00002         nntplib built-in demo - display the latest articles in a newsgroup""")

Definition at line 1056 of file nntplib.py.

nntplib.port = args.port

Definition at line 1070 of file nntplib.py.

tuple nntplib.s = NNTP(host=args.server, port=port)

Definition at line 1074 of file nntplib.py.

Definition at line 1095 of file nntplib.py.