웹사이트 검색

Python Django: Google 인증 및 처음부터 메일 가져오기


Python Django는 개발 프로세스를 단순화하고 개발자가 강력하고 기능이 풍부한 웹 애플리케이션을 만들 수 있도록 하는 기능으로 잘 알려진 강력한 웹 프레임워크입니다. 이 글에서는 Django의 두 가지 주요 기능인 Google 인증과 이메일 가져오기의 통합을 살펴보겠습니다. Django와 Google 인증의 통합을 원활하게 결합하고 Google API 클라이언트 라이브러리를 활용함으로써 개발자는 사용자에게 Google 자격 증명을 사용하여 안전한 로그인 환경을 제공할 수 있습니다. 또한 사용자는 Django 애플리케이션 내에서 Gmail 메시지를 편리하게 가져오고 상호 작용할 수 있습니다.

이 문서에서는 예제 및 출력과 함께 Google 인증 및 이메일 가져오기를 처음부터 구현하는 방법에 대한 단계별 지침을 제공합니다. 메시징 플랫폼, 이메일 기반 애플리케이션을 구축하거나 Django 프로젝트를 개선하려는 경우 이 문서에서는 Google 인증 및 이메일 가져오기를 Django 프로젝트에 원활하게 통합하는 데 필요한 지식과 도구를 제공합니다.

시작하려면 Python 환경에 Django 및 Django−all auth가 설치되어 있는지 확인하세요. pip를 사용하여 설치할 수 있습니다.

pip install django django-allauth

필수 패키지를 설치한 후에는 Django 애플리케이션에서 Google 인증 설정을 시작할 수 있습니다. 먼저 프로젝트의 settings.py 파일을 열고 INSTALLED_APPS 목록에 'allauth' 및 'allauth.account'를 추가합니다.

INSTALLED_APPS = [
    ...
    'allauth',
    'allauth.account',
    ...
]

그런 다음 settings.py 파일에 다음 줄을 추가하여 인증 백엔드를 구성합니다.

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',]

인증 백엔드를 구성한 후 다음 단계는 settings.py 파일에 Google OAuth 자격 증명을 제공하는 것입니다.

예는 다음과 같습니다.

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': ['profile', 'email'],
        'AUTH_PARAMS': {'access_type': 'online'},
    }
}

'client_id' 및 'client_secret' 값을 Google 개발자 콘솔에서 얻은 사용자 인증 정보로 바꿔야 합니다.

인증 설정이 완료되었으므로 이제 로그인 및 로그아웃 기능에 필요한 보기와 템플릿을 생성할 수 있습니다. 예제 코드는 다음과 같습니다.

from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView

class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    client_class = OAuth2Client

urls.py 파일에 다음 코드를 포함하세요.

from .views import GoogleLogin

urlpatterns = [
    ...
    path('accounts/google/login/', GoogleLogin.as_view(), name='google_login'),
    ...
]

이제 템플릿에 링크나 버튼을 포함하여 Google 인증 프로세스를 시작할 수 있습니다. 예를 들어

<a href="{% url 'google_login' %}">Login with Google</a>

제공된 링크를 클릭하면 자체 Google 자격 증명을 사용하여 인증하기 위해 Google 로그인 페이지로 리디렉션됩니다. 인증에 성공하면 Django 애플리케이션으로 원활하게 돌아가 해당 기능을 탐색할 준비가 됩니다. 이제 Python Django와 Google API 클라이언트 라이브러리를 열어 Gmail에서 이메일을 가져와 다양한 Google 서비스와 연결하는 과정을 단순화해 보겠습니다.

먼저 google−api−python−client 패키지가 설치되어 있는지 확인하세요.

pip install google-api-python-client

Gmail에 액세스하려면 Google 개발자 콘솔에서 Gmail API를 활성화해야 합니다. 아직 프로젝트를 만들지 않았다면 새 프로젝트를 만들고, Gmail API를 활성화하고, 프로젝트에 대한 API 자격 증명(OAuth 클라이언트 ID)을 생성하세요.

API 자격 증명이 있으면 이를 사용하여 Gmail API에 대한 액세스를 인증하고 승인할 수 있습니다. Django 프로젝트에서 gmail.py라는 파일을 만들고 다음 코드를 추가합니다.

import os
import pickle
import base64
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

# Define the SCOPES required for accessing Gmail
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def get_gmail_service():
    # Load or create the token file for authentication
    token_file = 'token.pickle'
    creds = None

    if os.path.exists(token_file):
        with open(token_file, 'rb') as token:
            creds = pickle.load(token)
    
    # If there are no valid credentials, authenticate the user
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        
        # Save the credentials for future use
        with open(token_file, 'wb') as token:
            pickle.dump(creds, token)
    
    # Create a Gmail service instance
    service = build('gmail', 'v1', credentials=creds)
    
    return service

def fetch_emails():
    # Get the Gmail service
    service = get_gmail_service()

    # Fetch the emails from the user's Gmail inbox
    results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
    emails = results.get('messages', [])

    if not emails:
        print('No emails found.')
    else:
        print('Emails:')
        for email in emails:
            msg = service.users().messages().get(userId='me', id=email['id']).execute()
            print(f"Subject: {msg['subject']}")
            print(f"From: {msg['from']}")
            print(f"Snippet: {msg['snippet']}")
            print('---')
# Call the fetch_emails() function to test
fetch_emails()

코드에서는 Gmail 액세스에 필요한 범위를 정의하고 필수 라이브러리를 가져옵니다. get_gmail_service() 메소드는 Gmail API에 대한 연결을 설정하고 사용자를 인증합니다. 사용자 자격 증명은 token.pickle 파일에서 안전하게 저장되고 검색됩니다. 이를 통해 Django 애플리케이션 내에서 사용자의 Gmail 계정에 안전하고 효율적으로 액세스할 수 있어 인증 환경이 보장됩니다.

fetch_emails() 함수는 Gmail API 메소드 users().messages().list() 및 users().messages().get()을 사용하여 사용자의 Gmail 받은편지함에서 이메일을 검색합니다. 각 이메일의 제목, 보낸 사람 및 내용을 인쇄합니다.

코드를 실행하고 이메일을 가져오려면 자격 증명.json 파일이 gmail.py 파일과 동일한 디렉터리에 있는지 확인하세요.

예는 다음과 같습니다.

python gmail.py

그러면 사용자가 인증되고 사용자의 Gmail 받은편지함에서 가져온 이메일의 세부정보가 인쇄됩니다.

결론

결론적으로 Python Django는 Google 인증을 구현하고 웹 애플리케이션 내에서 이메일을 가져오는 원활하고 안전한 방법을 제공합니다. Django−allauth와 Google API 클라이언트 라이브러리를 사용하면 사용자가 Google 자격 증명을 사용하여 쉽게 로그인하고 Gmail 받은 편지함에 액세스할 수 있습니다. 이러한 통합은 메시징 시스템, 이메일 분석 등과 같은 이메일 중심 애플리케이션을 구축할 수 있는 광범위한 가능성을 열어줍니다.

Django의 강력한 프레임워크와 강력한 Google API를 사용하여 사용자 인증을 간소화하고 이메일 관련 기능을 향상시키는 기능이 풍부한 애플리케이션을 만들 수 있습니다. Python Django는 Google 인증을 통합하고 처음부터 이메일을 가져오는 프로세스를 정말로 단순화합니다.

관련기사: