当前位置: 首页>>代码示例>>Python>>正文


Python web.HTTPFound方法代码示例

本文整理汇总了Python中aiohttp.web.HTTPFound方法的典型用法代码示例。如果您正苦于以下问题:Python web.HTTPFound方法的具体用法?Python web.HTTPFound怎么用?Python web.HTTPFound使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在aiohttp.web的用法示例。


在下文中一共展示了web.HTTPFound方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: code

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def code(self, request: web.Request):
        if 'code' not in request.query:
            raise web.HTTPFound("/register?" + urlencode({"redirect": request.url}))

        code = request.query["code"]
        data = {
            "code": code,
            "grant_type": "authorization_code",
            "redirect_uri": "http://api.typheus.me/hub",
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "scope": 'identify guilds'
        }
        response = await self.session.post(
            f"https://discordapp.com/api/oauth2/token",
            data=urlencode(data),
            headers={'Content-Type': "application/x-www-form-urlencoded"}
        )
        js = await response.json()
        if 'error' in js:
            raise web.HTTPServerError(reason=f"Invalid code or redirect {js['error']}")
        token = js['access_token']
        logging.info("Received Discord OAuth2 code, grabbing token")
        raise web.HTTPFound(f"/hub?token={token}") 
开发者ID:henry232323,项目名称:RPGBot,代码行数:26,代码来源:server.py

示例2: login_user

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def login_user(self, request):
        """
        Log a user in and save the session
        :param request:
        :return: the response/location of where the user is trying to navigate
        """
        data = await request.post()
        username = data.get('username')
        password = data.get('password')
        if self.ldap_config:
            verified = await self._ldap_login(username, password)
        else:
            verified = await self._check_credentials(request.app.user_map, username, password)

        if verified:
            self.log.debug('%s logging in:' % username)
            response = web.HTTPFound('/')
            await remember(request, response, username)
            raise response
        self.log.debug('%s failed login attempt: ' % username)
        raise web.HTTPFound('/login') 
开发者ID:mitre,项目名称:caldera,代码行数:23,代码来源:auth_svc.py

示例3: follow_user

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def follow_user(self, request):
        """Adds the current user as follower of the given user."""
        username = request.match_info['username']
        session = await get_session(request)
        user_id = session.get('user_id')

        if not user_id:
            raise web.HTTPNotAuthorized()

        whom_id = await db.get_user_id(self.mongo.user, username)

        if whom_id is None:
            raise web.HTTPFound()

        await self.mongo.follower.update_many(
            {'who_id': ObjectId(user_id)},
            {'$push': {'whom_id': whom_id}}, upsert=True)

        return redirect(request, 'user_timeline', username=username) 
开发者ID:aio-libs,项目名称:aiohttp_admin,代码行数:21,代码来源:views.py

示例4: unfollow_user

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def unfollow_user(self, request):
        """Removes the current user as follower of the given user."""
        username = request.match_info['username']
        session = await get_session(request)
        user_id = session.get('user_id')
        if not user_id:
            raise web.HTTPNotAuthorized()

        whom_id = await db.get_user_id(self.mongo.user, username)
        if whom_id is None:
            raise web.HTTPFound()

        await self.mongo.follower.update_many(
            {'who_id': ObjectId(session['user_id'])},
            {'$pull': {'whom_id': whom_id}})
        return redirect(request, 'user_timeline', username=username) 
开发者ID:aio-libs,项目名称:aiohttp_admin,代码行数:18,代码来源:views.py

示例5: login_required

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def login_required(fn):
    async def wrapped(request, *args, **kwargs):
        app = request.app
        router = app.router

        session = await get_session(request)

        if 'user_id' not in session:
            return web.HTTPFound(router['login'].url_for())

        user_id = session['user_id']
        # actually load user from your database (e.g. with aiopg)
        user = DATABASE[user_id]
        app['user'] = user
        return await fn(request, *args, **kwargs)

    return wrapped 
开发者ID:aio-libs,项目名称:aiohttp-session,代码行数:19,代码来源:login_required_example.py

