Exemple #1
0
def abort(status_code):
    from wsgi import container
    from masonite.response import Response

    response = container.make(Response)
    view = container.make("View")

    return response.view(view("errors/{}".format(status_code)), status=status_code)
Exemple #2
0
    def send(self, message_contents=None):
        """Send the message through SMTP.

        Keyword Arguments:
            message {string} -- The message to be sent to SMTP. (default: {None})

        Returns:
            None
        """
        config = self.config.DRIVERS['smtp']

        message = MIMEMultipart('alternative')

        if not message_contents:
            message_contents = self.message_body

        message_contents = MIMEText(message_contents, 'html')

        message['Subject'] = self.message_subject
        message['From'] = '{0} <{1}>'.format(self.config.FROM['name'],
                                             self.config.FROM['address'])
        message['To'] = self.to_address
        message['Reply-To'] = self.message_reply_to
        message.attach(message_contents)

        # Send the message via our own SMTP server.
        if 'ssl' in config and config['ssl'] is True:
            self.smtp = smtplib.SMTP_SSL('{0}:{1}'.format(
                config['host'], config['port']))
        else:
            self.smtp = smtplib.SMTP('{0}:{1}'.format(config['host'],
                                                      config['port']))

        # Check if TLS enabled
        if 'tls' in config and config['tls'] is True:
            # Define secure TLS connection
            context = ssl.create_default_context()
            context.check_hostname = False

            # Check if correct response code for starttls is received from the server
            if self.smtp.starttls(context=context)[0] != 220:
                raise smtplib.SMTPNotSupportedError(
                    "Server is using untrusted protocol.")

        if config.get('login', True):
            self.smtp.login(config['username'], config['password'])

        if self._queue:
            from wsgi import container
            from ... import Queue
            container.make(Queue).push(self._send_mail,
                                       args=(self.config.FROM['name'],
                                             self.to_address,
                                             message.as_string()))
            return

        self._send_mail(self.config.FROM['name'], self.to_address,
                        message.as_string())
Exemple #3
0
def app(environ, start_response):
    from wsgi import container

    '''
    |--------------------------------------------------------------------------
    | Startup the Service Container
    |--------------------------------------------------------------------------
    |
    | Instantiate the Service Container so we can bind classes into it and 
    | bind the environ variable that is created by the WSGI server into
    | the container.
    |
    '''
    
    container.bind('Environ', environ)

    '''
    |--------------------------------------------------------------------------
    | Execute All Service Providers
    |--------------------------------------------------------------------------
    |
    | Run all service provider boot methods if the wsgi attribute is true.
    |
    '''

    for provider in container.make('Application').PROVIDERS:
        located_provider = locate(provider)().load_app(container)
        if located_provider.wsgi is True:
            container.resolve(located_provider.boot)

    '''
    |--------------------------------------------------------------------------
    | We Are Ready For Launch
    |--------------------------------------------------------------------------
    |
    | If we have a solid response and not redirecting then we need to return
    | a 200 status code along with the data. If we don't, then we'll have
    | to return a 302 and redirect to where the developer would like to
    | go next.
    |
    '''

    start_response(container.make('StatusCode'), container.make('Headers'))

    '''
    |--------------------------------------------------------------------------
    | Final Step
    |--------------------------------------------------------------------------
    |
    | This will take the data variable from above and return it to the WSGI
    | server.
    |
    '''

    return iter([bytes(container.make('Response'), 'utf-8')])
Exemple #4
0
 def load_exception(self, e):
     from wsgi import container
     from masonite.response import Response
     response = container.make(Response)
     request = container.make('Request')
     handler = Handler(e)
     handler.context(
         {'WSGI': {
             'Path': request.path,
             'Input': request.all()
         }})
     response.view(handler.render(), status=500)
