serving.py 28 KB

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