Python aiohttp.web.HTTPFound() Examples
The following are 30
code examples of aiohttp.web.HTTPFound().
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
aiohttp.web
, or try the search function
.
Example #1
Source File: login_required_example.py From aiohttp-session with Apache License 2.0 | 6 votes |
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
Example #2
Source File: views.py From trace-examples with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #3
Source File: explorer.py From connectrum with MIT License | 6 votes |
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")
Example #4
Source File: ResponseFactory.py From jupiter with MIT License | 6 votes |
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
Example #5
Source File: api.py From mblog with MIT License | 6 votes |
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('/')) # 注销用户
Example #6
Source File: test_http_exception.py From aiohttp-session with Apache License 2.0 | 6 votes |
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'
Example #7
Source File: app.py From Preeminent with MIT License | 6 votes |
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时这个函数才起作用
Example #8
Source File: views.py From aiohttp_admin with Apache License 2.0 | 6 votes |
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)
Example #9
Source File: app.py From pastey with MIT License | 6 votes |
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 {}
Example #10
Source File: views.py From dvpwa with MIT License | 6 votes |
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': {}}
Example #11
Source File: server.py From RPGBot with GNU General Public License v3.0 | 6 votes |
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}")
Example #12
Source File: views.py From dvpwa with MIT License | 6 votes |
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}')
Example #13
Source File: auth_svc.py From caldera with Apache License 2.0 | 6 votes |
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')
Example #14
Source File: test_dict_autz.py From aiohttp-security with Apache License 2.0 | 5 votes |
def test_permits_enum_permission(loop, aiohttp_client): class Permission(enum.Enum): READ = '101' WRITE = '102' UNKNOWN = '103' class Autz(AbstractAuthorizationPolicy): async def permits(self, identity, permission, context=None): if identity == 'UserID': return permission in {Permission.READ, Permission.WRITE} else: return False async def authorized_userid(self, identity): if identity == 'UserID': return 'Andrew' else: return None async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def check(request): ret = await permits(request, Permission.READ) assert ret ret = await permits(request, Permission.WRITE) assert ret ret = await permits(request, Permission.UNKNOWN) assert not ret return web.Response() app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', check) app.router.add_route('POST', '/login', login) client = await aiohttp_client(app) resp = await client.post('/login') assert 200 == resp.status
Example #15
Source File: test_dict_autz.py From aiohttp-security with Apache License 2.0 | 5 votes |
def test_is_anonymous(loop, aiohttp_client): async def index(request): is_anon = await is_anonymous(request) if is_anon: raise web.HTTPUnauthorized() return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def logout(request): response = web.HTTPFound(location='/') await forget(request, response) raise response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status await client.post('/login') resp = await client.get('/') assert web.HTTPOk.status_code == resp.status await client.post('/logout') resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status
Example #16
Source File: api.py From mblog with MIT License | 5 votes |
def signout(request): logging.info('user sign out') return User.signout(web.HTTPFound(request.headers.get('Referer') or '/')) # 取(用户、博客、评论)表的条目
Example #17
Source File: test_dict_autz.py From aiohttp-security with Apache License 2.0 | 5 votes |
def test_login_required(loop, aiohttp_client): with pytest.raises(DeprecationWarning): @login_required async def index(request): return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def logout(request): response = web.HTTPFound(location='/') await forget(request, response) raise response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status await client.post('/login') resp = await client.get('/') assert web.HTTPOk.status_code == resp.status await client.post('/logout') resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status
Example #18
Source File: test_session_identity.py From aiohttp-security with Apache License 2.0 | 5 votes |
def test_forget(make_app, aiohttp_client): async def index(request): session = await get_session(request) return web.Response(text=session.get('AIOHTTP_SECURITY', '')) async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'Andrew') raise response async def logout(request): response = web.HTTPFound('/') await forget(request, response) raise response app = make_app() app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.post('/login') assert 200 == resp.status assert str(resp.url).endswith('/') txt = await resp.text() assert 'Andrew' == txt resp = await client.post('/logout') assert 200 == resp.status assert str(resp.url).endswith('/') txt = await resp.text() assert '' == txt
Example #19
Source File: test_dict_autz.py From aiohttp-security with Apache License 2.0 | 5 votes |
def test_check_authorized(loop, aiohttp_client): async def index(request): await check_authorized(request) return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'UserID') raise response async def logout(request): response = web.HTTPFound(location='/') await forget(request, response) raise response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status await client.post('/login') resp = await client.get('/') assert web.HTTPOk.status_code == resp.status await client.post('/logout') resp = await client.get('/') assert web.HTTPUnauthorized.status_code == resp.status
Example #20
Source File: test_cookies_identity.py From aiohttp-security with Apache License 2.0 | 5 votes |
def test_forget(loop, aiohttp_client): async def index(request): return web.Response() async def login(request): response = web.HTTPFound(location='/') await remember(request, response, 'Andrew') raise response async def logout(request): response = web.HTTPFound(location='/') await forget(request, response) raise response app = web.Application() _setup(app, CookiesIdentityPolicy(), Autz()) app.router.add_route('GET', '/', index) app.router.add_route('POST', '/login', login) app.router.add_route('POST', '/logout', logout) client = await aiohttp_client(app) resp = await client.post('/login') assert 200 == resp.status assert str(resp.url).endswith('/') cookies = client.session.cookie_jar.filter_cookies( client.make_url('/')) assert 'Andrew' == cookies['AIOHTTP_SECURITY'].value resp = await client.post('/logout') assert 200 == resp.status assert str(resp.url).endswith('/') cookies = client.session.cookie_jar.filter_cookies( client.make_url('/')) assert 'AIOHTTP_SECURITY' not in cookies
Example #21
Source File: aiohttp_demo.py From torpeewee with MIT License | 5 votes |
def create_handle(request): data = await request.post() data = data["data"] await Test.create(data=data, created_at=datetime.datetime.now()) return web.HTTPFound('/')
Example #22
Source File: handlers.py From aiohttp-security with Apache License 2.0 | 5 votes |
def login(self, request): response = web.HTTPFound('/') form = await request.post() login = form.get('login') password = form.get('password') db_engine = request.app.db_engine if await check_credentials(db_engine, login, password): await remember(request, response, login) raise response raise web.HTTPUnauthorized( body=b'Invalid username/password combination')
Example #23
Source File: device_tracker.py From HomeAssistantConfig with MIT License | 5 votes |
def get(self, request): # pylint: disable=no-self-use """Finish OAuth callback request.""" hass = request.app['hass'] params = request.query response = web.HTTPFound('/states') if 'state' not in params or 'code' not in params: if 'error' in params: _LOGGER.error( "Error authorizing Automatic: %s", params['error']) return response _LOGGER.error( "Error authorizing Automatic. Invalid response returned") return response if DATA_CONFIGURING not in hass.data or \ params['state'] not in hass.data[DATA_CONFIGURING]: _LOGGER.error("Automatic configuration request not found") return response code = params['code'] state = params['state'] account = hass.data[DATA_CONFIGURING][state] hass.async_create_task(account.initialize_callback(code, state)) return response
Example #24
Source File: utils.py From aiohttp-login with ISC License | 5 votes |
def redirect(urlname, *args, **kwargs): return HTTPFound(url_for(urlname, *args, **kwargs))
Example #25
Source File: factories.py From mblog with MIT License | 5 votes |
def response_factory(app, handler): async def response(request): logging.info('Response handler...') r = await handler(request) if isinstance(r, web.StreamResponse): return r if isinstance(r, bytes): resp = web.Response(body=r) resp.content_type = 'application/octet-stream' return resp 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 None: resp = web.Response(body=json.dumps(r, ensure_ascii=False, default=lambda o: o.__dict__).encode('utf-8')) resp.content_type = 'application/json;charset=utf-8' return resp else: # 如果用jinja2渲染,绑定已验证过的用户 r['__user__'] = request.__user__ resp = web.Response(body=app['__templating__'].get_template(template).render(**r).encode('utf-8')) resp.content_type = 'text/html;charset=utf-8' return resp if isinstance(r, int) and 100 <= r < 600: return web.Response(status=r) if isinstance(r, tuple) and len(r) == 2: status, message = r if isinstance(status, int) and 100 <= status < 600: return web.Response(status=status, text=str(message)) # default resp = web.Response(body=str(r).encode('utf-8')) resp.content_type = 'text/plain;charset=utf-8' return resp return response
Example #26
Source File: simple_example_auth.py From aiohttp-security with Apache License 2.0 | 5 votes |
def handler_logout(request): redirect_response = web.HTTPFound('/') await forget(request, redirect_response) raise redirect_response
Example #27
Source File: handlers.py From Preeminent with MIT License | 5 votes |
def signout(request): # 请求头部的referer,表示从哪里链接到当前页面的,即获得上一个页面 referer = request.headers.get('Referer') # 如果referer为None,则说明无前一个网址,可能是用户新打开了一个标签页,则登陆后转到首页 r = web.HTTPFound(referer or '/') # 通过设置cookie的最大存活时间来删除cookie,从而使登陆状态消失 r.set_cookie(COOKIE_NAME, '-deleted-', max_age=0, httponly=True) logging.info('user signed out.') return r # day11定义 # API:实现获取单条博客信息的功能
Example #28
Source File: WebServer.py From Dell-Support-Assist-RCE-PoC with MIT License | 5 votes |
def handle(request): global filename global PAYLOAD if request.headers["Host"] is not None: if "downloads.dell.com" in request.headers["Host"]: print("[+] Exploit binary requested.") return web.FileResponse(filename) elif "dell.com" in request.headers["Host"]: print("[+] Exploit payload requested.") return web.Response(text=PAYLOAD, headers={'Content-Type': 'text/html'}) redirect_url = "http://dellrce.dell.com" return web.HTTPFound(redirect_url)
Example #29
Source File: app.py From pastey with MIT License | 5 votes |
def get_paste(request): uuid = request.match_info.get('uuid') if not uuid: return {} paste_obj = await Paste.get_object_or_none( db=request.app['db'], uuid=uuid, ) if paste_obj: # Render the page return {'paste_obj': paste_obj.as_dict()} else: # Redirect to homepage return web.HTTPFound('/')
Example #30
Source File: app.py From pastey with MIT License | 5 votes |
def flush_db(request): """ Undocumented endpoint to wipe the DB """ await request.app['db'].flushdb() return web.HTTPFound('https://www.youtube.com/watch?v=dQw4w9WgXcQ')