Python sanic.response.html() Examples

The following are 30 code examples of sanic.response.html(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sanic.response , or try the search function .
Example #1
Source File: core.py    From swagger-ui-py with Apache License 2.0 6 votes vote down vote up
def _aiohttp_handler(self):
        from aiohttp import web

        async def swagger_doc_handler(request):
            return web.Response(text=self.doc_html, content_type='text/html')

        async def swagger_editor_handler(request):
            return web.Response(text=self.editor_html, content_type='text/html')

        async def swagger_config_handler(request):
            return web.json_response(self.get_config(request.host))

        self._app.router.add_get(self._uri(), swagger_doc_handler)
        self._app.router.add_get(self._uri('/'), swagger_doc_handler)

        if self._editor:
            self._app.router.add_get(self._uri('/editor'), swagger_editor_handler)

        self._app.router.add_get(self._uri('/swagger.json'), swagger_config_handler)
        self._app.router.add_static(self._uri('/'), path='{}/'.format(self.static_dir)) 
Example #2
Source File: test_jupyter.py    From idom with MIT License 6 votes vote down vote up
def test_same_origin_jupyter_display(driver, driver_wait, mount, server_url):
    clicked = idom.Var(False)

    @idom.element
    async def SimpleButton(self):
        @idom.event
        async def on_click(event):
            clicked.set(True)

        return idom.html.button(
            {"id": "simple-button", "onClick": on_click}, "click me same origin"
        )

    mount(SimpleButton)
    driver.get(f"{server_url}/__test_jupyter_widget_client__")

    client_button = driver.find_element_by_id("simple-button")
    client_button.click()

    driver_wait.until(lambda d: clicked.get()) 
Example #3
Source File: api_routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def apiui_command_help(request, user):
    template = env.get_template('apiui_command_help.html')
    if len(request.query_args) != 0:
        data = urllib.parse.unquote(request.query_args[0][1])
        query = await db_model.payloadtype_query()
        try:
            payloadtype = await db_objects.get(query, ptype=data)
        except Exception as e:
            data = ""
    else:
        data = ""
    if use_ssl:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="https",
                                  ws="wss", config=user['ui_config'], view_utc_time=user['view_utc_time'], agent=data)
    else:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="http",
                                  ws="ws", config=user['ui_config'], view_utc_time=user['view_utc_time'], agent=data)
    return response.html(content)

# add links to the routes in this file at the bottom 
Example #4
Source File: server.py    From owllook with Apache License 2.0 6 votes vote down vote up
def add_session_to_request(request):
    # before each request initialize a session
    # using the client's request
    host = request.headers.get('host', None)
    user_agent = request.headers.get('user-agent', None)
    if user_agent:
        user_ip = request.headers.get('X-Forwarded-For')
        LOGGER.info('user ip is: {}'.format(user_ip))
        if user_ip in CONFIG.FORBIDDEN:
            return html("<h3>网站正在维护...</h3>")
        if CONFIG.VAL_HOST == 'true':
            if not host or host not in CONFIG.HOST:
                return redirect('http://www.owllook.net')
        if CONFIG.WEBSITE['IS_RUNNING']:
            await app.session_interface.open(request)
        else:
            return html("<h3>网站正在维护...</h3>")
    else:
        return html("<h3>网站正在维护...</h3>") 
Example #5
Source File: novels_blueprint.py    From owllook with Apache License 2.0 6 votes vote down vote up
def chapter(request):
    """
    返回小说章节目录页
    : content_url   这决定当前U页面url的生成方式
    : url           章节目录页源url
    : novels_name   小说名称
    :return: 小说章节内容页
    """
    url = request.args.get('url', None)
    novels_name = request.args.get('novels_name', None)
    netloc = get_netloc(url)
    if netloc not in RULES.keys():
        return redirect(url)
    if netloc in REPLACE_RULES.keys():
        url = url.replace(REPLACE_RULES[netloc]['old'], REPLACE_RULES[netloc]['new'])
    content_url = RULES[netloc].content_url
    content = await cache_owllook_novels_chapter(url=url, netloc=netloc)
    if content:
        content = str(content).strip('[],, Jjs').replace(', ', '').replace('onerror', '').replace('js', '').replace(
            '加入书架', '')
        return template(
            'chapter.html', novels_name=novels_name, url=url, content_url=content_url, soup=content)
    else:
        return text('解析失败,请将失败页面反馈给本站,请重新刷新一次,或者访问源网页:{url}'.format(url=url)) 
