Ejemplo n.º 1
0
def main(argv=None):
    args = parse_arguments(argv=argv)

    if args.version:
        print(wikibox.__version__)
        return 0

    try:
        host, port = args.bind.split(':')\
            if ':' in args.bind else ('', args.bind)

        # Change dir
        if relpath(args.directory, '.') != '.':
            chdir(args.directory)

        configure(force=True)

        for f in args.config_files:
            settings.load_file(f)

        quickstart(application=wikibox.WikiBox(), host=host, port=int(port))
    except KeyboardInterrupt:
        print('CTRL+C detected.')
        return -1
    else:
        return 0
Ejemplo n.º 2
0
    def __call__(self, args):
        from nanohttp import Controller, HTTPNotFound, context
        from ..authoring import Story
        with open(args.story) as story_file:
            story = Story.load(story_file)

        class RootMockupController(Controller):
            def __init__(self):
                self.stories = []

            def add_story(self, story):
                self.stories.append(story)

            def server(self, call):
                for k, v in call.response.headers:
                    context.response_headers.add_header(k, v)

                yield call.response.text.encode()

            def __call__(self, *remaining_paths):
                calls = [story.base_call] + story.calls
                for call in calls:
                    url = call.url.replace(':', '')
                    if set(url.strip('/').split('/')) == set(remaining_paths):
                        return self.server(call)

                raise HTTPNotFound()

        from nanohttp import quickstart
        quickstart(RootMockupController())
Ejemplo n.º 3
0
    def launch(self):
        host, port = self.args.bind.split(':') if ':' in self.args.bind else ('', self.args.bind)

        quickstart(
            application=self.args.application,
            host=host,
            port=port
        )
Ejemplo n.º 4
0
 def test_with_application(self):
     shutdown = quickstart(application=self.application,
                           block=False,
                           port=self.port)
     self.assertTrue(callable(shutdown))
     time.sleep(.5)
     shutdown()
Ejemplo n.º 5
0
 def test_with_controller(self):
     shutdown = quickstart(controller=self.Root(),
                           block=False,
                           port=self.port)
     self.assertTrue(callable(shutdown))
     time.sleep(.5)
     shutdown()
Ejemplo n.º 6
0
 def test_before_configure(self):
     settings.__class__._instance = None
     shutdown = quickstart(port=self.port,
                           block=False,
                           config='''
         test_config_item: item1
         ''')
     self.assertTrue(callable(shutdown))
     time.sleep(.5)
     shutdown()
Ejemplo n.º 7
0
 def setUpClass(cls):
     server_port = cls.find_free_port()
     cls._server_shutdown = quickstart(
         controller=FinnotechRootMockController(),
         port=server_port,
         block=False
     )
     cls.api_client = FinnotechApiClient(
         client_id=valid_mock_client_id,
         client_secret=valid_mock_client_secret,
         base_url=f'http://localhost:{server_port}',
         scopes=ALL_SCOPE_CLIENT_CREDENTIALS + ALL_SCOPE_AUTHORIZATION_TOKEN
     )
     super().setUpClass()
Ejemplo n.º 8
0
                    family=context.identity.payload['family'])

    @json
    def post(self):
        if context.form.get('url') is None:
            raise HttpBadRequest()

        url = context.form.get('url')
        if not url.startswith('http'):
            url = f'http://{url}'

        url_exist = DBSession.query(Url).filter_by(url=url).one_or_none()

        if url_exist is None:
            url_exist = Url(url=url)
            DBSession.add(url_exist)
            DBSession.commit()

        hash_id = hashids.encode(url_exist.id)

        return dict(shortener_url=f'http://localhost:8080/urls/{hash_id}')


if __name__ == '__main__':
    from nanohttp import quickstart, configure
    configure()
    try:
        quickstart(Root())
    except KeyboardInterrupt:
        print('CTLR+C just pressed')
Ejemplo n.º 9
0
 def test_without_controller(self):
     shutdown = quickstart(port=self.port, block=False)
     self.assertTrue(callable(shutdown))
     time.sleep(.5)
     shutdown()
Ejemplo n.º 10
0
        yield '<h1>nanohttp demo page</h1>'
        yield '<h2>debug flag is: %s</h2>' % settings.debug
        yield '<img src="/static/cat.jpg" />'
        yield '<ul>'
        yield from ('<li><b>%s:</b> %s</li>' % i
                    for i in context.environ.items())
        yield '</ul>'
        yield '</body></html>'

    @html('post', 'put')
    def contact(self):
        yield '<h1>Thanks: %s</h1>' % context.form['name'] \
            if context.form else 'Please send a name.'

    @html
    def google(self):
        raise HttpFound('http://google.com')

    @html
    def error(self):
        raise Exception()

    @action(content_type='images/png', encoding=None)
    def logo(self):
        yield logo


if __name__ == '__main__':
    from nanohttp import quickstart
    quickstart(Root(), config='<sfsfsd>')
Ejemplo n.º 11
0
        result = func(*args, **kwargs)
        if hasattr(result, 'to_dict'):
            result = result.to_dict()
        elif not isinstance(result, dict):
            raise ValueError(
                'The result must be an instance of dict, not: %s' %
                type(result))

        template_ = lookup.get_template(template_name)
        return template_.render(**result)

    return wrapper


template = functools.partial(action,
                             content_type='text/html',
                             inner_decorator=render_template)


class Root(Controller):
    static = Static(here)

    @template('index.mak')
    def index(self):
        return dict(settings=settings, environ=context.environ)


if __name__ == '__main__':
    from nanohttp import quickstart
    quickstart(Root(), config='')
Ejemplo n.º 12
0
    def launch(self):
        host, port = self.args.bind.split(':') if ':' in self.args.bind else (
            '', self.args.bind)

        quickstart(controller=self.args.application.root, host=host, port=port)
Ejemplo n.º 13
0
 def wrapper(*args, **kw):
     terminate = quickstart(*args, block=False, port=free_port, **kw)
     time.sleep(.1)
     terminators.append(terminate)
     return f'http://localhost:{free_port}'