Debian Codegraph @

pecan/commands/serve.py

raw
1 """
2 Serve command for Pecan.
3 """
4 from __future__ import print_function
5 import logging
6 import os
7 import sys
8 import threading
9 import time
10 import subprocess
11 from wsgiref.simple_server import WSGIRequestHandler
12
13
14 from pecan.commands import BaseCommand
15 from pecan import util
16
17
18 logger = logging.getLogger(__name__)
19
20
21 class ServeCommand(BaseCommand):
22 """
23 Serves a Pecan web application.
24
25 This command serves a Pecan web application using the provided
26 configuration file for the server and application.
27 """
28
29 arguments = BaseCommand.arguments + ({
30 'name': '--reload',
31 'help': 'Watch for changes and automatically reload.',
32 'default': False,
33 'action': 'store_true'
34 },)
35
36 def run(self, args):
37 super(ServeCommand, self).run(args)
38 app = self.load_app()
39 self.serve(app, app.config)
40
41 def create_subprocess(self):
42 self.server_process = subprocess.Popen(
43 [arg for arg in sys.argv if arg != '--reload'],
44 stdout=sys.stdout, stderr=sys.stderr
45 )
46
47 def watch_and_spawn(self, conf):
48 from watchdog.observers import Observer
49 from watchdog.events import (
50 FileSystemEventHandler, FileSystemMovedEvent, FileModifiedEvent,
51 DirModifiedEvent
52 )
53
54 print('Monitoring for changes...')
55 self.create_subprocess()
56
57 parent = self
58
59 class AggressiveEventHandler(FileSystemEventHandler):
60
61 lock = threading.Lock()
62
63 def should_reload(self, event):
64 for t in (
65 FileSystemMovedEvent, FileModifiedEvent, DirModifiedEvent
66 ):
67 if isinstance(event, t):
68 return True
69 return False
70
71 def on_modified(self, event):
72 if self.should_reload(event) and self.lock.acquire(False):
73 parent.server_process.kill()
74 parent.create_subprocess()
75 time.sleep(1)
76 self.lock.release()
77
78 # Determine a list of file paths to monitor
79 paths = self.paths_to_monitor(conf)
80
81 event_handler = AggressiveEventHandler()
82 for path, recurse in paths:
83 observer = Observer()
84 observer.schedule(
85 event_handler,
86 path=path,
87 recursive=recurse
88 )
89 observer.start()
90
91 try:
92 while True:
93 time.sleep(1)
94 except KeyboardInterrupt:
95 pass
96
97 def paths_to_monitor(self, conf):
98 paths = []
99
100 for package_name in getattr(conf.app, 'modules', []):
101 module = __import__(package_name, fromlist=['app'])
102 if hasattr(module, 'app') and hasattr(module.app, 'setup_app'):
103 paths.append((
104 os.path.dirname(module.__file__),
105 True
106 ))
107 break
108
109 paths.append((os.path.dirname(conf.__file__), False))
110 return paths
111
112 def _serve(self, app, conf):
113 from wsgiref.simple_server import make_server
114
115 host, port = conf.server.host, int(conf.server.port)
116 srv = make_server(
117 host,
118 port,
119 app,
120 handler_class=PecanWSGIRequestHandler,
121 )
122
123 print('Starting server in PID %s' % os.getpid())
124
125 if host == '0.0.0.0':
126 print(
127 'serving on 0.0.0.0:%s, view at http://127.0.0.1:%s' %
128 (port, port)
129 )
130 else:
131 print("serving on http://%s:%s" % (host, port))
132
133 try:
134 srv.serve_forever()
135 except KeyboardInterrupt:
136 # allow CTRL+C to shutdown
137 pass
138
139 def serve(self, app, conf):
140 """
141 A very simple approach for a WSGI server.
142 """
143
144 if self.args.reload:
145 try:
146 self.watch_and_spawn(conf)
147 except ImportError:
148 print('The `--reload` option requires `watchdog` to be '
149 'installed.')
150 print(' $ pip install watchdog')
151 else:
152 self._serve(app, conf)
153
154
155 def gunicorn_run():
156 """
157 The ``gunicorn_pecan`` command for launching ``pecan`` applications
158 """
159 try:
160 from gunicorn.app.wsgiapp import WSGIApplication
161 except ImportError as exc:
162 args = exc.args
163 arg0 = args[0] if args else ''
164 arg0 += ' (are you sure `gunicorn` is installed?)'
165 exc.args = (arg0,) + args[1:]
166 raise
167
168 class PecanApplication(WSGIApplication):
169
170 def init(self, parser, opts, args):
171 if len(args) != 1:
172 parser.error("No configuration file was specified.")
173
174 self.cfgfname = os.path.normpath(
175 os.path.join(os.getcwd(), args[0])
176 )
177 self.cfgfname = os.path.abspath(self.cfgfname)
178 if not os.path.exists(self.cfgfname):
179 parser.error("Config file not found: %s" % self.cfgfname)
180
181 from pecan.configuration import _runtime_conf, set_config
182 set_config(self.cfgfname, overwrite=True)
183
184 # If available, use the host and port from the pecan config file
185 cfg = {}
186 if _runtime_conf.get('server'):
187 server = _runtime_conf['server']
188 if hasattr(server, 'host') and hasattr(server, 'port'):
189 cfg['bind'] = '%s:%s' % (
190 server.host, server.port
191 )
192 return cfg
193
194 def load(self):
195 from pecan.deploy import deploy
196 return deploy(self.cfgfname)
197
198 PecanApplication("%(prog)s [OPTIONS] config.py").run()
199
200
201 class PecanWSGIRequestHandler(WSGIRequestHandler, object):
202 """
203 A wsgiref request handler class that allows actual log output depending on
204 the application configuration.
205 """
206
207 def __init__(self, *args, **kwargs):
208 # We set self.path to avoid crashes in log_message() on unsupported
209 # requests (like "OPTIONS").
210 self.path = ''
211 super(PecanWSGIRequestHandler, self).__init__(*args, **kwargs)
212
213 def log_message(self, format, *args):
214 """
215 overrides the ``log_message`` method from the wsgiref server so that
216 normal logging works with whatever configuration the application has
217 been set to.
218
219 Levels are inferred from the HTTP status code, 4XX codes are treated as
220 warnings, 5XX as errors and everything else as INFO level.
221 """
222 code = args[1][0]
223 levels = {
224 '4': 'warning',
225 '5': 'error'
226 }
227
228 log_handler = getattr(logger, levels.get(code, 'info'))
229 log_handler(format % args)