Example #6
Source File: core.py    From swagger-ui-py with Apache License 2.0 6 votes vote down vote up
def _sanic_handler(self):
        from sanic import response
        from sanic.blueprints import Blueprint

        swagger_blueprint = Blueprint('swagger_blueprint', url_prefix=self._url_prefix)

        @swagger_blueprint.get('/')
        async def swagger_blueprint_doc_handler(request):
            return response.html(self.doc_html)

        if self._editor:
            @swagger_blueprint.get('/editor')
            async def swagger_blueprint_editor_handler(request):
                return response.html(self.editor_html)

        @swagger_blueprint.get('/swagger.json')
        async def swagger_blueprint_config_handler(request):
            return response.json(self.get_config(request.host))

        swagger_blueprint.static('/', str(self.static_dir))
        self._app.blueprint(swagger_blueprint) 
Example #7
Source File: novels_blueprint.py    From owllook with Apache License 2.0 6 votes vote down vote up
def owllook_register(request):
    """
    用户登录
    :param request:
    :return:
        :   -1  用户名或密码不能为空
        :   0   用户名或密码错误
        :   1   登陆成功
    """
    user = request['session'].get('user', None)
    if user:
        return redirect('/')
    else:
        ver_que_ans = ver_question()
        if ver_que_ans:
            request['session']['index'] = ver_que_ans
            return template(
                'register.html',
                title='owllook - 注册 - 网络小说搜索引擎',
                question=ver_que_ans[1]
            )
        else:
            return redirect('/') 
Example #8
Source File: core.py    From swagger-ui-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, app, app_type=None, config_path=None, config_url=None,
                 url_prefix='/api/doc', title='API doc', editor=False):

        self._app = app
        self._title = title
        self._url_prefix = url_prefix.rstrip('/')
        self._config_url = config_url
        self._config_path = config_path
        self._editor = editor

        assert self._config_url or self._config_path, 'config_url or config_path is required!'

        self._env = Environment(
            loader=FileSystemLoader(str(CURRENT_DIR.joinpath('templates'))),
            autoescape=select_autoescape(['html'])
        )

        if app_type and hasattr(self, '_{}_handler'.format(app_type)):
            getattr(self, '_{}_handler'.format(app_type))()
        else:
            self._auto_match_handler() 
Example #9
Source File: app_based_example.py    From sanic-cors with MIT License 6 votes vote down vote up
def get_exception(request):
    '''
        Since the path matches the regular expression r'/api/*', this resource
        automatically has CORS headers set.

        Browsers will first make a preflight request to verify that the resource
        allows cross-origin POSTs with a JSON Content-Type, which can be simulated
        as:
        $ curl --include -X OPTIONS http://127.0.0.1:5000/exception \
            --header Access-Control-Request-Method:POST \
            --header Access-Control-Request-Headers:Content-Type \
            --header Origin:www.examplesite.com
        >> HTTP/1.0 200 OK
        Content-Type: text/html; charset=utf-8
        Allow: POST, OPTIONS
        Access-Control-Allow-Origin: *
        Access-Control-Allow-Headers: Content-Type
        Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
        Content-Length: 0
        Server: Werkzeug/0.9.6 Python/2.7.9
        Date: Sat, 31 Jan 2015 22:25:22 GMT
    '''
    raise Exception("example") 
