File: site-forward.py

#!/usr/bin/python
"""
================================================================================
Create forward-link redirection pages for relocating a web site.
Generates one page for every existing site html file; upload the generated
files to your old web site.  See ftplib later in the book for ways to run
site uploads in scripts either after or during page file creation.

Added March 2014: 2.X compatibility, copy extra tools files at the end.
Added October 2015: make .html files for non .html items too, for servers
that support -- a x.jpg access may open a x.jpg.html file on some servers.
================================================================================
"""

from __future__ import print_function

import os, time
servername   = 'learning-python.com'      # where site is relocating to
homedir      = 'books'                    # where site will be rooted
templatename = 'template.html'            # template for generated pages
datestr      = time.strftime('%b-%d-%Y')  # mon-dd-yyyy, or time.asctime()?

REDIRECTALL = True  # make redirects for all, not just .html/.htm files (Oct15)

# where site files live locally
sitefilesdir = r'C:\MARKS-STUFF\Websites\Books\current-site-feb1814'
# where to store forward files
uploaddir    = r'C:\MARKS-STUFF\Websites\Books\forward-site-oct2615'

try:
    os.mkdir(uploaddir)                  # make upload dir if needed
except OSError: pass

template  = open(templatename).read()    # load or import template text
sitefiles = os.listdir(sitefilesdir)     # filenames, no directory prefix

count = 0
for filename in sitefiles:
    if not os.path.isfile(os.path.join(sitefilesdir, filename)):
        print('**skipping dir or non-file:', filename)
    else:
        if filename.endswith(('.html','.htm')) or REDIRECTALL:
            fwdname = os.path.join(uploaddir, filename)
            if not filename.endswith(('.html', '.htm')):
                fwdname += '.html'
            print('relocating', filename, 'via', fwdname)

            filetext = template.replace('$server$', servername)   # insert text
            filetext = filetext.replace('$home$',   homedir)      # and write
            filetext = filetext.replace('$file$',   filename)     # file varies
            filetext = filetext.replace('$date$',   datestr)      # if date used
            open(fwdname, 'w').write(filetext)
            count += 1

print('Last file =>\n', filetext, sep='')
print('Done:', count, 'forward files created.')

# copy files here to upload dir too: favicon, images, etc. (Mar14)
for extrahere in os.listdir('.'):
    to = os.path.join(uploaddir, extrahere)
    open(to, 'wb').write( open(extrahere, 'rb').read() )      # nothing fancy
    print('Copied extras file to:', to)



[Home] Books Programs Blog Python Author Training Search Email ©M.Lutz