Ensure that the package can be properly configured,
        and then create it.

def create_package(self, output=None):
        """
        Ensure that the package can be properly configured,
        and then create it.

        """

        # Create the Lambda zip package (includes project and virtualenvironment)
        # Also define the path the handler file so it can be copied to the zip
        # root for Lambda.
        current_file = os.path.dirname(os.path.abspath(
            inspect.getfile(inspect.currentframe())))
        handler_file = os.sep.join(current_file.split(os.sep)[0:]) + os.sep + 'handler.py'

        # Create the zip file(s)
        if self.stage_config.get('slim_handler', False):
            # Create two zips. One with the application and the other with just the handler.
            # https://github.com/Miserlou/Zappa/issues/510
            self.zip_path = self.zappa.create_lambda_zip(
                prefix=self.lambda_name,
                use_precompiled_packages=self.stage_config.get('use_precompiled_packages', True),
                exclude=self.stage_config.get('exclude', []),
                disable_progress=self.disable_progress,
                archive_format='tarball'
            )

            # Make sure the normal venv is not included in the handler's zip
            exclude = self.stage_config.get('exclude', [])
            cur_venv = self.zappa.get_current_venv()
            exclude.append(cur_venv.split('/')[-1])
            self.handler_path = self.zappa.create_lambda_zip(
                prefix='handler_{0!s}'.format(self.lambda_name),
                venv=self.zappa.create_handler_venv(),
                handler_file=handler_file,
                slim_handler=True,
                exclude=exclude,
                output=output,
                disable_progress=self.disable_progress
            )
        else:

            # Custom excludes for different versions.
            # Related: https://github.com/kennethreitz/requests/issues/3985
            if sys.version_info[0] < 3:
                # Exclude packages already builtin to the python lambda environment
                # Related: https://github.com/Miserlou/Zappa/issues/556
                exclude = self.stage_config.get(
                        'exclude', [
                                        "boto3",
                                        "dateutil",
                                        "botocore",
                                        "s3transfer",
                                        "six.py",
                                        "jmespath",
                                        "concurrent"
                                    ])
            else:
                # This could be python3.6 optimized.
                exclude = self.stage_config.get(
                        'exclude', [
                                        "boto3",
                                        "dateutil",
                                        "botocore",
                                        "s3transfer",
                                        "concurrent"
                                    ])

            # Create a single zip that has the handler and application
            self.zip_path = self.zappa.create_lambda_zip(
                prefix=self.lambda_name,
                handler_file=handler_file,
                use_precompiled_packages=self.stage_config.get('use_precompiled_packages', True),
                exclude=exclude,
                output=output,
                disable_progress=self.disable_progress
            )

            # Warn if this is too large for Lambda.
            file_stats = os.stat(self.zip_path)
            if file_stats.st_size > 52428800:  # pragma: no cover
                print('\n\nWarning: Application zip package is likely to be too large for AWS Lambda. '
                      'Try setting "slim_handler" to true in your Zappa settings file.\n\n')

        # Throw custom settings into the zip that handles requests
        if self.stage_config.get('slim_handler', False):
            handler_zip = self.handler_path
        else:
            handler_zip = self.zip_path

        with zipfile.ZipFile(handler_zip, 'a') as lambda_zip:

            settings_s = "# Generated by Zappa\n"

            if self.app_function:
                if '.' not in self.app_function: # pragma: no cover
                    raise ClickException("Your " + click.style("app_function", fg='red', bold=True) + " value is not a modular path." +
                        " It needs to be in the format `" + click.style("your_module.your_app_object", bold=True) + "`.")
                app_module, app_function = self.app_function.rsplit('.', 1)
                settings_s = settings_s + "APP_MODULE='{0!s}'\nAPP_FUNCTION='{1!s}'\n".format(app_module, app_function)

            if self.exception_handler:
                settings_s += "EXCEPTION_HANDLER='{0!s}'\n".format(self.exception_handler)
            else:
                settings_s += "EXCEPTION_HANDLER=None\n"

            if self.debug:
                settings_s = settings_s + "DEBUG=True\n"
            else:
                settings_s = settings_s + "DEBUG=False\n"

            settings_s = settings_s + "LOG_LEVEL='{0!s}'\n".format((self.log_level))

            if self.binary_support:
                settings_s = settings_s + "BINARY_SUPPORT=True\n"
            else:
                settings_s = settings_s + "BINARY_SUPPORT=False\n"

            head_map_dict = {}
            head_map_dict.update(dict(self.context_header_mappings))
            settings_s = settings_s + "CONTEXT_HEADER_MAPPINGS={0}\n".format(
                head_map_dict
            )

            # If we're on a domain, we don't need to define the /<<env>> in
            # the WSGI PATH
            if self.domain:
                settings_s = settings_s + "DOMAIN='{0!s}'\n".format((self.domain))
            else:
                settings_s = settings_s + "DOMAIN=None\n"

            if self.base_path:
                settings_s = settings_s + "BASE_PATH='{0!s}'\n".format((self.base_path))
            else:
                settings_s = settings_s + "BASE_PATH=None\n"

            # Pass through remote config bucket and path
            if self.remote_env:
                settings_s = settings_s + "REMOTE_ENV='{0!s}'\n".format(
                    self.remote_env
                )
            # DEPRECATED. use remove_env instead
            elif self.remote_env_bucket and self.remote_env_file:
                settings_s = settings_s + "REMOTE_ENV='s3://{0!s}/{1!s}'\n".format(
                    self.remote_env_bucket, self.remote_env_file
                )

            # Local envs
            env_dict = {}
            if self.aws_region:
                env_dict['AWS_REGION'] = self.aws_region
            env_dict.update(dict(self.environment_variables))

            # Environment variable keys must be ascii
            # https://github.com/Miserlou/Zappa/issues/604
            # https://github.com/Miserlou/Zappa/issues/998
            try:
                env_dict = dict((k.encode('ascii').decode('ascii'), v) for (k, v) in env_dict.items())
            except Exception:
                raise ValueError("Environment variable keys must be ascii.")

            settings_s = settings_s + "ENVIRONMENT_VARIABLES={0}\n".format(
                    env_dict
                )

            # We can be environment-aware
            settings_s = settings_s + "API_STAGE='{0!s}'\n".format((self.api_stage))
            settings_s = settings_s + "PROJECT_NAME='{0!s}'\n".format((self.project_name))

            if self.settings_file:
                settings_s = settings_s + "SETTINGS_FILE='{0!s}'\n".format((self.settings_file))
            else:
                settings_s = settings_s + "SETTINGS_FILE=None\n"

            if self.django_settings:
                settings_s = settings_s + "DJANGO_SETTINGS='{0!s}'\n".format((self.django_settings))
            else:
                settings_s = settings_s + "DJANGO_SETTINGS=None\n"

            # If slim handler, path to project zip
            if self.stage_config.get('slim_handler', False):
                settings_s += "ARCHIVE_PATH='s3://{0!s}/{1!s}_{2!s}_current_project.tar.gz'\n".format(
                    self.s3_bucket_name, self.api_stage, self.project_name)

                # since includes are for slim handler add the setting here by joining arbitrary list from zappa_settings file
                # and tell the handler we are the slim_handler
                # https://github.com/Miserlou/Zappa/issues/776
                settings_s += "SLIM_HANDLER=True\n"

                include = self.stage_config.get('include', [])
                if len(include) >= 1:
                    settings_s += "INCLUDE=" + str(include) + '\n'

            # AWS Events function mapping
            event_mapping = {}
            events = self.stage_config.get('events', [])
            for event in events:
                arn = event.get('event_source', {}).get('arn')
                function = event.get('function')
                if arn and function:
                    event_mapping[arn] = function
            settings_s = settings_s + "AWS_EVENT_MAPPING={0!s}\n".format(event_mapping)

            # Map Lext bot events
            bot_events = self.stage_config.get('bot_events', [])
            bot_events_mapping = {}
            for bot_event in bot_events:
                event_source = bot_event.get('event_source', {})
                intent = event_source.get('intent')
                invocation_source = event_source.get('invocation_source')
                function = bot_event.get('function')
                if intent and invocation_source and function:
                    bot_events_mapping[str(intent) + ':' + str(invocation_source)] = function

            settings_s = settings_s + "AWS_BOT_EVENT_MAPPING={0!s}\n".format(bot_events_mapping)

            # Map cognito triggers
            cognito_trigger_mapping = {}
            cognito_config = self.stage_config.get('cognito', {})
            triggers = cognito_config.get('triggers', [])
            for trigger in triggers:
                source = trigger.get('source')
                function = trigger.get('function')
                if source and function:
                    cognito_trigger_mapping[source] = function
            settings_s = settings_s + "COGNITO_TRIGGER_MAPPING={0!s}\n".format(cognito_trigger_mapping)

            # Authorizer config
            authorizer_function = self.authorizer.get('function', None)
            if authorizer_function:
                settings_s += "AUTHORIZER_FUNCTION='{0!s}'\n".format(authorizer_function)

            # Copy our Django app into root of our package.
            # It doesn't work otherwise.
            if self.django_settings:
                base = __file__.rsplit(os.sep, 1)[0]
                django_py = ''.join(os.path.join(base, 'ext', 'django_zappa.py'))
                lambda_zip.write(django_py, 'django_zappa_app.py')

            # async response
            async_response_table = self.stage_config.get('async_response_table', '')
            settings_s += "ASYNC_RESPONSE_TABLE='{0!s}'\n".format(async_response_table)

            # Lambda requires a specific chmod
            temp_settings = tempfile.NamedTemporaryFile(delete=False)
            os.chmod(temp_settings.name, 0o644)
            temp_settings.write(bytes(settings_s, "utf-8"))
            temp_settings.close()
            lambda_zip.write(temp_settings.name, 'zappa_settings.py')
            os.unlink(temp_settings.name)