Python sanic.response.redirect() Examples

The following are 30 code examples of sanic.response.redirect(). 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: google_login.py    From cape-webservices with Apache License 2.0 6 votes vote down vote up
def redirect_login_record_session_google(request):
    success_cb, error_cb, adapter, first_response = oauth_init(request)

    if adapter is None:
        return first_response

    authomatic = Authomatic(config=CONFIG, secret=SECRET_SALT)

    result = authomatic.login(adapter, 'google',
                              # session=session['authomatic'],
                              session_saver=lambda: None)
    if result:
        if result.error:
            warning("Google login error", result.error)
            return response.redirect('%s?error=%s' % (error_cb, result.error))
        elif result.user:
            debug("Google login success", result.user)
            result.user.update()
            debug("Google login update success", result.user)
            userdict = result.user.to_dict()
            return upsert_login_redirect(request, "google:" + userdict['email'], result.user.to_dict(), success_cb, adapter)
    return adapter.response 
Example #2
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 #3
Source File: md_blueprint.py    From owllook with Apache License 2.0 6 votes vote down vote up
def admin_setting(request):
    user = request['session'].get('user', None)
    if user:
        try:
            motor_db = motor_base.get_db()
            data = await motor_db.user.find_one({'user': user})
            if data:
                return template('admin_setting.html', title='{user}的设置 - owllook'.format(user=user),
                                is_login=1,
                                user=user,
                                register_time=data['register_time'],
                                email=data.get('email', '请尽快绑定邮箱'))
            else:
                return text('未知错误')
        except Exception as e:
            LOGGER.error(e)
            return redirect('/')
    else:
        return redirect('/') 
Example #4
Source File: routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def reroute_to_refresh(request, resp):
    resp.headers['Server'] = server_header
    # if you browse somewhere and get greeted with response.json.get('reasons')[0] and "Signature has expired"
    if resp and (resp.status == 403 or resp.status == 401) and resp.content_type == "application/json":
        output = js.loads(resp.body)
        if 'reasons' in output and 'Signature has expired' in output['reasons'][0]:
            # unauthorized due to signature expiring, not invalid auth, redirect to /refresh
            if request.cookies['refresh_token'] and request.cookies['access_token']:
                # auto generate a new
                return response.redirect("/uirefresh")
        if 'exception' in output and output['exception'] == "AuthenticationFailed":
            # authentication failed for one reason or another, redirect them to login
            resp = response.redirect("/login")
            del resp.cookies['access_token']
            del resp.cookies['refresh_token']
            return resp 
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: 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 #7
Source File: test_redirect.py    From sanic with MIT License 6 votes vote down vote up
def test_redirect_with_params(app, test_str):
    use_in_uri = quote(test_str)

    @app.route("/api/v1/test/<test>/")
    async def init_handler(request, test):
        return redirect(f"/api/v2/test/{use_in_uri}/")

    @app.route("/api/v2/test/<test>/")
    async def target_handler(request, test):
        assert test == test_str
        return text("OK")

    _, response = app.test_client.get(f"/api/v1/test/{use_in_uri}/")
    assert response.status == 200

    assert response.content == b"OK" 
Example #8
Source File: _oauth2_flow_dev_test.py    From aiogoogle with MIT License 5 votes vote down vote up
def authorize(request):
    if aiogoogle.oauth2.is_ready(CLIENT_CREDS):
        uri = aiogoogle.oauth2.authorization_url(
            client_creds=CLIENT_CREDS,
            state=state,
            access_type="offline",
            include_granted_scopes=True,
            login_hint=EMAIL,
            prompt="select_account",
        )
        return response.redirect(uri)
    else:
        raise ServerError("Client doesn't have enough info for Oauth2") 
Example #9
Source File: url_for_example.py    From sanic with MIT License 5 votes vote down vote up
def index(request):
    # generate a URL for the endpoint `post_handler`
    url = app.url_for('post_handler', post_id=5)
    # the URL is `/posts/5`, redirect to it
    return response.redirect(url) 
Example #10
Source File: oauth2_async.py    From pyfy with MIT License 5 votes vote down vote up
def authorize(request):
    export_keys()
    client.load_from_env()
    spt.client_creds = client
    if spt.is_oauth_ready:
        return response.redirect(spt.auth_uri(state=state))
    else:
        return (
            json(
                {
                    "error_description": "Client needs client_id, client_secret and a redirect uri in order to handle OAauth properly"
                }
            ),
            500,
        ) 
Example #11
Source File: md_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def book_list(request):
    user = request['session'].get('user', None)
    if user:
        try:
            return template('admin_book_list.html', title='{user}的书单 - owllook'.format(user=user),
                            is_login=1,
                            user=user)
        except Exception as e:
            LOGGER.error(e)
            return redirect('/')
    else:
        return redirect('/') 
