Added the new flask run module to start the server.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 42c28c3 · Browse files · 2 files·+224 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+224 added−0 removed
- other:+224 added−0 removed
Provenance
- Commit
7503bde- Tree
daa47ac- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
42c28c3
2 files changed+224 added−0 removed
added:flask/run.py+220 added
1+import os2+import sys3+from threading import Lock4+from optparse import OptionParser5+6+from werkzeug.serving import run_simple7+8+from ._compat import iteritems9+10+11+def find_best_app(module):12+ """Given a module instance this tries to find the best possible application13+ in the module or raises a RuntimeError.14+ """15+ from flask import Flask16+17+ # The app name wins, even if it's not a flask object.18+ app = getattr(module, 'app', None)19+ if app is not None and callable(app):20+ return app21+22+ # Otherwise find the first object named Flask23+ matches = []24+ for key, value in iteritems(module.__dict__):25+ if isinstance(value, Flask):26+ matches.append(value)27+28+ if matches:29+ if len(matches) > 1:30+ raise RuntimeError('More than one possible Flask application '31+ 'found in module "%s", none of which are called '32+ '"app". Be explicit!' % module)33+ return matches[0]34+35+ raise RuntimeError('Failed to find application in module "%s". Are '36+ 'you sure it contains a Flask application? Maybe '37+ 'you wrapped it in a WSGI middleware or you are '38+ 'using a factory function.' % module)39+40+41+def prepare_exec_for_file(filename):42+ module = []43+44+ # Chop off file extensions or package markers45+ if filename.endswith('.py'):46+ filename = filename[:-3]47+ elif os.path.split(filename)[1] == '__init__.py':48+ filename = os.path.dirname(filename)49+ filename = os.path.realpath(filename)50+51+ dirpath = filename52+ while 1:53+ dirpath, extra = os.path.split(dirpath)54+ module.append(extra)55+ if not os.path.isfile(os.path.join(dirpath, '__init__.py')):56+ break57+58+ sys.path.insert(0, dirpath)59+ return '.'.join(module[::-1])60+61+62+def locate_app(app_id, debug=None):63+ """Attempts to locate the application."""64+ if ':' in app_id:65+ module, app_obj = app_id.split(':', 1)66+ else:67+ module = app_id68+ app_obj = None69+70+ __import__(module)71+ mod = sys.modules[module]72+ if app_obj is None:73+ app = find_best_app(mod)74+ else:75+ app = getattr(mod, app_obj, None)76+ if app is None:77+ raise RuntimeError('Failed to find application in module "%s"'78+ % module)79+ if debug is not None:80+ app.debug = debug81+ return app82+83+84+class DispatchingApp(object):85+ """Special applicationt that dispatches to a flask application which86+ is imported by name on first request. This is safer than importing87+ the application upfront because it means that we can forward all88+ errors for import problems into the browser as error.89+ """90+91+ def __init__(self, app_id, debug=None, use_eager_loading=False):92+ self.app_id = app_id93+ self.app = None94+ self.debug = debug95+ self._lock = Lock()96+ if use_eager_loading:97+ self._load_unlocked()98+99+ def _load_unlocked(self):100+ self.app = rv = locate_app(self.app_id, self.debug)101+ return rv102+103+ def __call__(self, environ, start_response):104+ if self.app is not None:105+ return self.app(environ, start_response)106+ with self._lock:107+ if self.app is not None:108+ rv = self.app109+ else:110+ rv = self._load_unlocked()111+ return rv(environ, start_response)112+113+114+def run_application(app_id, host='127.0.0.1', port=5000, debug=None,115+ use_reloader=False, use_debugger=False,116+ use_eager_loading=None, magic_app_id=True):117+ """Useful function to start a Werkzeug server for an application that118+ is known by it's import name. By default the app ID can also be a119+ full file name in which case Flask attempts to reconstruct the import120+ name from it and do the right thing.121+122+ :param app_id: the import name of the application module. If a colon123+ is provided, everything afterwards is the application124+ object name. In case the magic app id is enabled this125+ can also be a filename.126+ :param host: the host to bind to.127+ :param port: the port to bind to.128+ :param debug: if set to something other than None then the application's129+ debug flag will be set to this.130+ :param use_reloader: enables or disables the reloader.131+ :param use_debugger: enables or disables the builtin debugger.132+ :param use_eager_loading: enables or disables eager loading. This is133+ normally conditional to the reloader.134+ :param magic_app_id: if this is enabled then the app id can also be a135+ filename instead of an import module and Flask136+ will attempt to reconstruct the import name.137+ """138+ if magic_app_id:139+ if os.path.isfile(app_id) or os.sep in app_id or \140+ os.altsep is not None and os.altsep in app_id:141+ app_id = prepare_exec_for_file(app_id)142+143+ if use_eager_loading is None:144+ use_eager_loading = not use_reloader145+146+ # Extra startup messages. This depends a but on Werkzeug internals to147+ # not double execute when the reloader kicks in.148+ if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':149+ print ' * Serving Flask app "%s"' % app_id150+ if debug is not None:151+ print ' * Forcing debug %s' % (debug and 'on' or 'off')152+153+ app = DispatchingApp(app_id, debug, use_eager_loading)154+ run_simple(host, port, app, use_reloader=use_reloader,155+ use_debugger=use_debugger)156+157+158+def main(as_module=False):159+ this_module = __package__ + '.run'160+161+ if as_module:162+ name = 'python -m ' + this_module163+ else:164+ name = 'flask-run'165+166+ parser = OptionParser(usage='%prog [options] module', prog=name)167+ parser.add_option('--debug', action='store_true',168+ dest='debug', help='Flip debug flag on. If enabled '169+ 'this also affects debugger and reloader defaults.')170+ parser.add_option('--no-debug', action='store_false',171+ dest='debug', help='Flip debug flag off.')172+ parser.add_option('--host', default='127.0.0.1',173+ help='The host to bind on. (defaults to 127.0.0.1)')174+ parser.add_option('--port', default=5000,175+ help='The port to bind on. (defaults to 5000)')176+ parser.add_option('--with-reloader', action='store_true',177+ dest='with_reloader',178+ help='Enable the reloader.')179+ parser.add_option('--without-reloader', action='store_false',180+ dest='with_reloader',181+ help='Disable the reloader.')182+ parser.add_option('--with-debugger', action='store_true',183+ dest='with_debugger',184+ help='Enable the debugger.')185+ parser.add_option('--without-debugger', action='store_false',186+ dest='with_debugger',187+ help='Disable the debugger.')188+ parser.add_option('--with-eager-loading', action='store_true',189+ dest='with_eager_loading',190+ help='Force enable the eager-loading. This makes the '191+ 'application load immediately but makes development '192+ 'flows harder. It\'s not recommended to enable eager '193+ 'loading when the reloader is enabled as it can lead '194+ 'to unexpected crashes.')195+ parser.add_option('--without-eager-loading', action='store_false',196+ dest='with_eager_loading',197+ help='Disable the eager-loading.')198+ opts, args = parser.parse_args()199+ if len(args) != 1:200+ parser.error('Expected exactly one argument which is the import '201+ 'name of the application.')202+203+ if opts.with_debugger is None:204+ opts.with_debugger = opts.debug205+ if opts.with_reloader is None:206+ opts.with_reloader = opts.debug207+208+ # This module is always executed as "python -m flask.run" and as such209+ # we need to ensure that we restore the actual command line so that210+ # the reloader can properly operate.211+ sys.argv = ['-m', this_module] + sys.argv[1:]212+213+ run_application(args[0], opts.host, opts.port, debug=opts.debug,214+ use_reloader=opts.with_reloader,215+ use_debugger=opts.with_debugger,216+ use_eager_loading=opts.with_eager_loading)217+218+219+if __name__ == '__main__':220+ main(as_module=True)modified:setup.py+4 added
104 unmodified lines105 'Programming Language :: Python :: 3',106 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',107 'Topic :: Software Development :: Libraries :: Python Modules'108 ],109+ entry_points='''110+ [console_scripts]111+ flask-run=flask.run:main112+ ''',113 cmdclass={'audit': run_audit},114 test_suite='flask.testsuite.suite'115 )