flask icon indicating copy to clipboard operation
flask copied to clipboard

`flask run` not processing SERVER_NAME for port binding

Open joelhed opened this issue 9 years ago • 5 comments

When running a development server, using flask run, with the SERVER_NAME config variable set to a port number other than 5000, the server still defaults to 5000. Looking into the code, it seems that flask.cli.run_command calls werkzeug.serving.run_simple directly, without passing through Flask.run, where the code for processing the server name resides.

This is using python 3.5, and Werkzeug 0.11.11

joelhed avatar Dec 17 '16 11:12 joelhed

Hi!

In app.py, the run() method.

def run(self, host=None, port=None, debug=None, **options):
        """Runs the application on a local development server.
       ....
       from werkzeug.serving import run_simple
        if host is None:
            host = '127.0.0.1'
        if port is None:
            server_name = self.config['SERVER_NAME']
            if server_name and ':' in server_name:
                port = int(server_name.rsplit(':', 1)[1])
            else:
                port = 5000
        if debug is not None:
            self.debug = bool(debug)
        options.setdefault('use_reloader', self.debug)
        options.setdefault('use_debugger', self.debug)
        try:
            run_simple(host, port, self, **options)
        finally:
            # reset the first request information if the development server
            # reset normally.  This makes it possible to restart the server
            # without reloader and that stuff from an interactive shell.
            self._got_first_request = False

keysona avatar Dec 18 '16 03:12 keysona

Exactly! Wouldn't it be great if the command line interface, i.e. run_command in cli.py, called that method, so that SERVER_NAMEgets parsed, instead of calling werkzeug's run_simple(), and skipping it entirely?

Simply replacing the function call might be difficult, due to the auto reloading problem, so I'd suggest extracting port assignment to a function get_port:

def get_port(app):
    server_name = app.config['SERVER_NAME']
    if server_name and ':' in server_name:
        return int(server_name.rsplit(':', 1)[1])
    else:
        return 5000

Using it seems rather obvious.

For reference, run_command in cli.py:

@click.command('run', short_help='Runs a development server.')
@click.option('--host', '-h', default='127.0.0.1',
              help='The interface to bind to.')
@click.option('--port', '-p', default=5000,
              help='The port to bind to.')
@click.option('--reload/--no-reload', default=None,
              help='Enable or disable the reloader.  By default the reloader '
              'is active if debug is enabled.')
@click.option('--debugger/--no-debugger', default=None,
              help='Enable or disable the debugger.  By default the debugger '
              'is active if debug is enabled.')
@click.option('--eager-loading/--lazy-loader', default=None,
              help='Enable or disable eager loading.  By default eager '
              'loading is enabled if the reloader is disabled.')
@click.option('--with-threads/--without-threads', default=False,
              help='Enable or disable multithreading.')
@pass_script_info
def run_command(info, host, port, reload, debugger, eager_loading,
                with_threads):
    """Runs a local development server for the Flask application.
    ...
    """
    from werkzeug.serving import run_simple

    debug = get_debug_flag()
    if reload is None:
        reload = bool(debug)
    if debugger is None:
        debugger = bool(debug)
    if eager_loading is None:
        eager_loading = not reload

    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)

    # Extra startup messages.  This depends a bit on Werkzeug internals to
    # not double execute when the reloader kicks in.
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # If we have an import path we can print it out now which can help
        # people understand what's being served.  If we do not have an
        # import path because the app was loaded through a callback then
        # we won't print anything.
        if info.app_import_path is not None:
            print(' * Serving Flask app "%s"' % info.app_import_path)
        if debug is not None:
            print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))

    run_simple(host, port, app, use_reloader=reload,
               use_debugger=debugger, threaded=with_threads)

joelhed avatar Dec 18 '16 15:12 joelhed

It's not possible with the current implementation. DispatchingApp may not load the Flask app immediately, so there's no guarantee that the app and its config is available when starting the server. This is so that errors during app setup are caught by the debugger instead of crashing the server.

davidism avatar Dec 19 '16 16:12 davidism

Is there a reason that in run_command, after app = DispatchingApp(...), do something like:

if app._app is not None:
    # something similar to the sn_host code in app.py/run
    # (or perhaps add a method that they both can call)

?

I ask because I find it really quite disconcerting that python $FLASK_APP works (with an app.run() within a __name__ == '__main__' block), while flask run doesn't. (That is to say, this seems to me to violate the "principle of least astonishment")

Could this be reconsidered, and/or would a pull request be considered? Thanks.

lindes avatar Oct 06 '17 17:10 lindes

Because then the behavior would be different if the app loaded successfully or not. Just don't rely on the behavior at all, then both behave equivalently. The config parsing was just a hidden convenience anyway.

davidism avatar Oct 06 '17 18:10 davidism