Example #12
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 #13
Source File: save_user_creds.py    From pyfy with MIT License 5 votes vote down vote up
def authorize(request):
    export_keys()
    client.load_from_env()
    spt.client_creds = client
    if spt.is_oauth_ready:
        return response.redirect(spt.auth_uri(state=state))
    else:
        return (
            json(
                {
                    "error_description": "Client needs client_id, client_secret and a redirect uri in order to handle OAauth properly"
                }
            ),
            500,
        ) 
Example #14
Source File: md_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def similar_user(request):
    user = request['session'].get('user', None)
    if user:
        try:
            motor_db = motor_base.get_db()
            similar_info = await motor_db.user_recommend.find_one({'user': user})
            if similar_info:
                similar_user = similar_info['similar_user'][:20]
                user_tag = similar_info['user_tag']
                updated_at = similar_info['updated_at']
                return template('similar_user.html',
                                title='与' + user + '相似的书友',
                                is_login=1,
                                is_similar=1,
                                user=user,
                                similar_user=similar_user,
                                user_tag=user_tag,
                                updated_at=updated_at)
            else:
                return template('similar_user.html',
                                title='与' + user + '相似的书友',
                                is_login=1,
                                is_similar=0,
                                user=user)
        except Exception as e:
            LOGGER.error(e)
            return redirect('/')
    else:
        return redirect('/') 
Example #15
Source File: md_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def zongheng(request):
    user = request['session'].get('user', None)
    novels_type = request.args.get('type', '人气榜单').strip()
    first_type_title = "人气榜单"
    first_type = []
    if novels_type in first_type:
        novels_head = [novels_type]
    elif novels_type == first_type_title:
        novels_head = ['#']
    else:
        return redirect('zongheng')
    search_ranking = await cache_others_search_ranking(spider='zongheng', novel_type=novels_type)
    title = "owllook - 纵横小说人气榜单"
    if user:
        return template('index.html',
                        title=title,
                        is_login=1,
                        is_zh=1,
                        is_qidian_model=1,
                        user=user,
                        search_ranking=search_ranking,
                        first_type=first_type,
                        first_type_title=first_type_title,
                        novels_head=novels_head)
    else:
        return template('index.html',
                        title=title,
                        is_login=0,
                        is_qidian_model=1,
                        search_ranking=search_ranking,
                        first_type=first_type,
                        first_type_title=first_type_title,
                        novels_head=novels_head) 
Example #16
Source File: _openid_connect_dev_test.py    From aiogoogle with MIT License 5 votes vote down vote up
def authorize(request):
    if aiogoogle.openid_connect.is_ready(CLIENT_CREDS):
        uri = aiogoogle.openid_connect.authorization_url(
            client_creds=CLIENT_CREDS,
            state=state,
            nonce=nonce,
            access_type="offline",
            include_granted_scopes=True,
            login_hint=EMAIL,
            prompt="select_account",
        )
        # Step A
        return response.redirect(uri)
    else:
        raise ServerError("Client doesn't have enough info for Oauth2") 
Example #17
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 #18
Source File: admin_blueprint.py    From owllook with Apache License 2.0 5 votes vote down vote up
def similar_user(request):
    user = request['session'].get('user', None)
    if user:
        try:
            motor_db = motor_base.get_db()
            similar_info = await motor_db.user_recommend.find_one({'user': user})
            if similar_info:
                similar_user = similar_info['similar_user'][:20]
                user_tag = similar_info['user_tag']
                updated_at = similar_info['updated_at']
                return template('similar_user.html',
                                title='与' + user + '相似的书友',
                                is_login=1,
                                is_similar=1,
                                user=user,
                                similar_user=similar_user,
                                user_tag=user_tag,
                                updated_at=updated_at)
            else:
                return template('similar_user.html',
                                title='与' + user + '相似的书友',
                                is_login=1,
                                is_similar=0,
                                user=user)
        except Exception as e:
            LOGGER.error(e)
            return redirect('/')
    else:
        return redirect('/') 
Example #19
Source File: test_plugin_urlfor.py    From sanicpluginsframework with MIT License 5 votes vote down vote up
def t2(request, context):
    app = context.app
    url_for = context.url_for
    t1 = url_for('t1')
    return redirect(t1) 
Example #20
Source File: app.py    From exchangeratesapi with MIT License 5 votes vote down vote up
def force_ssl(request):
    if request.headers.get("X-Forwarded-Proto") == "http":
        return redirect(request.url.replace("http://", "https://", 1), status=301) 
Example #21
Source File: app.py    From exchangeratesapi with MIT License 5 votes vote down vote up
def force_naked_domain(request):
    if request.host.startswith("www."):
        return redirect(request.url.replace("www.", "", 1), status=301) 
Example #22
Source File: openid_connect.py    From aiogoogle with MIT License 5 votes vote down vote up
def authorize(request):
    if aiogoogle.openid_connect.is_ready(CLIENT_CREDS):
        uri = aiogoogle.openid_connect.authorization_url(
            client_creds=CLIENT_CREDS,
            state=state,
            nonce=nonce,
            access_type="offline",
            include_granted_scopes=True,
            login_hint=EMAIL,
            prompt="select_account",
        )
        # Step A
        return response.redirect(uri)
    else:
        raise ServerError("Client doesn't have enough info for Oauth2")