示例6: test_exceptions

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def test_exceptions(aiohttp_client):

    async def save(request):
        session = await get_session(request)
        session['message'] = 'works'
        raise web.HTTPFound('/show')

    async def show(request):
        session = await get_session(request)
        message = session.get('message')
        return web.Response(text=str(message))

    client = await aiohttp_client(create_app(('/save', save), ('/show', show)))

    resp = await client.get('/save')
    assert resp.status == 200
    assert str(resp.url)[-5:] == '/show'
    text = await resp.text()
    assert text == 'works' 
开发者ID:aio-libs,项目名称:aiohttp-session,代码行数:21,代码来源:test_http_exception.py

示例7: response_factory

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def response_factory(app, handler):
    async def response(request):
        logging.info('%s response_factory response start next handler %s ' % (request.__uuid__, handler))
        r = await handler(request)
        logging.info('%s response_factory response end ' % (request.__uuid__))
        if isinstance(r, str):
            if r.startswith('redirect:'):
                return web.HTTPFound(r[9:])
            resp = web.Response(body=r.encode('utf-8'))
            resp.content_type = 'text/html;charset=utf-8'
            return resp
        if isinstance(r, dict):
            template = r.get('__template__')
            if template is not None:
                resp = web.Response(body=app['__templating__'].get_template(template).render(**r).encode('utf-8'))
                resp.content_type = 'text/html;charset=utf-8'
                return resp
            else:
                resp = web.Response(
                    body=json.dumps(r, ensure_ascii=False).encode('utf-8'))
                resp.content_type = 'application/json;charset=utf-8'
                return resp
        return r

    return response 
开发者ID:dianbaer,项目名称:jupiter,代码行数:27,代码来源:ResponseFactory.py

示例8: vote

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def vote(request):
    async with request.app['db'].acquire() as conn:
        question_id = int(request.match_info['question_id'])
        data = await request.post()
        try:
            choice_id = int(data['choice'])
        except (KeyError, TypeError, ValueError) as e:
            raise web.HTTPBadRequest(
                text='You have not specified choice value') from e
        try:
            await db.vote(conn, question_id, choice_id)
        except db.RecordNotFound as e:
            raise web.HTTPNotFound(text=str(e))
        router = request.app.router
        url = router['results'].url(parts={'question_id': question_id})
        return web.HTTPFound(location=url) 
开发者ID:DataDog,项目名称:trace-examples,代码行数:18,代码来源:views.py

示例9: search

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def search(request):
    query = (await request.post())['q'].strip()

    if not (1 <= len(query) <= 200):
        raise HTTPFound('/')

    if len(query) <= 7:
        raise HTTPFound('/blk/'+query.lower())
    elif len(query) == 64:
        # assume it's a hash of block or txn
        raise HTTPFound('/txn/'+query.lower())
    elif query[0] in '13mn':
        # assume it'a payment address
        raise HTTPFound('/addr/'+query)
    else:
        return Response(text="Can't search for that") 
开发者ID:coinkite,项目名称:connectrum,代码行数:18,代码来源:explorer.py

示例10: oauth2

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def oauth2(code):
    url = 'https://api.weibo.com/oauth2/access_token'
    payload = {
        'client_id': '366603916',
        'client_secret': 'b418efbd77094585d0a7f9ccac98a706',
        'grant_type': 'authorization_code',
        'code': code,
        'redirect_uri': 'http://www.qiangtaoli.com'
    }
    with ClientSession() as session:
        async with session.post(url, data=payload) as resp:
            params = await resp.json()
        async with session.get('https://api.weibo.com/2/users/show.json', params=params) as resp:
            info = await resp.json()
        o = await Oauth.find('weibo-' + info['idstr'])
        if not o:
            return 'redirect:/bootstrap/register?oid=weibo-%s&name=%s&image=%s' % (info['idstr'], info['name'], info['avatar_large'])
        user = await User.find(o.user_id)
        if not user:
            return 'oauth user was deleted.'
        return user.signin(web.HTTPFound('/'))


# 注销用户 
开发者ID:moling3650,项目名称:mblog,代码行数:26,代码来源:api.py