Exemple #5
0
    def handle(self):
        from wsgi import container

        if self.option('driver') == 'default':
            queue = container.make(Queue)
        else:
            queue = container.make(Queue).driver(self.option('driver'))

        if self.option('failed'):
            queue.run_failed_jobs()
            return

        queue.connect().consume(self.option('channel'), fair=self.option('fair'))
    def handle(self):
        from wsgi import container

        if self.option("driver") == "default":
            queue = container.make(Queue)
        else:
            queue = container.make(Queue).driver(self.option("driver"))

        if self.option("failed"):
            queue.run_failed_jobs()
            return

        queue.connect().consume(self.option("channel"),
                                fair=self.option("fair"))
        def wrapper(*args, **kwargs):
            from wsgi import container

            request = container.make("Request")
            response = container.make("Response")
            errors = request.validate(*rules)
            if errors:
                if redirect:
                    return response.redirect(redirect).with_errors(
                        errors).with_input()
                if back:
                    return response.back().with_errors(errors).with_input()
                return errors
            else:
                return container.resolve(func)
Exemple #8
0
    def view_helper(errors={}):
        if errors:
            return MessageBag(errors)

        from wsgi import container
        return MessageBag(
            container.make('Request').session.get('errors') or {})
Exemple #9
0
    def send(self, message=None):
        """Send the message through the Mailgun service.

        Keyword Arguments:
            message {string} -- The message to be sent to Mailgun. (default: {None})

        Returns:
            requests.post -- Returns the response as a requests object.
        """
        if message and isinstance(message, str):
            warnings.warn(
                "Passing message to .send() is deprecated. Please use .text() and .html().",
                category=DeprecationWarning,
                stacklevel=2,
            )
            data = self._get_message_for_send_deprecated(message)

        # The above should be removed once deprecation time period passed.
        elif not message:
            data = self.message()
        else:
            data = message

        if self._queue:
            from wsgi import container
            from ... import Queue

            return container.make(Queue).push(self._send_mail, args=(data, ))

        return self._send_mail(data)
Exemple #10
0
    def send(self, message_contents=None):
        """Send the message through SMTP.

        Keyword Arguments:
            message {string} -- The message to be sent to SMTP. (default: {None})

        Returns:
            None
        """
        config = self.config.DRIVERS['smtp']

        message = MIMEMultipart('alternative')

        if not message_contents:
            message_contents = self.message_body

        message_contents = MIMEText(message_contents, 'html')

        message['Subject'] = self.message_subject
        message['From'] = '{0} <{1}>'.format(self.config.FROM['name'],
                                             self.config.FROM['address'])
        message['To'] = self.to_address
        message['Reply-To'] = self.message_reply_to
        message.attach(message_contents)

        # Send the message via our own SMTP server.
        if 'ssl' in config and config['ssl'] is True:
            self.smtp = smtplib.SMTP_SSL('{0}:{1}'.format(
                config['host'], config['port']))
        else:
            self.smtp = smtplib.SMTP('{0}:{1}'.format(config['host'],
                                                      config['port']))

        if config.get('login', True):
            self.smtp.login(config['username'], config['password'])

        if self._queue:
            from wsgi import container
            from ... import Queue
            container.make(Queue).push(self._send_mail,
                                       args=(self.config.FROM['name'],
                                             self.to_address,
                                             message.as_string()))
            return

        self._send_mail(self.config.FROM['name'], self.to_address,
                        message.as_string())
    def handle(self):
        if has_unmigrated_migrations():
            self.comment(
                "\nYou have unmigrated migrations. Run 'craft migrate' to migrate them\n"
            )

        if self.option('live-reload'):
            try:
                from livereload import Server
            except ImportError:
                raise DriverLibraryNotFound(
                    "Could not find the livereload library. Install it by running 'pip install livereload==2.5.1'"
                )

            from wsgi import container
            from config import application
            import glob

            server = Server(container.make('WSGI'))
            for filepath in glob.glob('resources/templates/**/*/'):
                server.watch(filepath)

            self.line('')
            self.info('Live reload server is starting...')
            self.info(
                'This will only work for templates. Changes to Python files may require a browser refresh.'
            )
            self.line('')
            application = server.serve(
                port=self.option('port'),
                restart_delay=self.option('reload-interval'),
                liveport=5500,
                root=application.BASE_DIRECTORY,
                debug=True)
            return

        if not self.option('dont-reload'):
            logger = DefaultLogger(LogLevel.INFO)

            # worker args are pickled and then passed to the new process
            worker_args = [
                self.option("host"),
                self.option("port"),
                "wsgi:application",
            ]

            reloader = Reloader(
                "masonite.commands._devserver.run",
                find_default_monitor_factory(logger),
                logger,
                worker_args=worker_args,
            )

            self._run_reloader(reloader, extra_files=[".env", "storage/"])

        else:
            from wsgi import application
            from ._devserver import run
            run(self.option("host"), self.option("port"), application)
