Пример #1
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')])
Пример #2
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')])
Пример #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')])
Пример #4
0
    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')])
Пример #5
0
def callback(ch, method, properties, body):
    from wsgi import container
    job = pickle.loads(body)
    if inspect.isclass(job):
        job = container.resolve(job)
    job.handle()
    ch.basic_ack(delivery_tag=method.delivery_tag)
Пример #6
0
    def work(self, ch, method, properties, body):
        from wsgi import container
        job = pickle.loads(body)
        obj = job['obj']
        args = job['args']
        callback = job['callback']
        ran = job['ran']

        try:
            try:
                if inspect.isclass(obj):
                    obj = container.resolve(obj)

                getattr(obj, callback)(*args)

            except AttributeError:
                obj(*args)

            self.success('[\u2713] Job Successfully Processed')
        except Exception as e:
            self.danger('Job Failed: {}'.format(str(e)))

            if ran < 3 and isinstance(obj, Queueable):
                time.sleep(1)
                self.push(obj.__class__, args=args, callback=callback, ran=ran + 1)
            else:
                if hasattr(obj, 'failed'):
                    getattr(obj, 'failed')(job, str(e))

                self.add_to_failed_queue_table(job)

        ch.basic_ack(delivery_tag=method.delivery_tag)
Пример #7
0
def callback(ch, method, properties, body):
    from wsgi import container
    job = pickle.loads(body)
    obj = job['obj']
    args = job['args']
    if inspect.isclass(obj):
        obj = container.resolve(obj)
    obj.handle(*args)
    ch.basic_ack(delivery_tag=method.delivery_tag)
Пример #8
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)
    def handle(self):
        from wsgi import container as app
        tasks = app.collect(Task)

        for task_key, task_class in tasks.items():
            # Resolve the task with the container
            task = app.resolve(task_class)

            # If the class should run then run it
            if task.should_run():
                task.handle()
Пример #10
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
Пример #11
0
        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)
Пример #12
0
    def render(self, template):
        self.set_properties()
        from wsgi import container

        if self.request.input('send'):
            self.request.request_variables.update(json.loads(self.request.input('send')))

        if hasattr(self, self.request.input('method', '')):
            container.resolve(getattr(self, self.request.input('method')))

        # Modified state now
        props = {}
        for prop in self.attrs:
            props.update({prop: self.__dict__.get(prop)})

        x = self.view.render(template, props).rendered_template
        x = x.replace("@method=", "@click='handle($event)' method=")
        x = x.replace("prop='", "x-model.lazy='props.")
        x = x.replace('prop="', 'x-model.lazy="props.')
        self.request.cookie('livewire:props', json.dumps(props))
        self.request.header('X-Livewire', json.dumps(props))
        x = x.partition("</template>")[:1][0] + "</template>"
        x = x.replace('template', 'div')
        return x
Пример #13
0
def callback(ch, method, properties, body):
    from wsgi import container
    job = pickle.loads(body)
    obj = job['obj']
    args = job['args']
    callback = job['callback']
    if inspect.isclass(obj):
        obj = container.resolve(obj)

    try:
        getattr(obj, callback)(*args)
    except AttributeError:
        obj(*args)

    ch.basic_ack(delivery_tag=method.delivery_tag)
Пример #14
0
        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)
