~certify-web-dev/twisted/certify-trunk

« back to all changes in this revision

Viewing changes to twisted/web/tap.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2007-01-17 14:52:35 UTC
  • mfrom: (1.1.5 upstream) (2.1.2 etch)
  • Revision ID: james.westby@ubuntu.com-20070117145235-btmig6qfmqfen0om
Tags: 2.5.0-0ubuntu1
New upstream version, compatible with python2.5.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
 
3
# See LICENSE for details.
 
4
 
 
5
 
 
6
"""I am the support module for creating web servers with 'mktap'
 
7
"""
 
8
 
 
9
import string, os
 
10
 
 
11
# Twisted Imports
 
12
from twisted.web import server, static, twcgi, script, demo, distrib, trp
 
13
from twisted.internet import interfaces
 
14
from twisted.python import usage, reflect
 
15
from twisted.spread import pb
 
16
from twisted.application import internet, service, strports
 
17
 
 
18
 
 
19
class Options(usage.Options):
 
20
    synopsis = "Usage: mktap web [options]"
 
21
    optParameters = [["port", "p", "8080","Port to start the server on."],
 
22
                     ["logfile", "l", None, "Path to web CLF (Combined Log Format) log file."],
 
23
                     ["https", None, None, "Port to listen on for Secure HTTP."],
 
24
                     ["certificate", "c", "server.pem", "SSL certificate to use for HTTPS. "],
 
25
                     ["privkey", "k", "server.pem", "SSL certificate to use for HTTPS."],
 
26
                     ]
 
27
    optFlags = [["personal", "",
 
28
                 "Instead of generating a webserver, generate a "
 
29
                 "ResourcePublisher which listens on "
 
30
                 "~/%s" % distrib.UserDirectory.userSocketName],
 
31
                ["notracebacks", "n", "Display tracebacks in broken web pages. " +
 
32
                 "Displaying tracebacks to users may be security risk!"],
 
33
]
 
34
    zsh_actions = {"logfile" : "_files -g '*.log'", "certificate" : "_files -g '*.pem'",
 
35
                   "privkey" : "_files -g '*.pem'"}
 
36
 
 
37
 
 
38
    longdesc = """\
 
39
This creates a web.tap file that can be used by twistd.  If you specify
 
40
no arguments, it will be a demo webserver that has the Test class from
 
41
twisted.web.demo in it."""
 
42
 
 
43
    def __init__(self):
 
44
        usage.Options.__init__(self)
 
45
        self['indexes'] = []
 
46
        self['root'] = None
 
47
 
 
48
    def opt_index(self, indexName):
 
49
        """Add the name of a file used to check for directory indexes.
 
50
        [default: index, index.html]
 
51
        """
 
52
        self['indexes'].append(indexName)
 
53
 
 
54
    opt_i = opt_index
 
55
        
 
56
    def opt_user(self):
 
57
        """Makes a server with ~/public_html and ~/.twistd-web-pb support for
 
58
        users.
 
59
        """
 
60
        self['root'] = distrib.UserDirectory()
 
61
 
 
62
    opt_u = opt_user
 
63
 
 
64
    def opt_path(self, path):
 
65
        """<path> is either a specific file or a directory to
 
66
        be set as the root of the web server. Use this if you
 
67
        have a directory full of HTML, cgi, php3, epy, or rpy files or
 
68
        any other files that you want to be served up raw.
 
69
        """
 
70
 
 
71
        self['root'] = static.File(os.path.abspath(path))
 
72
        self['root'].processors = {
 
73
            '.cgi': twcgi.CGIScript,
 
74
            '.php3': twcgi.PHP3Script,
 
75
            '.php': twcgi.PHPScript,
 
76
            '.epy': script.PythonScript,
 
77
            '.rpy': script.ResourceScript,
 
78
            '.trp': trp.ResourceUnpickler,
 
79
            }
 
80
 
 
81
    def opt_processor(self, proc):
 
82
        """`ext=class' where `class' is added as a Processor for files ending
 
83
        with `ext'.
 
84
        """
 
85
        if not isinstance(self['root'], static.File):
 
86
            raise usage.UsageError("You can only use --processor after --path.")
 
87
        ext, klass = proc.split('=', 1)
 
88
        self['root'].processors[ext] = reflect.namedClass(klass)
 
89
 
 
90
    def opt_static(self, path):
 
