client-side library tools for transferring and processing information over the Internet,
but it’s not at all complete.
A more or less comprehensive list of Python’s Internet-related modules appears at the
start of the previous chapter. Among other things, Python also includes client-side
support libraries for Internet news, Telnet, HTTP, XML-RPC, and other standard pro-
tocols. Most of these are analogous to modules we’ve already met—they provide an
object-based interface that automates the underlying sockets and message structures.
For instance, Python’s nntplib module supports the client-side interface to NNTP—
the Network News Transfer Protocol—which is used for reading and posting articles
to Usenet newsgroups on the Internet. Like other protocols, NNTP runs on top of
sockets and merely defines a standard message protocol; like other modules, nntplib
hides most of the protocol details and presents an object-based interface to Python
scripts.
We won’t get into full protocol details here, but in brief, NNTP servers store a range
of articles on the server machine, usually in a flat-file database. If you have the domain
or IP name of a server machine that runs an NNTP server program listening on the
NNTP port, you can write scripts that fetch or post articles from any machine that has
Python and an Internet connection. For instance, the script in Example 13-28 by default
fetches and displays the last 10 articles from Python’s Internet newsgroup,
comp.lang.python, from the news.rmi.net NNTP server at one of my ISPs.
Example 13-28. PP4E\Internet\Other\readnews.py
"""
fetch and print usenet newsgroup posting from comp.lang.python via the
nntplib module, which really runs on top of sockets; nntplib also supports
posting new messages, etc.; note: posts not deleted after they are read;
"""
listonly = False
showhdrs = ['From', 'Subject', 'Date', 'Newsgroups', 'Lines']
try:
import sys
servername, groupname, showcount = sys.argv[1:]
showcount = int(showcount)
except:
servername = nntpconfig.servername # assign this to your server
groupname = 'comp.lang.python' # cmd line args or defaults
showcount = 10 # show last showcount posts
connect to nntp server
print('Connecting to', servername, 'for', groupname)
from nntplib import NNTP
connection = NNTP(servername)
(reply, count, first, last, name) = connection.group(groupname)
print('%s has %s articles: %s-%s' % (name, count, first, last))
get request headers only
fetchfrom = str(int(last) - (showcount-1))
992 | Chapter 13: Client-Side Scripting