Пример #15
0
    def work(self, ch, method, _, body):
        from wsgi import container

        job = pickle.loads(body)
        obj = job["obj"]
        args = job["args"]
        callback = job["callback"]
        ran = job["ran"]

        try:
            try:
                if inspect.isclass(obj):
                    obj = container.resolve(obj)

                getattr(obj, callback)(*args)

            except AttributeError:
                obj(*args)

            try:
                self.success("[\u2713] Job Successfully Processed")
            except UnicodeEncodeError:
                self.success("[Y] Job Successfully Processed")
        except Exception as e:
            self.danger("Job Failed: {}".format(str(e)))

            if not obj.run_again_on_fail:
                ch.basic_ack(delivery_tag=method.delivery_tag)
                return

            if ran < obj.run_times and isinstance(obj, Queueable):
                time.sleep(1)
                self.push(obj.__class__,
                          args=args,
                          callback=callback,
                          ran=ran + 1)
            else:
                if hasattr(obj, "failed"):
                    getattr(obj, "failed")(job, str(e))

                self.add_to_failed_queue_table(job)

        ch.basic_ack(delivery_tag=method.delivery_tag)
    def consume(self, channel, **options):  # skipcq
        from config.database import DB as schema, DATABASES
        from wsgi import container

        if not channel or channel == "default":
            channel = DATABASES["default"]

        self.info(
            '[*] Waiting to process jobs from the "queue_jobs" table on the "{}" connection. To exit press CTRL + C'
            .format(channel))
        schema = schema.connection(channel)
        while True:
            builder = schema.table("queue_jobs")
            jobs = builder.where_null("ran_at").where(
                schema.table("queue_jobs").where_null('wait_until').or_where(
                    'wait_until', '<=',
                    pendulum.now().to_datetime_string())).limit(1).get()

            if not jobs.count():
                time.sleep(5)

            for job in jobs:
                builder.where("id", job["id"]).update({
                    "ran_at":
                    pendulum.now().to_datetime_string(),
                })
                unserialized = pickle.loads(job.serialized)
                obj = unserialized["obj"]
                args = unserialized["args"]
                callback = unserialized["callback"]
                ran = job.attempts

                try:
                    try:
                        if inspect.isclass(obj):
                            obj = container.resolve(obj)

                        getattr(obj, callback)(*args)

                    except AttributeError:
                        obj(*args)

                    try:
                        # attempts = 1
                        builder.where("id", job["id"]).update({
                            "ran_at":
                            pendulum.now().to_datetime_string(),
                            "attempts":
                            job["attempts"] + 1,
                        })
                        self.success("[\u2713] Job Successfully Processed")
                    except UnicodeEncodeError:
                        self.success("[Y] Job Successfully Processed")
                except Exception as e:  # skipcq
                    self.danger("Job Failed: {}".format(str(e)))

                    if not obj.run_again_on_fail:
                        # ch.basic_ack(delivery_tag=method.delivery_tag)
                        builder.where("id", job["id"]).update({
                            "ran_at":
                            pendulum.now().to_datetime_string(),
                            "failed":
                            1,
                            "attempts":
                            job["attempts"] + 1,
                        })

                    if ran < obj.run_times and isinstance(obj, Queueable):
                        time.sleep(1)
                        builder.where("id", job["id"]).update(
                            {"attempts": job["attempts"] + 1})
                        continue
                    else:
                        builder.where("id", job["id"]).update({
                            "attempts":
                            job["attempts"] + 1,
                            "ran_at":
                            pendulum.now().to_datetime_string(),
                            "failed":
                            1,
                        })

                        if hasattr(obj, "failed"):
                            getattr(obj, "failed")(unserialized, str(e))

                        self.add_to_failed_queue_table(unserialized,
                                                       driver="database")

            time.sleep(5)
    def consume(self, channel, fair=False, **options):
        from config.database import DB as schema, DATABASES
        from config import queue
        from wsgi import container

        if not channel or channel == 'default':
            channel = DATABASES['default']

        self.info(
            '[*] Waiting to process jobs from the "queue_jobs" table on the "{}" connection. To exit press CTRL + C'
            .format(channel))
        schema = schema.connection(channel)
        while True:
            jobs = schema.table('queue_jobs').where('ran_at', None).get()
            if not jobs.count():
                time.sleep(5)

            for job in jobs:
                unserialized = pickle.loads(job.serialized)
                obj = unserialized['obj']
                args = unserialized['args']
                callback = unserialized['callback']
                ran = job.attempts

                wait_time = job['wait_until']

                if isinstance(wait_time, str):
                    wait_time = pendulum.parse(job['wait_until'])
                else:
                    wait_time = pendulum.instance(job['wait_until'])

                # print(job['wait_until'], wait_time.is_future())
                if job['wait_until'] and wait_time.is_future():
                    continue
                try:
                    try:
                        if inspect.isclass(obj):
                            obj = container.resolve(obj)

                        getattr(obj, callback)(*args)

                    except AttributeError:
                        obj(*args)

                    try:
                        # attempts = 1
                        schema.table('queue_jobs').where(
                            'id', job['id']).update({
                                'ran_at':
                                pendulum.now().to_datetime_string(),
                                'attempts':
                                job['attempts'] + 1,
                            })
                        self.success('[\u2713] Job Successfully Processed')
                    except UnicodeEncodeError:
                        self.success('[Y] Job Successfully Processed')
                except Exception as e:
                    self.danger('Job Failed: {}'.format(str(e)))

                    if not obj.run_again_on_fail:
                        # ch.basic_ack(delivery_tag=method.delivery_tag)
                        schema.table('queue_jobs').where(
                            'id', job['id']).update({
                                'ran_at':
                                pendulum.now().to_datetime_string(),
                                'failed':
                                1,
                                'attempts':
                                job['attempts'] + 1,
                            })

                    if ran < obj.run_times and isinstance(obj, Queueable):
                        time.sleep(1)
                        schema.table('queue_jobs').where(
                            'id', job['id']).update({
                                'attempts':
                                job['attempts'] + 1,
                            })
                        continue
                    else:
                        schema.table('queue_jobs').where(
                            'id', job['id']).update({
                                'attempts':
                                job['attempts'] + 1,
                                'ran_at':
                                pendulum.now().to_datetime_string(),
                                'failed':
                                1,
                            })

                        if hasattr(obj, 'failed'):
                            getattr(obj, 'failed')(unserialized, str(e))

                        self.add_to_failed_queue_table(unserialized,
                                                       driver='database')

            time.sleep(5)
Пример #18
0
def app(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
    """
    |--------------------------------------------------------------------------
    | 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('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([bytes(container.make('Response'), 'utf-8')])
Пример #19
0
 def __init__(self):
     from wsgi import container
     self.message = 'This is a message'
     container.resolve(super().__init__)