У меня трудное время, так как я не мог понять, как перенаправить на предыдущий URL. Когда я тестировал request.referrer 10 дней go, он работал, но теперь он больше не работает, и вместо этого я получаю тот же URL. Я создаю логин Google. Вот код:
@main.route("/post/<int:post_id>", methods=["GET", "POST"])
def post(post_id):
post = Posts.query.filter_by(id=post_id).one()
comments = post.comments
if post == None:
return ('Error')
elif current_user.is_authenticated:
return render_template("show_post0.html", post=post, comments=comments, username=current_user.user_name, userimage=current_user.user_photo)
return render_template("show_post_login.html", post=post, comments=comments)
# redirect to previous url
def redirect_url(default='main.post'):
return request.args.get('next') or \
request.referrer or \
url_for(default)
@main.route("/login/callback")
def callback():
# Get authorization code Google sent back to you
code = request.args.get("code")
# Find out what URL to hit to get tokens that allow you to ask for
# things on behalf of a user
google_provider_cfg = get_google_provider_cfg()
token_endpoint = google_provider_cfg["token_endpoint"]
# Prepare and send request to get tokens! Yay tokens!
token_url, headers, body = client.prepare_token_request(
token_endpoint,
authorization_response=request.url,
redirect_url=request.base_url,
code=code,
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
)
# Parse the tokens!
client.parse_request_body_response(json.dumps(token_response.json()))
# Now that we have tokens (yay) let's find and hit URL
# from Google that gives you user's profile information,
# including their Google Profile Image and Email
userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
uri, headers, body = client.add_token(userinfo_endpoint)
userinfo_response = requests.get(uri, headers=headers, data=body)
# We want to make sure their email is verified.
# The user authenticated with Google, authorized our
# app, and now we've verified their email through Google!
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
users_email = userinfo_response.json()["email"]
picture = userinfo_response.json()["picture"]
users_name = userinfo_response.json()["given_name"]
else:
return "User email not available or not verified by Google.", 400
# Create a user in our db with the information provided
# by Google
author = Author(
google_id=unique_id, user_name=users_name, user_email=users_email, user_photo=picture
)
user = Author.query.filter_by(google_id=unique_id).first()
# Doesn't exist? Add to database
if user:
# Begin user session by logging the user in
login_user(user)
else:
db.session.add(author)
db.session.commit()
login_user(author)
# Send user back to homepage
print("##############", request.args.get('next')) # the result is None
print("##############", request.referrer ) # the result is the same URL when login to Google, so the page keep loading again without returning to the previous page. That's strange because the first time I used this method, it worked perfectly!
return redirect(redirect_url())
Я мог бы перенаправить прямо на маршрут Post, но я хочу использовать этот метод в нескольких маршрутах.
Заранее спасибо!