本文整理汇总了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}")
示例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')
示例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)
示例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)
示例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
示例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'
示例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
示例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)
示例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")
示例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('/'))
# 注销用户
示例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时这个函数才起作用
示例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 {}
示例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': {}}
示例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}')
示例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)