# ----------------------------------------------#
#                                              #
# **Step B (Check OAuth2 figure above)**       #
#                                              #
# ----------------------------------------------#
# NOTE:                                        #
#  you should now be authorizing your app @    #
#   https://accounts.google.com/o/oauth2/      #
# ----------------------------------------------#

# ----------------------------------------------#
#                                              #
# **Step C, D & E (Check OAuth2 figure above)**#
#                                              #
# ----------------------------------------------#

# Step C
# Google should redirect current_user to
# this endpoint with a grant code 
Example #23
Source File: oauth2.py    From aiogoogle with MIT License 5 votes vote down vote up
def authorize(request):
    if aiogoogle.oauth2.is_ready(CLIENT_CREDS):
        uri = aiogoogle.oauth2.authorization_url(
            client_creds=CLIENT_CREDS,
            state=state,
            access_type="offline",
            include_granted_scopes=True,
            login_hint=EMAIL,
            prompt="select_account",
        )
        # Step A
        return response.redirect(uri)
    else:
        raise ServerError("Client doesn't have enough info for Oauth2")


# ----------------------------------------------#
#                                              #
# **Step B (Check OAuth2 figure above)**       #
#                                              #
# ----------------------------------------------#
# NOTE:                                        #
#  you should now be authorizing your app @    #
#   https://accounts.google.com/o/oauth2/      #
# ----------------------------------------------#

# ----------------------------------------------#
#                                              #
# **Step C, D & E (Check OAuth2 figure above)**#
#                                              #
# ----------------------------------------------#

# Step C
# Google should redirect current_user to
# this endpoint with a grant code 
Example #24
Source File: redirect_example.py    From sanic with MIT License 5 votes vote down vote up
def handle_request(request):
    return response.redirect('/redirect') 
Example #25
Source File: main.py    From idom with MIT License 5 votes vote down vote up
def forward_to_index(request):
    return response.redirect("/docs/index.html") 
Example #26
Source File: delayed_response.py    From sanic with MIT License 5 votes vote down vote up
def handler(request):
    return response.redirect("/sleep/3") 
Example #27
Source File: test_redirect.py    From sanic with MIT License 5 votes vote down vote up
def redirect_app(app):
    @app.route("/redirect_init")
    async def redirect_init(request):
        return redirect("/redirect_target")

    @app.route("/redirect_init_with_301")
    async def redirect_init_with_301(request):
        return redirect("/redirect_target", status=301)

    @app.route("/redirect_target")
    async def redirect_target(request):
        return text("OK")

    @app.route("/1")
    def handler1(request):
        return redirect("/2")

    @app.route("/2")
    def handler2(request):
        return redirect("/3")

    @app.route("/3")
    def handler3(request):
        return text("OK")

    @app.route("/redirect_with_header_injection")
    async def redirect_with_header_injection(request):
        return redirect("/unsafe\ntest-header: test-value\n\ntest-body")

    return app 
Example #28
Source File: routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handler_403(request, exception):
    return response.redirect("/login") 
Example #29
Source File: routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def logout(request, user):
    resp = response.redirect("/login")
    del resp.cookies['access_token']
    del resp.cookies['refresh_token']
    query = await db_model.operator_query()
    operator = await db_objects.get(query, id=user['id'])
    if operator.current_operation is not None:
        await db_objects.create(db_model.OperationEventLog, operator=operator, operation=operator.current_operation,
                                message="Apfell: {} signed out".format(operator.username))
    # now actually invalidate tokens
    await invalidate_refresh_token(user['id'])
    return resp 
Example #30
Source File: routes.py    From Apfell with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        # go here if we're in the browser and our JWT expires so we can update it and continue on
        payload = self.instance.auth.extract_payload(request, verify=True)
        try:
            user = await utils.call(
                self.instance.auth.retrieve_user, request, payload=payload
            )
        except exceptions.MeEndpointNotSetup:
            raise exceptions.RefreshTokenNotImplemented

        user_id = await self.instance.auth._get_user_id(user)
        refresh_token = await utils.call(
            self.instance.auth.retrieve_refresh_token,
            request=request,
            user_id=user_id,
        )
        if isinstance(refresh_token, bytes):
            refresh_token = refresh_token.decode("utf-8")
        token = await self.instance.auth.retrieve_refresh_token_from_request(
            request
        )

        if refresh_token != token:
            raise exceptions.AuthenticationFailed()

        access_token, output = await self.responses.get_access_token_output(
            request, user, self.config, self.instance
        )
        redirect_to = request.headers['referer'] if 'referer' in request.headers else "/"
        resp = response.redirect(redirect_to)
        resp.cookies[self.config.cookie_access_token_name()] = access_token
        resp.cookies[self.config.cookie_access_token_name()]['httponly'] = True
        return resp