91
        """Same as --path, this is deprecated and will be removed in a
 
92
        future release."""
 
93
        print ("WARNING: --static is deprecated and will be removed in"
 
94
               "a future release. Please use --path.")
 
95
        self.opt_path(path)
 
96
    opt_s = opt_static
 
97
    
 
98
    def opt_class(self, className):
 
99
        """Create a Resource subclass with a zero-argument constructor.
 
100
        """
 
101
        classObj = reflect.namedClass(className)
 
102
        self['root'] = classObj()
 
103
 
 
104
 
 
105
    def opt_resource_script(self, name):
 
106
        """An .rpy file to be used as the root resource of the webserver."""
 
107
        self['root'] = script.ResourceScriptWrapper(name)
 
108
 
 
109
 
 
110
    def opt_mime_type(self, defaultType):
 
111
        """Specify the default mime-type for static files."""
 
112
        if not isinstance(self['root'], static.File):
 
113
            raise usage.UsageError("You can only use --mime_type after --path.")
 
114
        self['root'].defaultType = defaultType
 
115
    opt_m = opt_mime_type
 
116
 
 
117
 
 
118
    def opt_allow_ignore_ext(self):
 
119
        """Specify whether or not a request for 'foo' should return 'foo.ext'"""
 
120
        if not isinstance(self['root'], static.File):
 
121
            raise usage.UsageError("You can only use --allow_ignore_ext "
 
122
                                   "after --path.")
 
123
        self['root'].ignoreExt('*')
 
124
 
 
125
    def opt_ignore_ext(self, ext):
 
126
        """Specify an extension to ignore.  These will be processed in order.
 
127
        """
 
128
        if not isinstance(self['root'], static.File):
 
129
            raise usage.UsageError("You can only use --ignore_ext "
 
130
                                   "after --path.")
 
131
        self['root'].ignoreExt(ext)
 
132
 
 
133
    def opt_flashconduit(self, port=None):
 
134
        """Start a flashconduit on the specified port.
 
135
        """
 
136
        if not port:
 
137
            port = "4321"
 
138
        self['flashconduit'] = port
 
139
 
 
140
    def postOptions(self):
 
141
        if self['https']:
 
142
            try:
 
143
                from twisted.internet.ssl import DefaultOpenSSLContextFactory
 
144
            except ImportError:
 
145
                raise usage.UsageError("SSL support not installed")
 
146
 
 
147
 
 
148
def makeService(config):
 
149
    s = service.MultiService()
 
150
    if config['root']:
 
151
        root = config['root']
 
152
        if config['indexes']:
 
153
            config['root'].indexNames = config['indexes']
 
154
    else:
 
155
        # This really ought to be web.Admin or something
 
156
        root = demo.Test()
 
157
 
 
158
    if isinstance(root, static.File):
 
159
        root.registry.setComponent(interfaces.IServiceCollection, s)
 
160
   
 
161
    if config['logfile']:
 
162
        site = server.Site(root, logPath=config['logfile'])
 
163
    else:
 
164
        site = server.Site(root)
 
165
 
 
166
    site.displayTracebacks = not config["notracebacks"]
 
167
    
 
168
    if config['personal']:
 
169
        import pwd,os
 
170
 
 
171
        pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
 
172
                 = pwd.getpwuid(os.getuid())
 
173
        i = internet.UNIXServer(os.path.join(pw_dir,
 
174
                                   distrib.UserDirectory.userSocketName),
 
175
                      pb.BrokerFactory(distrib.ResourcePublisher(site)))
 
176
        i.setServiceParent(s)
 
177
    else:
 
178
        if config['https']:
 
179
            from twisted.internet.ssl import DefaultOpenSSLContextFactory
 
180
            i = internet.SSLServer(int(config['https']), site,
 
181
                          DefaultOpenSSLContextFactory(config['privkey'],
 
182
                                                       config['certificate']))
 
183
            i.setServiceParent(s)
 
184
        strports.service(config['port'], site).setServiceParent(s)
 
185
    
 
186
    flashport = config.get('flashconduit', None)
 
187
    if flashport:
 
188
        from twisted.web.woven.flashconduit import FlashConduitFactory
 
189
        i = internet.TCPServer(int(flashport), FlashConduitFactory(site))
 
190
        i.setServiceParent(s)
 
191
    return s