serving.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.serving
  4. ~~~~~~~~~~~~~~~~
  5. There are many ways to serve a WSGI application. While you're developing
  6. it you usually don't want a full blown webserver like Apache but a simple
  7. standalone one. From Python 2.5 onwards there is the `wsgiref`_ server in
  8. the standard library. If you're using older versions of Python you can
  9. download the package from the cheeseshop.
  10. However there are some caveats. Sourcecode won't reload itself when
  11. changed and each time you kill the server using ``^C`` you get an
  12. `KeyboardInterrupt` error. While the latter is easy to solve the first
  13. one can be a pain in the ass in some situations.
  14. The easiest way is creating a small ``start-myproject.py`` that runs the
  15. application::
  16. #!/usr/bin/env python
  17. # -*- coding: utf-8 -*-
  18. from myproject import make_app
  19. from werkzeug.serving import run_simple
  20. app = make_app(...)
  21. run_simple('localhost', 8080, app, use_reloader=True)
  22. You can also pass it a `extra_files` keyword argument with a list of
  23. additional files (like configuration files) you want to observe.
  24. For bigger applications you should consider using `click`
  25. (http://click.pocoo.org) instead of a simple start file.
  26. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  27. :license: BSD, see LICENSE for more details.
  28. """
  29. from __future__ import with_statement
  30. import io
  31. import os
  32. import socket
  33. import sys
  34. import signal
  35. can_fork = hasattr(os, "fork")
  36. try:
  37. import termcolor
  38. except ImportError:
  39. termcolor = None
  40. try:
  41. import ssl
  42. except ImportError:
  43. class _SslDummy(object):
  44. def __getattr__(self, name):
  45. raise RuntimeError('SSL support unavailable')
  46. ssl = _SslDummy()
  47. def _get_openssl_crypto_module():
  48. try:
  49. from OpenSSL import crypto
  50. except ImportError:
  51. raise TypeError('Using ad-hoc certificates requires the pyOpenSSL '
  52. 'library.')
  53. else:
  54. return crypto
  55. try:
  56. import SocketServer as socketserver
  57. from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
  58. except ImportError:
  59. import socketserver
  60. from http.server import HTTPServer, BaseHTTPRequestHandler
  61. ThreadingMixIn = socketserver.ThreadingMixIn
  62. if can_fork:
  63. ForkingMixIn = socketserver.ForkingMixIn
  64. else:
  65. class ForkingMixIn(object):
  66. pass
  67. # important: do not use relative imports here or python -m will break
  68. import werkzeug
  69. from werkzeug._internal import _log
  70. from werkzeug._compat import PY2, WIN, reraise, wsgi_encoding_dance
  71. from werkzeug.urls import url_parse, url_unquote
  72. from werkzeug.exceptions import InternalServerError
  73. LISTEN_QUEUE = 128
  74. can_open_by_fd = not WIN and hasattr(socket, 'fromfd')
  75. class DechunkedInput(io.RawIOBase):
  76. """An input stream that handles Transfer-Encoding 'chunked'"""
  77. def __init__(self, rfile):
  78. self._rfile = rfile
  79. self._done = False
  80. self._len = 0
  81. def readable(self):
  82. return True
  83. def read_chunk_len(self):
  84. try:
  85. line = self._rfile.readline().decode('latin1')
  86. _len = int(line.strip(), 16)
  87. except ValueError:
  88. raise IOError('Invalid chunk header')
  89. if _len < 0:
  90. raise IOError('Negative chunk length not allowed')
  91. return _len
  92. def readinto(self, buf):
  93. read = 0
  94. while not self._done and read < len(buf):
  95. if self._len == 0:
  96. # This is the first chunk or we fully consumed the previous
  97. # one. Read the next length of the next chunk
  98. self._len = self.read_chunk_len()
  99. if self._len == 0:
  100. # Found the final chunk of size 0. The stream is now exhausted,
  101. # but there is still a final newline that should be consumed
  102. self._done = True
  103. if self._len > 0:
  104. # There is data (left) in this chunk, so append it to the
  105. # buffer. If this operation fully consumes the chunk, this will
  106. # reset self._len to 0.
  107. n = min(len(buf), self._len)
  108. buf[read:read + n] = self._rfile.read(n)
  109. self._len -= n
  110. read += n
  111. if self._len == 0:
  112. # Skip the terminating newline of a chunk that has been fully
  113. # consumed. This also applies to the 0-sized final chunk
  114. terminator = self._rfile.readline()
  115. if terminator not in (b'\n', b'\r\n', b'\r'):
  116. raise IOError('Missing chunk terminating newline')
  117. return read
  118. class WSGIRequestHandler(BaseHTTPRequestHandler, object):
  119. """A request handler that implements WSGI dispatching."""
  120. @property
  121. def server_version(self):
  122. return 'Werkzeug/' + werkzeug.__version__
  123. def make_environ(self):
  124. request_url = url_parse(self.path)
  125. def shutdown_server():
  126. self.server.shutdown_signal = True
  127. url_scheme = self.server.ssl_context is None and 'http' or 'https'
  128. path_info = url_unquote(request_url.path)
  129. environ = {
  130. 'wsgi.version': (1, 0),
  131. 'wsgi.url_scheme': url_scheme,
  132. 'wsgi.input': self.rfile,
  133. 'wsgi.errors': sys.stderr,
  134. 'wsgi.multithread': self.server.multithread,
  135. 'wsgi.multiprocess': self.server.multiprocess,
  136. 'wsgi.run_once': False,
  137. 'werkzeug.server.shutdown': shutdown_server,
  138. 'SERVER_SOFTWARE': self.server_version,
  139. 'REQUEST_METHOD': self.command,
  140. 'SCRIPT_NAME': '',
  141. 'PATH_INFO': wsgi_encoding_dance(path_info),
  142. 'QUERY_STRING': wsgi_encoding_dance(request_url.query),
  143. 'REMOTE_ADDR': self.address_string(),
  144. 'REMOTE_PORT': self.port_integer(),
  145. 'SERVER_NAME': self.server.server_address[0],
  146. 'SERVER_PORT': str(self.server.server_address[1]),
  147. 'SERVER_PROTOCOL': self.request_version
  148. }
  149. for key, value in self.headers.items():
  150. key = key.upper().replace('-', '_')
  151. if key not in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
  152. key = 'HTTP_' + key
  153. environ[key] = value
  154. if environ.get('HTTP_TRANSFER_ENCODING', '').strip().lower() == 'chunked':
  155. environ['wsgi.input_terminated'] = True
  156. environ['wsgi.input'] = DechunkedInput(environ['wsgi.input'])
  157. if request_url.scheme and request_url.netloc:
  158. environ['HTTP_HOST'] = request_url.netloc
  159. return environ
  160. def run_wsgi(self):
  161. if self.headers.get('Expect', '').lower().strip() == '100-continue':
  162. self.wfile.write(b'HTTP/1.1 100 Continue\r\n\r\n')
  163. self.environ = environ = self.make_environ()
  164. headers_set = []
  165. headers_sent = []
  166. def write(data):
  167. assert headers_set, 'write() before start_response'
  168. if not headers_sent:
  169. status, response_headers = headers_sent[:] = headers_set
  170. try:
  171. code, msg = status.split(None, 1)
  172. except ValueError:
  173. code, msg = status, ""
  174. code = int(code)
  175. self.send_response(code, msg)
  176. header_keys = set()
  177. for key, value in response_headers:
  178. self.send_header(key, value)
  179. key = key.lower()
  180. header_keys.add(key)
  181. if not ('content-length' in header_keys or
  182. environ['REQUEST_METHOD'] == 'HEAD' or
  183. code < 200 or code in (204, 304)):
  184. self.close_connection = True
  185. self.send_header('Connection', 'close')
  186. if 'server' not in header_keys:
  187. self.send_header('Server', self.version_string())
  188. if 'date' not in header_keys:
  189. self.send_header('Date', self.date_time_string())
  190. self.end_headers()
  191. assert isinstance(data, bytes), 'applications must write bytes'
  192. self.wfile.write(data)
  193. self.wfile.flush()
  194. def start_response(status, response_headers, exc_info=None):
  195. if exc_info:
  196. try:
  197. if headers_sent:
  198. reraise(*exc_info)
  199. finally:
  200. exc_info = None
  201. elif headers_set:
  202. raise AssertionError('Headers already set')
  203. headers_set[:] = [status, response_headers]
  204. return write
  205. def execute(app):
  206. application_iter = app(environ, start_response)
  207. try:
  208. for data in application_iter:
  209. write(data)
  210. if not headers_sent:
  211. write(b'')
  212. finally:
  213. if hasattr(application_iter, 'close'):
  214. application_iter.close()
  215. application_iter = None
  216. try:
  217. execute(self.server.app)
  218. except (socket.error, socket.timeout) as e:
  219. self.connection_dropped(e, environ)
  220. except Exception:
  221. if self.server.passthrough_errors:
  222. raise
  223. from werkzeug.debug.tbtools import get_current_traceback
  224. traceback = get_current_traceback(ignore_system_exceptions=True)
  225. try:
  226. # if we haven't yet sent the headers but they are set
  227. # we roll back to be able to set them again.
  228. if not headers_sent:
  229. del headers_set[:]
  230. execute(InternalServerError())
  231. except Exception:
  232. pass
  233. self.server.log('error', 'Error on request:\n%s',
  234. traceback.plaintext)
  235. def handle(self):
  236. """Handles a request ignoring dropped connections."""
  237. rv = None
  238. try:
  239. rv = BaseHTTPRequestHandler.handle(self)
  240. except (socket.error, socket.timeout) as e:
  241. self.connection_dropped(e)
  242. except Exception:
  243. if self.server.ssl_context is None or not is_ssl_error():
  244. raise
  245. if self.server.shutdown_signal:
  246. self.initiate_shutdown()
  247. return rv
  248. def initiate_shutdown(self):
  249. """A horrible, horrible way to kill the server for Python 2.6 and
  250. later. It's the best we can do.
  251. """
  252. # Windows does not provide SIGKILL, go with SIGTERM then.
  253. sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
  254. # reloader active
  255. if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
  256. os.kill(os.getpid(), sig)
  257. # python 2.7
  258. self.server._BaseServer__shutdown_request = True
  259. # python 2.6
  260. self.server._BaseServer__serving = False
  261. def connection_dropped(self, error, environ=None):
  262. """Called if the connection was closed by the client. By default
  263. nothing happens.
  264. """
  265. def handle_one_request(self):
  266. """Handle a single HTTP request."""
  267. self.raw_requestline = self.rfile.readline()
  268. if not self.raw_requestline:
  269. self.close_connection = 1
  270. elif self.parse_request():
  271. return self.run_wsgi()
  272. def send_response(self, code, message=None):
  273. """Send the response header and log the response code."""
  274. self.log_request(code)
  275. if message is None:
  276. message = code in self.responses and self.responses[code][0] or ''
  277. if self.request_version != 'HTTP/0.9':
  278. hdr = "%s %d %s\r\n" % (self.protocol_version, code, message)
  279. self.wfile.write(hdr.encode('ascii'))
  280. def version_string(self):
  281. return BaseHTTPRequestHandler.version_string(self).strip()
  282. def address_string(self):
  283. if getattr(self, 'environ', None):
  284. return self.environ['REMOTE_ADDR']
  285. else:
  286. return self.client_address[0]
  287. def port_integer(self):
  288. return self.client_address[1]
  289. def log_request(self, code='-', size='-'):
  290. msg = self.requestline
  291. code = str(code)
  292. if termcolor:
  293. color = termcolor.colored
  294. if code[0] == '1': # 1xx - Informational
  295. msg = color(msg, attrs=['bold'])
  296. elif code[0] == '2': # 2xx - Success
  297. msg = color(msg, color='white')
  298. elif code == '304': # 304 - Resource Not Modified
  299. msg = color(msg, color='cyan')
  300. elif code[0] == '3': # 3xx - Redirection
  301. msg = color(msg, color='green')
  302. elif code == '404': # 404 - Resource Not Found
  303. msg = color(msg, color='yellow')
  304. elif code[0] == '4': # 4xx - Client Error
  305. msg = color(msg, color='red', attrs=['bold'])
  306. else: # 5xx, or any other response
  307. msg = color(msg, color='magenta', attrs=['bold'])
  308. self.log('info', '"%s" %s %s', msg, code, size)
  309. def log_error(self, *args):
  310. self.log('error', *args)
  311. def log_message(self, format, *args):
  312. self.log('info', format, *args)
  313. def log(self, type, message, *args):
  314. _log(type, '%s - - [%s] %s\n' % (self.address_string(),
  315. self.log_date_time_string(),
  316. message % args))
  317. #: backwards compatible name if someone is subclassing it
  318. BaseRequestHandler = WSGIRequestHandler
  319. def generate_adhoc_ssl_pair(cn=None):
  320. from random import random
  321. crypto = _get_openssl_crypto_module()
  322. # pretty damn sure that this is not actually accepted by anyone
  323. if cn is None:
  324. cn = '*'
  325. cert = crypto.X509()
  326. cert.set_serial_number(int(random() * sys.maxsize))
  327. cert.gmtime_adj_notBefore(0)
  328. cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)
  329. subject = cert.get_subject()
  330. subject.CN = cn
  331. subject.O = 'Dummy Certificate' # noqa: E741
  332. issuer = cert.get_issuer()
  333. issuer.CN = 'Untrusted Authority'
  334. issuer.O = 'Self-Signed' # noqa: E741
  335. pkey = crypto.PKey()
  336. pkey.generate_key(crypto.TYPE_RSA, 2048)
  337. cert.set_pubkey(pkey)
  338. cert.sign(pkey, 'sha256')
  339. return cert, pkey
  340. def make_ssl_devcert(base_path, host=None, cn=None):
  341. """Creates an SSL key for development. This should be used instead of
  342. the ``'adhoc'`` key which generates a new cert on each server start.
  343. It accepts a path for where it should store the key and cert and
  344. either a host or CN. If a host is given it will use the CN
  345. ``*.host/CN=host``.
  346. For more information see :func:`run_simple`.
  347. .. versionadded:: 0.9
  348. :param base_path: the path to the certificate and key. The extension
  349. ``.crt`` is added for the certificate, ``.key`` is
  350. added for the key.
  351. :param host: the name of the host. This can be used as an alternative
  352. for the `cn`.
  353. :param cn: the `CN` to use.
  354. """
  355. from OpenSSL import crypto
  356. if host is not None:
  357. cn = '*.%s/CN=%s' % (host, host)
  358. cert, pkey = generate_adhoc_ssl_pair(cn=cn)
  359. cert_file = base_path + '.crt'
  360. pkey_file = base_path + '.key'
  361. with open(cert_file, 'wb') as f:
  362. f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
  363. with open(pkey_file, 'wb') as f:
  364. f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
  365. return cert_file, pkey_file
  366. def generate_adhoc_ssl_context():
  367. """Generates an adhoc SSL context for the development server."""
  368. crypto = _get_openssl_crypto_module()
  369. import tempfile
  370. import atexit
  371. cert, pkey = generate_adhoc_ssl_pair()
  372. cert_handle, cert_file = tempfile.mkstemp()
  373. pkey_handle, pkey_file = tempfile.mkstemp()
  374. atexit.register(os.remove, pkey_file)
  375. atexit.register(os.remove, cert_file)
  376. os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
  377. os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
  378. os.close(cert_handle)
  379. os.close(pkey_handle)
  380. ctx = load_ssl_context(cert_file, pkey_file)
  381. return ctx
  382. def load_ssl_context(cert_file, pkey_file=None, protocol=None):
  383. """Loads SSL context from cert/private key files and optional protocol.
  384. Many parameters are directly taken from the API of
  385. :py:class:`ssl.SSLContext`.
  386. :param cert_file: Path of the certificate to use.
  387. :param pkey_file: Path of the private key to use. If not given, the key
  388. will be obtained from the certificate file.
  389. :param protocol: One of the ``PROTOCOL_*`` constants in the stdlib ``ssl``
  390. module. Defaults to ``PROTOCOL_SSLv23``.
  391. """
  392. if protocol is None:
  393. protocol = ssl.PROTOCOL_SSLv23
  394. ctx = _SSLContext(protocol)
  395. ctx.load_cert_chain(cert_file, pkey_file)
  396. return ctx
  397. class _SSLContext(object):
  398. '''A dummy class with a small subset of Python3's ``ssl.SSLContext``, only
  399. intended to be used with and by Werkzeug.'''
  400. def __init__(self, protocol):
  401. self._protocol = protocol
  402. self._certfile = None
  403. self._keyfile = None
  404. self._password = None
  405. def load_cert_chain(self, certfile, keyfile=None, password=None):
  406. self._certfile = certfile
  407. self._keyfile = keyfile or certfile
  408. self._password = password
  409. def wrap_socket(self, sock, **kwargs):
  410. return ssl.wrap_socket(sock, keyfile=self._keyfile,
  411. certfile=self._certfile,
  412. ssl_version=self._protocol, **kwargs)
  413. def is_ssl_error(error=None):
  414. """Checks if the given error (or the current one) is an SSL error."""
  415. exc_types = (ssl.SSLError,)
  416. try:
  417. from OpenSSL.SSL import Error
  418. exc_types += (Error,)
  419. except ImportError:
  420. pass
  421. if error is None:
  422. error = sys.exc_info()[1]
  423. return isinstance(error, exc_types)
  424. def select_ip_version(host, port):
  425. """Returns AF_INET4 or AF_INET6 depending on where to connect to."""
  426. # disabled due to problems with current ipv6 implementations
  427. # and various operating systems. Probably this code also is
  428. # not supposed to work, but I can't come up with any other
  429. # ways to implement this.
  430. # try:
  431. # info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
  432. # socket.SOCK_STREAM, 0,
  433. # socket.AI_PASSIVE)
  434. # if info:
  435. # return info[0][0]
  436. # except socket.gaierror:
  437. # pass
  438. if ':' in host and hasattr(socket, 'AF_INET6'):
  439. return socket.AF_INET6
  440. return socket.AF_INET
  441. def get_sockaddr(host, port, family):
  442. """Returns a fully qualified socket address, that can properly used by
  443. socket.bind"""
  444. try:
  445. res = socket.getaddrinfo(host, port, family,
  446. socket.SOCK_STREAM, socket.SOL_TCP)
  447. except socket.gaierror:
  448. return (host, port)
  449. return res[0][4]
  450. class BaseWSGIServer(HTTPServer, object):
  451. """Simple single-threaded, single-process WSGI server."""
  452. multithread = False
  453. multiprocess = False
  454. request_queue_size = LISTEN_QUEUE
  455. def __init__(self, host, port, app, handler=None,
  456. passthrough_errors=False, ssl_context=None, fd=None):
  457. if handler is None:
  458. handler = WSGIRequestHandler
  459. self.address_family = select_ip_version(host, port)
  460. if fd is not None:
  461. real_sock = socket.fromfd(fd, self.address_family,
  462. socket.SOCK_STREAM)
  463. port = 0
  464. HTTPServer.__init__(self, get_sockaddr(host, int(port),
  465. self.address_family), handler)
  466. self.app = app
  467. self.passthrough_errors = passthrough_errors
  468. self.shutdown_signal = False
  469. self.host = host
  470. self.port = self.socket.getsockname()[1]
  471. # Patch in the original socket.
  472. if fd is not None:
  473. self.socket.close()
  474. self.socket = real_sock
  475. self.server_address = self.socket.getsockname()
  476. if ssl_context is not None:
  477. if isinstance(ssl_context, tuple):
  478. ssl_context = load_ssl_context(*ssl_context)
  479. if ssl_context == 'adhoc':
  480. ssl_context = generate_adhoc_ssl_context()
  481. # If we are on Python 2 the return value from socket.fromfd
  482. # is an internal socket object but what we need for ssl wrap
  483. # is the wrapper around it :(
  484. sock = self.socket
  485. if PY2 and not isinstance(sock, socket.socket):
  486. sock = socket.socket(sock.family, sock.type, sock.proto, sock)
  487. self.socket = ssl_context.wrap_socket(sock, server_side=True)
  488. self.ssl_context = ssl_context
  489. else:
  490. self.ssl_context = None
  491. def log(self, type, message, *args):
  492. _log(type, message, *args)
  493. def serve_forever(self):
  494. self.shutdown_signal = False
  495. try:
  496. HTTPServer.serve_forever(self)
  497. except KeyboardInterrupt:
  498. pass
  499. finally:
  500. self.server_close()
  501. def handle_error(self, request, client_address):
  502. if self.passthrough_errors:
  503. raise
  504. return HTTPServer.handle_error(self, request, client_address)
  505. def get_request(self):
  506. con, info = self.socket.accept()
  507. return con, info
  508. class ThreadedWSGIServer(ThreadingMixIn, BaseWSGIServer):
  509. """A WSGI server that does threading."""
  510. multithread = True
  511. daemon_threads = True
  512. class ForkingWSGIServer(ForkingMixIn, BaseWSGIServer):
  513. """A WSGI server that does forking."""
  514. multiprocess = True
  515. def __init__(self, host, port, app, processes=40, handler=None,
  516. passthrough_errors=False, ssl_context=None, fd=None):
  517. if not can_fork:
  518. raise ValueError('Your platform does not support forking.')
  519. BaseWSGIServer.__init__(self, host, port, app, handler,
  520. passthrough_errors, ssl_context, fd)
  521. self.max_children = processes
  522. def make_server(host=None, port=None, app=None, threaded=False, processes=1,
  523. request_handler=None, passthrough_errors=False,
  524. ssl_context=None, fd=None):
  525. """Create a new server instance that is either threaded, or forks
  526. or just processes one request after another.
  527. """
  528. if threaded and processes > 1:
  529. raise ValueError("cannot have a multithreaded and "
  530. "multi process server.")
  531. elif threaded:
  532. return ThreadedWSGIServer(host, port, app, request_handler,
  533. passthrough_errors, ssl_context, fd=fd)
  534. elif processes > 1:
  535. return ForkingWSGIServer(host, port, app, processes, request_handler,
  536. passthrough_errors, ssl_context, fd=fd)
  537. else:
  538. return BaseWSGIServer(host, port, app, request_handler,
  539. passthrough_errors, ssl_context, fd=fd)
  540. def is_running_from_reloader():
  541. """Checks if the application is running from within the Werkzeug
  542. reloader subprocess.
  543. .. versionadded:: 0.10
  544. """
  545. return os.environ.get('WERKZEUG_RUN_MAIN') == 'true'
  546. def run_simple(hostname, port, application, use_reloader=False,
  547. use_debugger=False, use_evalex=True,
  548. extra_files=None, reloader_interval=1,
  549. reloader_type='auto', threaded=False,
  550. processes=1, request_handler=None, static_files=None,
  551. passthrough_errors=False, ssl_context=None):
  552. """Start a WSGI application. Optional features include a reloader,
  553. multithreading and fork support.
  554. This function has a command-line interface too::
  555. python -m werkzeug.serving --help
  556. .. versionadded:: 0.5
  557. `static_files` was added to simplify serving of static files as well
  558. as `passthrough_errors`.
  559. .. versionadded:: 0.6
  560. support for SSL was added.
  561. .. versionadded:: 0.8
  562. Added support for automatically loading a SSL context from certificate
  563. file and private key.
  564. .. versionadded:: 0.9
  565. Added command-line interface.
  566. .. versionadded:: 0.10
  567. Improved the reloader and added support for changing the backend
  568. through the `reloader_type` parameter. See :ref:`reloader`
  569. for more information.
  570. :param hostname: The host for the application. eg: ``'localhost'``
  571. :param port: The port for the server. eg: ``8080``
  572. :param application: the WSGI application to execute
  573. :param use_reloader: should the server automatically restart the python
  574. process if modules were changed?
  575. :param use_debugger: should the werkzeug debugging system be used?
  576. :param use_evalex: should the exception evaluation feature be enabled?
  577. :param extra_files: a list of files the reloader should watch
  578. additionally to the modules. For example configuration
  579. files.
  580. :param reloader_interval: the interval for the reloader in seconds.
  581. :param reloader_type: the type of reloader to use. The default is
  582. auto detection. Valid values are ``'stat'`` and
  583. ``'watchdog'``. See :ref:`reloader` for more
  584. information.
  585. :param threaded: should the process handle each request in a separate
  586. thread?
  587. :param processes: if greater than 1 then handle each request in a new process
  588. up to this maximum number of concurrent processes.
  589. :param request_handler: optional parameter that can be used to replace
  590. the default one. You can use this to replace it
  591. with a different
  592. :class:`~BaseHTTPServer.BaseHTTPRequestHandler`
  593. subclass.
  594. :param static_files: a list or dict of paths for static files. This works
  595. exactly like :class:`SharedDataMiddleware`, it's actually
  596. just wrapping the application in that middleware before
  597. serving.
  598. :param passthrough_errors: set this to `True` to disable the error catching.
  599. This means that the server will die on errors but
  600. it can be useful to hook debuggers in (pdb etc.)
  601. :param ssl_context: an SSL context for the connection. Either an
  602. :class:`ssl.SSLContext`, a tuple in the form
  603. ``(cert_file, pkey_file)``, the string ``'adhoc'`` if
  604. the server should automatically create one, or ``None``
  605. to disable SSL (which is the default).
  606. """
  607. if not isinstance(port, int):
  608. raise TypeError('port must be an integer')
  609. if use_debugger:
  610. from werkzeug.debug import DebuggedApplication
  611. application = DebuggedApplication(application, use_evalex)
  612. if static_files:
  613. from werkzeug.wsgi import SharedDataMiddleware
  614. application = SharedDataMiddleware(application, static_files)
  615. def log_startup(sock):
  616. display_hostname = hostname not in ('', '*') and hostname or 'localhost'
  617. if ':' in display_hostname:
  618. display_hostname = '[%s]' % display_hostname
  619. quit_msg = '(Press CTRL+C to quit)'
  620. port = sock.getsockname()[1]
  621. _log('info', ' * Running on %s://%s:%d/ %s',
  622. ssl_context is None and 'http' or 'https',
  623. display_hostname, port, quit_msg)
  624. def inner():
  625. try:
  626. fd = int(os.environ['WERKZEUG_SERVER_FD'])
  627. except (LookupError, ValueError):
  628. fd = None
  629. srv = make_server(hostname, port, application, threaded,
  630. processes, request_handler,
  631. passthrough_errors, ssl_context,
  632. fd=fd)
  633. if fd is None:
  634. log_startup(srv.socket)
  635. srv.serve_forever()
  636. if use_reloader:
  637. # If we're not running already in the subprocess that is the
  638. # reloader we want to open up a socket early to make sure the
  639. # port is actually available.
  640. if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
  641. if port == 0 and not can_open_by_fd:
  642. raise ValueError('Cannot bind to a random port with enabled '
  643. 'reloader if the Python interpreter does '
  644. 'not support socket opening by fd.')
  645. # Create and destroy a socket so that any exceptions are
  646. # raised before we spawn a separate Python interpreter and
  647. # lose this ability.
  648. address_family = select_ip_version(hostname, port)
  649. s = socket.socket(address_family, socket.SOCK_STREAM)
  650. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  651. s.bind(get_sockaddr(hostname, port, address_family))
  652. if hasattr(s, 'set_inheritable'):
  653. s.set_inheritable(True)
  654. # If we can open the socket by file descriptor, then we can just
  655. # reuse this one and our socket will survive the restarts.
  656. if can_open_by_fd:
  657. os.environ['WERKZEUG_SERVER_FD'] = str(s.fileno())
  658. s.listen(LISTEN_QUEUE)
  659. log_startup(s)
  660. else:
  661. s.close()
  662. # Do not use relative imports, otherwise "python -m werkzeug.serving"
  663. # breaks.
  664. from werkzeug._reloader import run_with_reloader
  665. run_with_reloader(inner, extra_files, reloader_interval,
  666. reloader_type)
  667. else:
  668. inner()
  669. def run_with_reloader(*args, **kwargs):
  670. # People keep using undocumented APIs. Do not use this function
  671. # please, we do not guarantee that it continues working.
  672. from werkzeug._reloader import run_with_reloader
  673. return run_with_reloader(*args, **kwargs)
  674. def main():
  675. '''A simple command-line interface for :py:func:`run_simple`.'''
  676. # in contrast to argparse, this works at least under Python < 2.7
  677. import optparse
  678. from werkzeug.utils import import_string
  679. parser = optparse.OptionParser(
  680. usage='Usage: %prog [options] app_module:app_object')
  681. parser.add_option('-b', '--bind', dest='address',
  682. help='The hostname:port the app should listen on.')
  683. parser.add_option('-d', '--debug', dest='use_debugger',
  684. action='store_true', default=False,
  685. help='Use Werkzeug\'s debugger.')
  686. parser.add_option('-r', '--reload', dest='use_reloader',
  687. action='store_true', default=False,
  688. help='Reload Python process if modules change.')
  689. options, args = parser.parse_args()
  690. hostname, port = None, None
  691. if options.address:
  692. address = options.address.split(':')
  693. hostname = address[0]
  694. if len(address) > 1:
  695. port = address[1]
  696. if len(args) != 1:
  697. sys.stdout.write('No application supplied, or too much. See --help\n')
  698. sys.exit(1)
  699. app = import_string(args[0])
  700. run_simple(
  701. hostname=(hostname or '127.0.0.1'), port=int(port or 5000),
  702. application=app, use_reloader=options.use_reloader,
  703. use_debugger=options.use_debugger
  704. )
  705. if __name__ == '__main__':
  706. main()