Example #10
Source File: app_based_example.py    From sanic-cors with MIT License 6 votes vote down vote up
def hello_world(request):
    '''
        Since the path '/' does not match the regular expression r'/api/*',
        this route does not have CORS headers set.
    '''
    return html('''
<html>
    <head></head>
    <body>
    <h1>Hello CORS!</h1>
    <h3> End to end editable example with jquery! </h3>
    <a class="jsbin-embed" href="http://jsbin.com/zazitas/embed?js,console">JS Bin on jsbin.com</a>
    <script src="//static.jsbin.com/js/embed.min.js?3.35.12"></script>
    </body>
</html>
''') 
Example #11
Source File: test_decorators.py    From sanic-jwt with MIT License 6 votes vote down vote up
def test_redirect_without_url(app):
    sanic_app, sanic_jwt = app

    @sanic_app.route("/index.html")
    def index(request):
        return html("<html><body>Home</body></html>")

    @sanic_app.route("/protected/static")
    @sanic_jwt.protected(redirect_on_fail=True)
    async def my_protected_static(request):
        return text("", status=200)

    request, response = sanic_app.test_client.get("/protected/static")

    assert response.status == 200
    assert response.body == b'<html><body>Home</body></html>'
    assert response.history
    assert response.history[0].status_code == 302 
Example #12
Source File: routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def settings(request, user):
    template = env.get_template('settings.html')
    try:
        query = await db_model.operator_query()
        operator = await db_objects.get(query, username=user['username'])
        op_json = operator.to_json()
        del op_json['ui_config']
        if use_ssl:
            content = template.render(links=await respect_pivot(links, request), name=user['username'], http="https", ws="wss",
                                      op=op_json, config=user['ui_config'], view_utc_time=user['view_utc_time'])
        else:
            content = template.render(links=await respect_pivot(links, request), name=user['username'], http="http", ws="ws",
                                      op=op_json, config=user['ui_config'], view_utc_time=user['view_utc_time'])
        return response.html(content)
    except Exception as e:
        print(e)
        return json({'status': 'error', 'error': 'Failed to find operator'}) 
Example #13
Source File: novels_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def feedback(request):
    return template('feedback.html') 
Example #14
Source File: admin_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def lcxs(request):
    user = request['session'].get('user', None)
    if user:
        return template('admin_lcxs.html',
                        is_login=1,
                        user=user)
    else:
        return redirect('/') 
Example #15
Source File: novels_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def index(request):
    user = request['session'].get('user', None)
    search_ranking = await cache_owllook_search_ranking()
    if user:
        return template('index.html', title='owllook - 网络小说搜索引擎', is_login=1, user=user,
                        search_ranking=search_ranking[:25])
    else:
        return template('index.html', title='owllook - 网络小说搜索引擎', is_login=0, search_ranking=search_ranking[:25]) 
Example #16
Source File: novels_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def template(tpl, **kwargs):
    template = env.get_template(tpl)
    return html(template.render(kwargs)) 
Example #17
Source File: admin_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def template(tpl, **kwargs):
    template = env.get_template(tpl)
    return html(template.render(kwargs)) 
Example #18
Source File: operate_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def template(tpl, **kwargs):
    template = env.get_template(tpl)
    return html(template.render(kwargs)) 
Example #19
Source File: postile.py    From postile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def preview(request):
    """build and return a preview page
    """
    if app.debug:
        template = jinja_env.get_template('index-debug.html')
    else:
        template = jinja_env.get_template('index.html')

    html_content = template.render(host=request.host, scheme=request.scheme)
    return response.html(html_content) 
Example #20
Source File: bp_api.py    From hproxy with MIT License 5 votes vote down vote up
def api_html(request):
    url = request.args.get('url')
    # TODO
    ajax = request.args.get('ajax', 0)
    foreign = request.args.get('foreign', 0)
    if url:
        speed, res_dict = await get_random_proxy(request)
        try:
            proxy = res_dict.get('proxy')
            html_res = await request_url_by_aiohttp(url=url, proxy='http://' + proxy)
            if html_res:
                return json({
                    'status': 1,
                    'info': {
                        'html': html_res,
                        'proxy': proxy
                    },
                    'msg': 'success'
                })
            else:
                return json({
                    'status': -1,
                    'info': {
                        'proxy': proxy,
                        'details': proxy
                    },
                    'msg': 'Crawling failed!'
                })

        except:
            return json({
                'status': -1,
                'msg': 'Crawling failed!'
            })
    else:
        return json({
            'status': -1,
            'msg': 'URL is required'
        }) 
