플라스크에서 URL로 리디렉션
나는 파이톤과 플라스크를 처음 접하고, 그에 준하는 일을 하려고 한다.Response.redirect
C# - 예: 특정 URL로 리디렉션 - 이 작업은 어떻게 진행하시겠습니까?
내 암호는 다음과 같다.
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
리디렉션을 반환해야 하는 경우:
import os
from flask import Flask,redirect
app = Flask(__name__)
@app.route('/')
def hello():
return redirect("http://www.example.com", code=302)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
플라스크 문서에 대한 설명서를 참조하십시오.코드의 기본값은 302이므로code=302
생략하거나 다른 리디렉션 코드(301, 302, 303, 305 및 307 중 하나)로 대체할 수 있다.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def hello():
return redirect(url_for('foo'))
@app.route('/foo')
def foo():
return 'Hello Foo!'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
설명서의 예를 살펴보십시오.
Plask API 설명서(2.0.x):
플라스크.redirect(flask()
location
,code=302
,Response=None
)클라이언트를 대상 위치로 리디렉션하는 응답 개체(WSGI 응용 프로그램)를 반환한다.지원되는 코드는 301, 302, 303, 305, 307이며, 실제 리디렉션이 아니므로 300은 지원되지 않으며, If-Modified-Phores 헤더가 정의된 요청이 있는 요청에 대한 응답이기 때문에 304는 지원되지 않는다.
버전 0.6의 새로운 기능: 위치는 이제 iri_to_uri() 함수를 사용하여 인코딩되는 유니코드 문자열일 수 있다.
매개 변수:
location
– 응답을 리디렉션해야 하는 위치.code
- 리디렉션 상태 코드. 기본값은 302.Response
(class) – 응답을 인스턴스화할 때 사용할 응답 클래스.기본값은 werkzeug.wrappers 입니다.지정되지 않은 경우 응답.
나는 이 질문이 업데이트될 가치가 있다고 믿는다.다른 접근 방식과 비교해 보십시오.
플라스크(0.12.2)에서 한 URL에서 다른 URL로 리디렉션(3xx)을 수행하는 방법은 다음과 같다.
#!/usr/bin/env python
from flask import Flask, redirect
app = Flask(__name__)
@app.route("/")
def index():
return redirect('/you_were_redirected')
@app.route("/you_were_redirected")
def redirected():
return "You were redirected. Congrats :)!"
if __name__ == "__main__":
app.run(host="0.0.0.0",port=8000,debug=True)
다른 공식적인 언급은, 여기.
플라스크는 다음을 포함한다.redirect
모든 URL로 리디렉션하는 기능.더 나아가, 에러 코드로 요청을 조기에 중단할 수 있다.abort
:
from flask import abort, Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def hello():
return redirect(url_for('hello'))
@app.route('/hello'):
def world:
abort(401)
기본적으로 각 오류 코드에 대해 흑백 오류 페이지가 표시된다.
그redirect
방법은 기본적으로 코드 302를 사용한다.여기에 http 상태 코드에 대한 목록.
flask.redirect(location, code=302)
닥터는 여기서 찾을 수 있다.
만약 당신이 어떤 상태 코드나 간단히 말할 수 있는 어떤 것 없이 URL로 리디렉션하기를 원한다면 그것은 꽤 쉽다.
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/')
def redirect_to_link():
# return redirect method, NOTE: replace google.com with the link u want
return redirect('https://google.com')
이것을 위해 당신은 간단히 다음 것을 사용할 수 있다.redirect
에 포함된 함수flask
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/')
def hello():
return redirect("https://www.exampleURL.com", code = 302)
if __name__ == "__main__":
app.run()
플라스크를 처음 접하는 다른 유용한 팁은 다음과 같다.app.debug = True
디버거 출력으로 플라스크 객체를 초기화한 후 무엇이 문제인지 알아내는 동안 많은 도움이 된다.
다음과 같이 사용할 수 있다.
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
# Redirect from here, replace your custom site url "www.google.com"
return redirect("https://www.google.com", code=200)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
플라스크에서 사용자 / 요청을 리디렉션하는 방법
API 핸들러 함수 내부에 오류를 던지면 사용자가 리디렉션을 처리할 수 있는 오류 핸들러로 리디렉션된다.아니면 그냥 전화해서redirect
다른 사람들이 말하는 것처럼, 하지만 이것은 허가받지 않은 사용자를 리디렉션하는 또 다른 방법이다.내 말뜻을 설명하기 위해, 나는 아래에 예를 제공했다.
사용자에게 권한이 부여되어야 하는 경우
먼저 이렇게 보호되는 보호 경로가 있다고 가정해 봅시다.
def handle_api_auth(func):
"""
**handle_api_auth**
wrapper to handle public api calls authentications
:param func: a function to be wrapped
:return: wrapped function
"""
@functools.wraps(func)
def auth_wrapper(*args, **kwargs):
api_key: Optional[str] = request.headers.get('x-api-key')
secret_token: Optional[str] = request.headers.get('x-secret-token')
domain: Optional[str] = request.base_url
if is_request_valid(api_key=api_key, secret=secret_token, domain=domain):
return func(*args, **kwargs)
# NOTE: throwing an Error Here will redirect your user to an error handler or alteratively you can just call redirect like everyone else is saying, but this is another way of redirecting unathorized users
message: str = "request not authorized"
raise UnAuthenticatedError(status=error_codes.un_auth_error_code, description=message)
return auth_wrapper
is_request_valid의 정의는 다음과 같다.
@app_cache.cache.memoize(timeout=15 * 60, cache_none=False) # timeout equals fifteen minutes // 900 seconds
def is_request_valid(api_key: str, secret: str, domain: str) -> bool:
"""
**is_api_key_valid**
validates api keys on behalf of client api calls
:param api_key: str -> api_key to check
:param secret: str -> secret token
:param domain: str -> domain registered for the api_key and secret_token
:return: bool -> True if api_key is valid
"""
organization_id: str = config_instance.ORGANIZATION_ID
# NOTE: lets assumy api_keys_view.get_api_key will return the api keys from some database somewhere
response = api_keys_view.get_api_key(api_key=api_key, organization_id=organization_id)
response_data, status_code = response
response_dict = response_data.get_json()
if not response_dict.get('status'):
return False
api_instance: dict = response_dict.get('payload')
if not isinstance(api_instance, dict):
return False
domain: str = domain.lower().strip()
# NOTE accessing the keys this way will throw ValueError if keys are not available which is what we want
# Any Error which gets thrown Ridirects the Users from the path the user is on to an error handler.
is_secret_valid: bool = hmac.compare_digest(api_instance['secret_token'], secret)
is_domain_valid: bool = hmac.compare_digest(api_instance['domain'], domain)
_request_valid: bool = is_secret_valid and is_domain_valid
return not not api_instance.get('is_active') if _request_valid else False
다음과 같은 오류 처리기 정의
from flask import Blueprint, jsonify, request, redirect
from werkzeug.exceptions Unauthorized
error_handler = BluePrint('error_handlers', __name__)
@error_handler.app_errorhandler(Unauthorized)
def handle_error(e : Unauthorized) -> tuple:
"""default unath handler"""
return jsonify(dict(message=e.description)), e.code if request.headers.get('content-type') == 'application/json' else redirect('/login')
다른 오류도 동일하게 처리하고 경우에 따라 요청이 수행되었음을 주지한다.
사용자가 무절제한 응답을 보내면 사용자가 로그인 페이지로 리디렉션되는 json이 아니라 Unath Errors를 처리하는 것이 프런트 엔드까지입니다.
플라스크에서 URL로 리디렉션할 수 있는 두 가지 방법이 있다.
- 예를 들어 로그인한 후 사용자를 다른 경로로 리디렉션하려는 경우 등
- 다음과 같은 변수 예를 예상하는 경로로 사용자를 리디렉션할 수도 있다.
@app.route('/post/<string:post_id>')
#1 사례에 대한 플라스크 리디렉션을 구현하려면 간단하다. 그냥 다음과 같이 하십시오.
from flask import Flask,redirect,render_template,url_for
app = Flask(__name__)
@app.route('/login')
def login():
# if user credentials are valid, redirect to user dashboard
if login == True:
return redirect(url_for(app.dashboard))
else:
print("Login failed !, invalid credentials")
return render_template('login.html',title="Home Page")
@app.route('/dashboard')
def dashboard():
return render_template('dashboard.html',title="Dashboard")
사례 #2에 대해 플라스크 리디렉션을 구현하려면 다음을 수행하십시오.
from flask import Flask,redirect,render_template,url_for
app = Flask(__name__)
@app.route('/home')
def home():
# do some logic, example get post id
if my_post_id:
# **Note:** post_id is the variable name in the open_post route
# We need to pass it as **post_id=my_post_id**
return redirect(url_for(app.open_post,post_id=my_post_id))
else:
print("Post you are looking for does not exist")
return render_template('index.html',title="Home Page")
@app.route('/post/<string:post_id>')
def open_post():
return render_template('readPost.html',title="Read Post")
같은 일을 관점으로 볼 수 있다.
<a href="{{url_for(app.open_post,post_id=my_post_id)}}"></a>
고go: 리리션는는을 하십시오.app.home
또는app.something..
(기능 이름 보기 또는 보기)를 사용하지 않고redirect("/home")
는, 를 . 에서하면. 이이: 로로 수정이 되는 것은 이다."/home"
로"/index/page"
어떤 이유에서인지, 그러면 너의 코드가 깨질 것이다.
참조URL: https://stackoverflow.com/questions/14343812/redirecting-to-url-in-flask
'Programing' 카테고리의 다른 글
rollBehavior는 Nuxt의 전체 페이지에 영향을 미친다. (0) | 2022.03.25 |
---|---|
구문 오류: 어휘적으로 바인딩된 이름으로 허용 안 함 (0) | 2022.03.24 |
React 앱에서 무한 루프/충돌을 일으키는 이유는? (0) | 2022.03.24 |
Numpy 배열과 행렬의 차이점은 무엇인가?어떤 걸로 할까? (0) | 2022.03.24 |
반응에서 소품으로 사용되는 패싱 배열 (0) | 2022.03.24 |