async def start(self, ctx: Context):
        csv_path = Path(__file__).with_name('people.csv')
        db_path = csv_path.with_name('people.db')

        # Remove any existing db file
        if db_path.exists():
            db_path.unlink()

        self.add_component('sqlalchemy', url='sqlite:///{}'.format(db_path),
                           metadata=Base.metadata)
        await super().start(ctx)

        # Create the table
        Base.metadata.create_all()

        async with threadpool():
            num_rows = 0
            with csv_path.open() as csvfile:
                reader = csv.reader(csvfile, delimiter='|')

                # Import each row into the session as a new Person instance
                for name, city, phone, email in reader:
                    num_rows += 1
                    ctx.dbsession.add(Person(name=name, city=city, phone=phone, email=email))

        logger.info('Imported %d rows of data', num_rows)
        asyncio.get_event_loop().stop()
Beispiel #2
0
    def __await__(self):
        if self._raw_file is None:
            self._raw_file = yield from call_in_executor(
                open, *self._open_args, executor=self._executor, **self._open_kwargs)
            self.flush = threadpool(self._executor)(self._raw_file.flush)
            self.read = threadpool(self._executor)(self._raw_file.read)
            self.readline = threadpool(self._executor)(self._raw_file.readline)
            self.readlines = threadpool(self._executor)(self._raw_file.readlines)
            self.seek = threadpool(self._executor)(self._raw_file.seek)
            self.truncate = threadpool(self._executor)(self._raw_file.truncate)
            self.write = threadpool(self._executor)(self._raw_file.write)
            self.writelines = threadpool(self._executor)(self._raw_file.writelines)

        return self
    async def start(self, ctx: Context):
        self.add_component('py4j')
        await super().start(ctx)

        async with threadpool():
            f = ctx.java.jvm.java.io.File(__file__)
            buffer = ctx.java.new_array(ctx.java.jvm.char, f.length())
            reader = ctx.java.jvm.java.io.FileReader(f)
            reader.read(buffer)
            reader.close()
            print(ctx.java.jvm.java.lang.String(buffer))

        asyncio.get_event_loop().stop()
Beispiel #4
0
    def __await__(self):
        if self._raw_file is None:
            self._raw_file = yield from call_in_executor(
                open,
                *self._open_args,
                executor=self._executor,
                **self._open_kwargs)
            self.flush = threadpool(self._executor)(self._raw_file.flush)
            self.read = threadpool(self._executor)(self._raw_file.read)
            self.readline = threadpool(self._executor)(self._raw_file.readline)
            self.readlines = threadpool(self._executor)(
                self._raw_file.readlines)
            self.seek = threadpool(self._executor)(self._raw_file.seek)
            self.truncate = threadpool(self._executor)(self._raw_file.truncate)
            self.write = threadpool(self._executor)(self._raw_file.write)
            self.writelines = threadpool(self._executor)(
                self._raw_file.writelines)

        return self
    async def begin_request(self, parent_ctx: Context, request: HTTPRequest):
        # Check that the HTTP method was "POST"
        if request.method != 'POST':
            raise HTTPError(405, 'POST required for XML-RPC')

        # Check that the content type is correct
        if request.content_type != 'text/xml':
            raise HTTPError(400, 'Wrong content-type for XML-RPC (must be text/xml)')

        # Parse the XML request
        body = await request.body.read()
        try:
            document = cElementTree.fromstring(body.decode('utf-8'))
        except (UnicodeDecodeError, ParseError) as e:
            raise XMLRPCError(-32701, 'Parse error: %s' % e)

        # Find the requested method name
        methodname = document.find('methodName')
        if not methodname:
            raise XMLRPCError(-32600, 'Server error: invalid xml-rpc')

        # Find the callable by the method name
        method = self.methods.get(methodname)
        if method is None:
            raise XMLRPCError(-32601, 'Server error: method not found')

        # Deserialize the arguments
        param_elements = document.findall('params/param/value')
        try:
            async with threadpool():
                args = [deserialize(element) for element in param_elements]
        except Exception as e:
            raise XMLRPCError(-32602, 'Server error: invalid arguments: %s' % e)

        # Create a request context and call the callable in it
        async with HTTPRequestContext(parent_ctx, self, request) as ctx:
            retval = exception = fault_code = None
            try:
                retval = await method(ctx, *args)
            except XMLRPCError as e:
                exception = e
                fault_code = e.fault_code
            except Exception as e:
                exception = e
                fault_code = -32500
                logger.exception('Error during method invocation')

            # Serialize the return value
            serialized_retval = None
            try:
                serialized_retval = await call_in_executor(serialize, retval)
            except Exception as e:
                exception = e
                fault_code = -32603

        # Finish the request context
        try:
            await ctx.dispatch_event('finished', exception)
        except Exception as e:
            exception = e
            fault_code = -32400
            logger.exception('Error during XML-RPC request context teardown')

        # Generate the methodResponse XML
        if exception is None:
            body = ('<?xml version="1.0"?>\n<methodResponse><params><value>%s'
                    '</value></params></methodResponse>' % serialized_retval)
        else:
            fault = serialize({'faultCode': fault_code, 'faultString': str(exception)})
            body = ('<?xml version="1.0"?>\n<methodResponse><fault>%s'
                    '</fault></methodResponse>' % fault)

        ctx.response.content_type = 'text/xml'