Example #21
Source File: md_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def bookmarks(request):
    user = request['session'].get('user', None)
    if user:
        try:
            motor_db = motor_base.get_db()
            data = await motor_db.user_message.find_one({'user': user})
            if data:
                # 获取所有书签
                bookmarks = data.get('bookmarks', None)
                if bookmarks:
                    result = []
                    for i in bookmarks:
                        item_result = {}
                        bookmark = i.get('bookmark', None)
                        query = parse_qs(urlparse(bookmark).query)
                        item_result['novels_name'] = query.get('novels_name', '')[0] if query.get('novels_name',
                                                                                                  '') else ''
                        item_result['chapter_name'] = query.get(
                            'name', '')[0] if query.get('name', '') else ''
                        item_result['chapter_url'] = query.get('chapter_url', '')[0] if query.get('chapter_url',
                                                                                                  '') else ''
                        item_result['bookmark'] = bookmark
                        item_result['add_time'] = i.get('add_time', '')
                        result.append(item_result)
                    return template('admin_bookmarks.html', title='{user}的书签 - owllook'.format(user=user),
                                    is_login=1,
                                    user=user,
                                    is_bookmark=1,
                                    result=result[::-1])
            return template('admin_bookmarks.html', title='{user}的书签 - owllook'.format(user=user),
                            is_login=1,
                            user=user,
                            is_bookmark=0)
        except Exception as e:
            LOGGER.error(e)
            return redirect('/')
    else:
        return redirect('/') 
Example #22
Source File: test_jupyter.py    From idom with MIT License 5 votes vote down vote up
def application(application):
    @application.route("/__test_jupyter_widget_client__")
    async def jupyter_widget_client(request):
        widget = JupyterDisplay()
        return response.html(widget._repr_html_())

    return application 
Example #23
Source File: latency.py    From python-socketio with MIT License 5 votes vote down vote up
def index(request):
    with open('latency.html') as f:
        return html(f.read()) 
Example #24
Source File: app.py    From python-socketio with MIT License 5 votes vote down vote up
def index(request):
    with open('app.html') as f:
        return html(f.read()) 
Example #25
Source File: app.py    From chrome-prerender with MIT License 5 votes vote down vote up
def _render(prerender: Prerender, url: str, format: str = 'html', proxy: str = '') -> str:
    '''Retry once after TemporaryBrowserFailure occurred.'''
    for i in range(2):
        try:
            return await prerender.render(url, format, proxy)
        except (TemporaryBrowserFailure, asyncio.TimeoutError) as e:
            if i < 1:
                logger.warning('Temporary browser failure: %s, retry rendering %s in 1s', str(e), url)
                await asyncio.sleep(1)
                continue
            raise 
Example #26
Source File: app.py    From chrome-prerender with MIT License 5 votes vote down vote up
def _save_to_cache(key: str, data: bytes, format: str = 'html') -> None:
    try:
        cache.set(key, data, CACHE_LIVE_TIME, format)
    except Exception:
        logger.exception('Error writing cache')
        if sentry:
            sentry.captureException() 
Example #27
Source File: jinja_example.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test(request):
    data = request.json
    return html(template.render(**data))   # 模板页面渲染 
Example #28
Source File: payloads_routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def instantiate_c2profile(request, user):
    template = env.get_template('instantiate_c2profile.html')
    if use_ssl:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="https",
                                  ws="wss", config=user['ui_config'], view_utc_time=user['view_utc_time'])
    else:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="http",
                                  ws="ws", config=user['ui_config'], view_utc_time=user['view_utc_time'])
    return response.html(content) 
Example #29
Source File: payloads_routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def payloads_creation(request, user):
    template = env.get_template('payloads_creation.html')
    if use_ssl:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="https",
                                  ws="wss", config=user['ui_config'], view_utc_time=user['view_utc_time'])
    else:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="http",
                                  ws="ws", config=user['ui_config'], view_utc_time=user['view_utc_time'])
    return response.html(content) 
Example #30
Source File: services_routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def services_host_file(request, user):
    template = env.get_template('services_host_file.html')
    if use_ssl:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="https",
                                  ws="wss", config=user['ui_config'], view_utc_time=user['view_utc_time'])
    else:
        content = template.render(links=await respect_pivot(links, request), name=user['username'], http="http",
                                  ws="ws", config=user['ui_config'], view_utc_time=user['view_utc_time'])
    return response.html(content)

# add links to the routes in this file at the bottom