Итак, я пытаюсь перенаправить свое веб-приложение django после того, как пользователь отправил форму И если пользователь выбрал опцию «Ссылка на Strava» в форме.
Что я сейчас делаю нужно открыть страницу авторизации API Strava для обмена кодом/токеном, чтобы мое приложение получало данные из учетной записи пользователя Strava.
Моя текущая проблема заключается в том, что оно не перенаправляется на мой Страница авторизации Strava API (нет ошибки, ничего), и я попытался распечатать URL-адрес авторизации, чтобы можно было отладить ее. Я попробовал вручную открыть URL-адрес авторизации, и он работает.
Я просмотрел несколько руководств по Strava API с использованием Python, и все они вручную вводят ссылку для копирования кода после того, как пользователь нажал кнопку ' Авторизовано».
Правильен ли мой метод?
Отправка формы -> Перенаправить пользователя на авторизацию API Strava
Страница (зависла на этом шаге) -> Обратный вызов для возврата кода/токена ->
Извлечение данных
Вот мой текущий код внутри
Код: Выделить всё
views.py
Код: Выделить всё
async def index(request):
if request.method == 'POST': #Start of process after Form Submitted
try:
data_dict = link_validation(request, data_dict)
#Rest of the code Here (Irrelevant and not related to Strava API)
except Exception as e:
return render(request, 'index.html', {'error_message': str(e)})
else:
return render(request, 'index.html')
def link_validation(request, data_dict):
redirect_to_strava_auth(request)
#Rest of the code logic here to be put when Strava API Authorization is solved
def redirect_to_strava_auth(request):
auth_url = f"https://www.strava.com/oauth/authorize?client_id={STRAVA_CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&approval_prompt=force&scope=read,profile:read_all,activity:read"
print("Redirect URL:", auth_url) #Prints a valid link and I tried opening it in browser manually, it works
return redirect(auth_url) #This is the problem I can't solve (Not producing any error, just no redirection)
#This function will be executed right after the user clicked the 'Authorize' on my Strava API
def exchange_code_for_token(request):
code = request.GET.get('code')
token_url = "https://www.strava.com/oauth/token"
payload = {
'client_id': STRAVA_CLIENT_ID,
'client_secret': STRAVA_CLIENT_SECRET,
'code': code,
'grant_type': 'authorization_code'
}
response = requests.post(token_url, data=payload)
if response.status_code == 200:
access_token = response.json()['access_token']
# Save access_token to the user session or database
return HttpResponseRedirect('/index/') # Redirect to success page or any other page
else:
return HttpResponse("Error exchanging code for access token")

Here's the current step by step demo of my current progress on youtube video
(Ignore the error message that appeared in card as it is not related to API Redirection).
YOUTUBE: django strava API redirection to auth page not working
Alternative Solution Idea (In case my method won't really work) - Via JavaScript:
Conditional Check on javascript if auth code already exists -> Put the
Authorization Page as
Код: Выделить всё
the link -> User Authorizes my API -> Redirect back to my django app
along with Auth Code/Token and store it in session -> Pass the code when form is submitted to
Код: Выделить всё
views.py
Источник: https://stackoverflow.com/questions/781 ... ot-working