示例11: auth_factory

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def auth_factory(app, handler):
    @asyncio.coroutine
    def auth(request):
        logging.info('check user: %s %s' % (request.method, request.path))
        request.__user__ = None  # 先把请求的__user__属性绑定None
        cookie_str = request.cookies.get(COOKIE_NAME)  # 通过cookie名取得加密cookie字符串,COOKIE_NAME是在headlers模块中定义的
        if cookie_str:
            user = yield from cookie2user(cookie_str)  # 验证cookie,并得到用户信息
            if user:
                logging.info('set current user: %s' % user.email)
                request.__user__ = user  # 将用户信息绑定到请求上
        # 如果请求路径是管理页面,但是用户不是管理员,将重定向到登陆页面
        if request.path.startswith('/manage/') and (request.__user__ is None or not request.__user__.admin):
            return web.HTTPFound('/signin')
        return (yield from handler(request))
    return auth

# 只有当请求方法为POST时这个函数才起作用 
开发者ID:ReedSun,项目名称:Preeminent,代码行数:20,代码来源:app.py

示例12: save_paste

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def save_paste(request):
    post_data = await request.post()
    if post_data:
        title = post_data.get('title')
        body = post_data.get('body', '')
        if title:
            paste_obj = Paste(
                uuid=str(uuid4()),
                created_at=str(datetime.utcnow().isoformat()),
                title=title,
                body=body,
            )
            await paste_obj.save(request.app['db'])
            # redirect to paste page
            return web.HTTPFound('/pastes/{}'.format(paste_obj.uuid))
    return {} 
开发者ID:paxosglobal,项目名称:pastey,代码行数:18,代码来源:app.py

示例13: review

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def review(request: Request):
    app: Application = request.app
    course_id = int(request.match_info['course_id'])
    async with app['db'].acquire() as conn:
        course = await Course.get(conn, course_id)
        if not course:
            raise HTTPNotFound()
        if request.method == 'POST':
            data = await request.post()
            review_text = data.get('review_text')
            if not review_text:
                return {
                    'course': course,
                    'errors': {
                        'review_text': 'this is required field',
                    },
                }
            await Review.create(conn, course_id, review_text)
            raise HTTPFound(f'/courses/{course_id}')
        return {'course': course, 'errors': {}} 
开发者ID:anxolerd,项目名称:dvpwa,代码行数:22,代码来源:views.py

示例14: evaluate

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def evaluate(request: Request):
    app: Application = request.app
    student_id = int(request.match_info['student_id'])
    course_id = int(request.match_info['course_id'])
    data = await request.post()
    async with app['db'].acquire() as conn:
        student = await Student.get(conn, student_id)
        course = await Course.get(conn, course_id)
        if not student or not course:
            raise HTTPNotFound()
        try:
            data = EVALUATE_SCHEMA.check_and_return(data)
        except DataError as e:
            return {'errors': e.as_dict(),
                    'course': course,
                    'student': student}
        await Mark.create(conn, student_id, course_id,
                          data['points'])
    raise HTTPFound(f'/courses/{course_id}') 
开发者ID:anxolerd,项目名称:dvpwa,代码行数:21,代码来源:views.py

示例15: setup_management_ui

# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import HTTPFound [as 别名]
def setup_management_ui(self) -> None:
        ui_base = self.config["server.ui_base_path"]
        if ui_base == "/":
            ui_base = ""
        directory = (self.config["server.override_resource_path"]
                     or pkg_resources.resource_filename("maubot", "management/frontend/build"))
        self.app.router.add_static(f"{ui_base}/static", f"{directory}/static")
        self.setup_static_root_files(directory, ui_base)

        with open(f"{directory}/index.html", "r") as file:
            index_html = file.read()

        @web.middleware
        async def frontend_404_middleware(request: web.Request, handler) -> web.Response:
            if hasattr(handler, "__self__") and isinstance(handler.__self__, web.StaticResource):
                try:
                    return await handler(request)
                except web.HTTPNotFound:
                    return web.Response(body=index_html, content_type="text/html")
            return await handler(request)

        async def ui_base_redirect(_: web.Request) -> web.Response:
            raise web.HTTPFound(f"{ui_base}/")

        self.app.middlewares.append(frontend_404_middleware)
        self.app.router.add_get(f"{ui_base}/", lambda _: web.Response(body=index_html,
                                                                      content_type="text/html"))
        self.app.router.add_get(ui_base, ui_base_redirect) 
开发者ID:maubot,项目名称:maubot,代码行数:30,代码来源:server.py


注:本文中的aiohttp.web.HTTPFound方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。