Exemple #12
0
 def wrapper(*args, **kwargs):
     from wsgi import container
     request = container.make('Request')
     errors = request.validate(*rules)
     if errors:
         if redirect:
             return request.redirect(redirect)
         return errors
     else:
         return container.resolve(func)
Exemple #13
0
    def load_exception(self, e):
        from wsgi import container
        from masonite.response import Response
        response = container.make(Response)
        request = container.make('Request')
        handler = Handler(e)
        # handler.integrate(StackOverflowIntegration())
        handler.integrate(SolutionsIntegration())
        handler.context({
            'WSGI': {
                'Path': request.path,
                'Input': request.all() or None,
                'Parameters': request.url_params,
                'Request Method': request.get_request_method()
            },
            'Headers': self.get_headers(request)
        })

        return response.view(handler.render(), status=500)
Exemple #14
0
    def login(self):
        from wsgi import container
        auth = container.make(Auth)

        if (auth.login(self.username, self.password or '')):
            self.failed = False
            self.loggedin = True
            return

        self.failed = True
        self.loggedin = False
Exemple #15
0
def return_with_errors(errors):
    from wsgi import container

    clean_errors = {}
    for error in errors:
        if isinstance(errors[error], list):
            clean_errors.update({error: errors[error]})
        else:
            clean_errors.update({error: [errors[error]]})

    request = container.make("Request")
    return request.back().with_errors(clean_errors)
Exemple #16
0
def app(environ, start_response):
    ''' The WSGI Application Server '''

    from wsgi import container

    '''
    |--------------------------------------------------------------------------
    | Add Environ To Service Container
    |--------------------------------------------------------------------------
    |
    | Add the environ to the service container. The environ is generated by the
    | the WSGI server above and used by a service provider to manipulate the
    | incoming requests
    |
    '''

    container.bind('Environ', environ)

    '''
    |--------------------------------------------------------------------------
    | Execute All Service Providers That Require The WSGI Server
    |--------------------------------------------------------------------------
    |
    | Run all service provider boot methods if the wsgi attribute is true.
    |
    '''

    try:
        for provider in container.make('Application').PROVIDERS:
            located_provider = locate(provider)().load_app(container)
            if located_provider.wsgi is True:
                container.resolve(located_provider.boot)
    except Exception as e:
        container.make('ExceptionHandler').load_exception(e)

    '''
    |--------------------------------------------------------------------------
    | We Are Ready For Launch
    |--------------------------------------------------------------------------
    |
    | If we have a solid response and not redirecting then we need to return
    | a 200 status code along with the data. If we don't, then we'll have
    | to return a 302 redirection to where ever the user would like go
    | to next.
    |
    '''

    start_response(container.make('StatusCode'), container.make('Headers'))

    '''
    |--------------------------------------------------------------------------
    | Final Step
    |--------------------------------------------------------------------------
    |
    | This will take the data variable from the Service Container and return
    | it to the WSGI server.
    |
    '''

    return iter([bytes(container.make('Response'), 'utf-8')])
Exemple #17
0
    def send(self, message=None, message_contents=None):
        """Send the message through SMTP.

        Keyword Arguments:
            message {string} -- The HTML message to be sent to SMTP. (default: {None})

        Returns:
            None
        """
        # The old argument name was `message_contents`. users might have used this as keyword argument or as arg.
        assert (
            message is None or message_contents is None
        ), 'using deprecated  argument "message_contents" together with the new arg "message" ??'
        message_contents = message or message_contents
        if message_contents and isinstance(message_contents, str):
            warnings.warn(
                "Passing message_contents to .send() is a deprecated. Please use .text() and .html().",
                category=DeprecationWarning,
                stacklevel=2,
            )
            message = self._get_message_for_send_deprecated(message_contents)

        # The above should be removed once deprecation time period passed.
        elif not message:
            message = self.message()

        self._smtp_connect()

        if self._queue:
            from wsgi import container
            from ... import Queue

            container.make(Queue).push(
                self._send_mail,
                args=(self.mail_from_header, self.to_addresses, message),
            )
            return

        return self._send_mail(self.mail_from_header, self.to_addresses,
                               message)
        def wrapper(*args, **kwargs):
            from wsgi import container

            request = container.make("Request")

            user = request.user()

            if not user:
                return abort_403()
            elif not user.can(permission):
                return abort_403()

            return container.resolve(function)
Exemple #19
0
def app(environ, start_response):
    ''' The WSGI Application Server '''
    from wsgi import container

    '''
    |--------------------------------------------------------------------------
    | Add Environ To Service Container
    |--------------------------------------------------------------------------
    |
    | Add the environ to the service container. The environ is generated by the
    | the WSGI server above and used by a service provider to manipulate the
    | incoming requests
    |
    '''

    container.bind('Environ', environ)

    '''
    |--------------------------------------------------------------------------
    | Execute All Service Providers That Require The WSGI Server
    |--------------------------------------------------------------------------
    |
    | Run all service provider boot methods if the wsgi attribute is true.
    |
    '''

    try:
        for provider in container.make('WSGIProviders'):
            container.resolve(provider.boot)
    except Exception as e:
        container.make('ExceptionHandler').load_exception(e)

    '''
    |--------------------------------------------------------------------------
    | We Are Ready For Launch
    |--------------------------------------------------------------------------
    |
    | If we have a solid response and not redirecting then we need to return
    | a 200 status code along with the data. If we don't, then we'll have
    | to return a 302 redirection to where ever the user would like go
    | to next.
    |
    '''

    start_response(container.make('StatusCode'), container.make('Headers'))

    '''
    |--------------------------------------------------------------------------
    | Final Step
    |--------------------------------------------------------------------------
    |
    | This will take the data variable from the Service Container and return
    | it to the WSGI server.
    |
    '''

    return iter([bytes(container.make('Response'), 'utf-8')])
Exemple #20
0
def back(location=None):
    """Return an input element for use in telling Masonite which route to redirect back to.

    Arguments:
        location {string} -- The route to redirect back to.

    Returns:
        string -- An input string.
    """
    if location is None:
        from wsgi import container
        location = container.make('Request').path

    return Markup(
        "<input type='hidden' name='__back' value='{0}'>".format(location))
Exemple #21
0
    def send(self, message=None):
        """Send the message through the Mailgun service.

        Keyword Arguments:
            message {string} -- The message to be sent to Mailgun. (default: {None})

        Returns:
            requests.post -- Returns the response as a requests object.
        """

        if self._queue:
            from wsgi import container
            from ... import Queue
            return container.make(Queue).push(self._send_mail, args=(message,))

        return self._send_mail(message)
Exemple #22
0
    def handle(self):
        from wsgi import container

        for provider in container.make("Providers"):
            if provider.__class__.__name__ == self.argument("name"):
                if self.option("tag") != "None":
                    provider.publish(tag=self.option("tag"))
                    provider.publish_migrations(tag=self.option("tag"))

                provider.publish()
                provider.publish_migrations()

                return

        raise ValueError("Could not find the {} provider".format(
            self.argument("name")))
Exemple #23
0
def old(session_key, default=''):
    """Return the old value submitted by forms validated with Valitators.

    Arguments:
        session_key {string} -- The key flashed to session.

    Returns:
        string -- An input string.
    """

    from wsgi import container
    session_container = container.make('Session')

    if session_container.has(session_key):
        return session_container.get(session_key)
    return default
    def handle(self):
        from wsgi import container

        for provider in container.make('Providers'):
            if provider.__class__.__name__ == self.argument('name'):
                if self.option('tag') != 'None':
                    provider.publish(tag=self.option('tag'))
                    provider.publish_migrations(tag=self.option('tag'))

                provider.publish()
                provider.publish_migrations()

                return

        raise ValueError('Could not find the {} provider'.format(
            self.argument('name')))
Exemple #25
0
    def handle(self):
        from wsgi import container

        web_routes = container.make("WebRoutes")

        routes = [["Method", "Path", "Name", "Domain", "Middleware"]]

        for route in web_routes:
            routes.append([
                route.method_type,
                route.route_url,
                route.named_route,
                route.required_domain,
                ",".join(route.list_middleware),
            ])

        print(tabulate(routes, headers="firstrow", tablefmt="rst"))
    def app(self, environ, start_response):
        """The WSGI Application Server.

        Arguments:
            environ {dict} -- The WSGI environ dictionary
            start_response {WSGI callable}

        Returns:
            WSGI Response
        """
        from wsgi import container
        # print('imported', mark - first)

        """Add Environ To Service Container
        Add the environ to the service container. The environ is generated by the
        the WSGI server above and used by a service provider to manipulate the
        incoming requests
        """

        container.bind('Environ', environ)

        """Execute All Service Providers That Require The WSGI Server
        Run all service provider boot methods if the wsgi attribute is true.
        """

        try:
            for provider in container.make('WSGIProviders'):
                container.resolve(provider.boot)
                # print('time took for ', provider, time.time() - start)
                # print()
                # end = end - start
        except Exception as e:
            container.make('ExceptionHandler').load_exception(e)

        """We Are Ready For Launch
        If we have a solid response and not redirecting then we need to return
        a 200 status code along with the data. If we don't, then we'll have
        to return a 302 redirection to where ever the user would like go
        to next.
        """

        start_response(container.make('Request').get_status_code(),
                    container.make('Request').get_and_reset_headers())

        """Final Step
        This will take the data variable from the Service Container and return
        it to the WSGI server.
        """
        return iter([container.make('Response')])
    def validate_input(self, email, name, password):
        from wsgi import container

        validator = container.make("Validator")
        errors = validator.validate(
            {
                "email": email or "",
                "name": name or "",
                "password": password or ""
            },
            validator.required(["email", "name", "password"]),
            validator.email(["email"]),
        )

        users_with_email = User.where("email", email).count()

        if users_with_email >= 1:
            errors.update(
                {"email_exists": ["This email already exists in database"]})

        return errors
Exemple #28
0
    def create_container(self):
        container = App()
        from config import application
        from config import providers

        container.bind('WSGI', generate_wsgi())
        container.bind('Application', application)
        container.bind('Container', container)

        container.bind('ProvidersConfig', providers)
        container.bind('Providers', [])
        container.bind('WSGIProviders', [])

        """Bind all service providers
        Let's register everything into the Service Container. Once everything is
        in the container we can run through all the boot methods. For reasons
        some providers don't need to execute with every request and should
        only run once when the server is started. Providers will be ran
        once if the wsgi attribute on a provider is False.
        """

        for provider in container.make('ProvidersConfig').PROVIDERS:
            located_provider = provider()
            located_provider.load_app(container).register()
            if located_provider.wsgi:
                container.make('WSGIProviders').append(located_provider)
            else:
                container.make('Providers').append(located_provider)

        for provider in container.make('Providers'):
            container.resolve(provider.boot)

        """Get the application from the container
        Some providers may change the WSGI Server like wrapping the WSGI server
        in a Whitenoise container for an example. Let's get a WSGI instance
        from the container and pass it to the application variable. This
        will allow WSGI servers to pick it up from the command line
        """

        return container
        """Execute All Service Providers That Require The WSGI Server
        Run all service provider boot methods if the wsgi attribute is true.
        """

        try:
            for provider in container.make('WSGIProviders'):
                container.resolve(provider.boot)
        except Exception as e:
            container.make('ExceptionHandler').load_exception(e)

        """We Are Ready For Launch
        If we have a solid response and not redirecting then we need to return
        a 200 status code along with the data. If we don't, then we'll have
        to return a 302 redirection to where ever the user would like go
        to next.
        """

        start_response(container.make('Request').get_status_code(),
                    container.make('Request').get_and_reset_headers())

        """Final Step
        This will take the data variable from the Service Container and return
        it to the WSGI server.
        """
        return iter([container.make('Response')])


container = PackageContainer().create()

application = container.make('WSGI')
Exemple #30
0
 def __init__(self, strategy):
     super().__init__(strategy)
     self.view = container.make(View)
     self.response = container.make(Response)
 def upload(self, *args, **kwargs):
     from wsgi import container
     return container.make(Upload).driver('disk').store(*args, **kwargs)