찾다
백엔드 개발파이썬 튜토리얼TDD 방법론과 PostgreSQL을 사용하여 Django로 완전한 블로그 앱을 구축하기 위한 가이드(부분 보안 사용자 인증)

여러분, 다시 오신 것을 환영합니다! 이전 부분에서는 Django 블로그 애플리케이션에 대한 보안 사용자 등록 프로세스를 구축했습니다. 그러나 성공적으로 등록한 후 홈페이지로 리디렉션되었습니다. 이 동작은 사용자 인증을 구현하면 수정됩니다. 사용자 인증은 승인된 사용자만 특정 기능에 액세스할 수 있도록 보장하고 민감한 정보를 보호합니다.
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
이 시리즈에서는 다음 ERD(Entity-Relationship Diagram)에 따라 완전한 블로그 애플리케이션을 구축합니다. 이번에는 안전한 사용자 인증 프로세스를 설정하는 데 중점을 둘 것입니다. 이 콘텐츠가 도움이 되셨다면 좋아요, 댓글, 구독을 눌러주세요 다음 편이 공개될 때에도 최신 소식을 받아보실 수 있습니다.
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
이것은 로그인 기능을 구현한 후 로그인 페이지가 어떻게 보일지에 대한 미리보기입니다. 시리즈의 이전 부분을 아직 읽어보지 않으셨다면, 이 튜토리얼이 이전 단계의 연속이므로 읽어보시길 권장합니다.

자, 시작해 보겠습니다 !!

Django에는 사용자 인증 처리를 단순화하는 contrib.auth라는 앱이 내장되어 있습니다. blog_env/settings.py 파일을 확인하면 INSTALLED_APPS 아래에 인증이 이미 나열되어 있는 것을 볼 수 있습니다.

# django_project/settings.py
INSTALLED_APPS = [
    # "django.contrib.admin",
    "django.contrib.auth",  # 



<p>auth 앱은 로그인, 로그아웃, 비밀번호 변경, 비밀번호 재설정 등을 처리하기 위한 여러 인증 보기를 제공합니다. 이는 사용자 로그인, 등록, 권한과 같은 필수 인증 기능을 별도의 작업 없이 사용할 수 있음을 의미합니다. 처음부터 모든 것을 구축합니다.</p>

<p>이 튜토리얼에서는 로그인 및 로그아웃 보기에만 초점을 맞추고 나머지 보기는 시리즈 후반부에서 다룰 것입니다.</p>

<h2>
  
  
  1. 로그인 양식 만들기
</h2>

<p>TDD 접근 방식에 따라 로그인 양식에 대한 테스트를 만드는 것부터 시작해 보겠습니다. 아직 로그인 양식을 만들지 않았으므로 users/forms.py 파일로 이동하여 AuthenticationForm을 상속하는 새 클래스를 만듭니다.<br>
</p>

<pre class="brush:php;toolbar:false"># users/forms.py
from django.contrib.auth import AuthenticationForm

class LoginForm(AuthenticationForm):


양식이 정의되면 users/tests/test_forms.py에 테스트 사례를 추가하여 기능을 확인할 수 있습니다.

# users/tests/test_forms.py

#   --- other code

class LoginFormTest(TestCase):
  def setUp(self):
    self.user = User.objects.create_user(
      full_name= 'Tester User',
      email= 'tester@gmail.com',
      bio= 'new bio for tester',
      password= 'password12345'
    )

  def test_valid_credentials(self):
    """
    With valid credentials, the form should be valid
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'password12345',
      'remember_me': False
    }

    form = LoginForm(data = credentials)
    self.assertTrue(form.is_valid())

  def test_wrong_credentials(self):
    """
    With wrong credentials, the form should raise Invalid email or password error
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'wrongpassword',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertIn('Invalid email or password', str(form.errors['__all__']))

  def test_credentials_with_empty_email(self):
    """
    Should raise an error when the email field is empty
    """
    credentials = {
      'email': '',
      'password': 'password12345',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['email']))

  def test_credentials_with_empty_password(self):
    """
    Should raise error when the password field is empty
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': '',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['password']))

이러한 테스트에서는 유효한 자격 증명으로 로그인 성공, 잘못된 자격 증명으로 로그인 실패, 오류 메시지를 적절하게 처리하는 등의 시나리오를 다룹니다.

AuthenticationForm 클래스는 기본적으로 몇 가지 기본 유효성 검사를 제공합니다. 그러나 LoginForm을 사용하면 특정 요구 사항을 충족하기 위해 동작을 맞춤화하고 필요한 유효성 검사 규칙을 추가할 수 있습니다.

# django_project/settings.py
INSTALLED_APPS = [
    # "django.contrib.admin",
    "django.contrib.auth",  # 



<p>우리는 <strong>이메일</strong>, <strong>비밀번호</strong> 및 <strong>remember_me</strong> 필드를 포함하는 사용자 정의 로그인 양식을 만들었습니다. Remember_me 확인란을 사용하면 사용자가 브라우저 세션 전반에 걸쳐 로그인 세션을 유지할 수 있습니다.</p>

<p>우리 양식은 AuthenticationForm을 확장하므로 일부 기본 동작을 재정의했습니다.</p>

  • ** __init__ 메소드**: 이메일 기반 인증에 맞춰 양식에서 기본 사용자 이름 필드를 제거했습니다.
  • clean() 메소드: 이 메소드는 이메일 및 비밀번호 필드의 유효성을 검사합니다. 자격 증명이 유효하면 Django에 내장된 인증 메커니즘을 사용하여 사용자를 인증합니다.
  • confirm_login_allowed() 메소드: 이 내장 메소드는 로그인 전 추가 확인 기회를 제공합니다. 필요한 경우 이 메서드를 재정의하여 사용자 지정 검사를 구현할 수 있습니다. 이제 테스트를 통과해야 합니다.
# users/forms.py
from django.contrib.auth import AuthenticationForm

class LoginForm(AuthenticationForm):


2. 로그인 뷰 생성

2.1 로그인 보기에 대한 테스트 만들기

아직 로그인에 대한 뷰가 없으므로 users/views.py 파일로 이동하여 인증 앱의 LoginView를 상속하는 새 클래스를 생성해 보겠습니다

# users/tests/test_forms.py

#   --- other code

class LoginFormTest(TestCase):
  def setUp(self):
    self.user = User.objects.create_user(
      full_name= 'Tester User',
      email= 'tester@gmail.com',
      bio= 'new bio for tester',
      password= 'password12345'
    )

  def test_valid_credentials(self):
    """
    With valid credentials, the form should be valid
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'password12345',
      'remember_me': False
    }

    form = LoginForm(data = credentials)
    self.assertTrue(form.is_valid())

  def test_wrong_credentials(self):
    """
    With wrong credentials, the form should raise Invalid email or password error
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'wrongpassword',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertIn('Invalid email or password', str(form.errors['__all__']))

  def test_credentials_with_empty_email(self):
    """
    Should raise an error when the email field is empty
    """
    credentials = {
      'email': '',
      'password': 'password12345',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['email']))

  def test_credentials_with_empty_password(self):
    """
    Should raise error when the password field is empty
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': '',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['password']))

users/tests/test_views.py 파일 하단에 다음 테스트 사례를 추가하세요

# users/forms.py

# -- other code
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AuthenticationForm # new line
from django.contrib.auth import get_user_model, authenticate # new line


# --- other code

class LoginForm(AuthenticationForm):
  email = forms.EmailField(
    required=True,
    widget=forms.EmailInput(attrs={'placeholder': 'Email','class': 'form-control',})
  )
  password = forms.CharField(
    required=True,
    widget=forms.PasswordInput(attrs={
                                'placeholder': 'Password',
                                'class': 'form-control',
                                'data-toggle': 'password',
                                'id': 'password',
                                'name': 'password',
                                })
  )
  remember_me = forms.BooleanField(required=False)

  def __init__(self, *args, **kwargs):
    super(LoginForm, self).__init__(*args, **kwargs)
    # Remove username field

    if 'username' in self.fields:
      del self.fields['username']

  def clean(self):
    email = self.cleaned_data.get('email')
    password = self.cleaned_data.get('password')

    # Authenticate using email and password
    if email and password:
      self.user_cache = authenticate(self.request, email=email, password=password)
      if self.user_cache is None:
        raise forms.ValidationError("Invalid email or password")
      else:
        self.confirm_login_allowed(self.user_cache)
    return self.cleaned_data

  class Meta:
    model = User
    fields = ('email', 'password', 'remember_me')

이 단계에서는 이러한 테스트가 실패하는지 확인해야 합니다.

2.2 로그인 뷰 생성

파일 하단의 users/views.py 파일에 아래 코드를 추가하세요.

(.venv)$ python3 manage.py test users.tests.test_forms
Found 9 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.........
----------------------------------------------------------------------
Ran 9 tests in 3.334s
OK
Destroying test database for alias 'default'...

위 코드에서는 다음을 수행합니다.

  • form_class 속성 설정: 더 이상 기본 AuthenticationForm을 사용하지 않으므로 사용자 정의 LoginForm을 form_class 속성으로 지정합니다.
  • form_valid 메서드 재정의: 유효한 양식 데이터가 게시될 때 호출되는 form_valid 메서드를 재정의합니다. 이를 통해 사용자가 성공적으로 로그인한 후 사용자 정의 동작을 구현할 수 있습니다.
  • 세션 만료 처리: 사용자가 Remember_me 상자를 선택하지 않으면 브라우저를 닫을 때 세션이 자동으로 만료됩니다. 그러나 Remember_me 상자를 선택하면 settings.py에 정의된 기간 동안 세션이 지속됩니다. 기본 세션 길이는 2주이지만 settings.py의 SESSION_COOKIE_AGE 변수를 사용하여 이를 수정할 수 있습니다. 예를 들어 쿠키 수명을 7일로 설정하려면 설정에 다음 줄을 추가하면 됩니다.
# -- other code 
from .forms import CustomUserCreationForm, LoginForm
from django.contrib.auth import get_user_model, views
# -- other code

class CustomLoginView(views.LoginForm):


맞춤형 로그인 기능을 연결하고 사용자가 로그인 페이지에 액세스할 수 있도록 하기 위해 users/urls.py 파일에 URL 패턴을 정의합니다. 이 파일은 특정 URL(이 경우 /log_in/)을 해당 보기(CustomLoginView)에 매핑합니다. 또한 Django에 내장된 LogoutView를 사용하여 로그아웃 기능에 대한 경로를 포함할 것입니다.

# django_project/settings.py
INSTALLED_APPS = [
    # "django.contrib.admin",
    "django.contrib.auth",  # 



<p>모든 것이 순조롭게 진행된 것 같지만 로그인 및 로그아웃 성공 시 사용자를 리디렉션할 위치를 지정해야 합니다. 이를 위해 LOGIN_REDIRECT_URL 및 LOGOUT_REDIRECT_URL 설정을 사용합니다. blog_app/settings.py 파일 하단에 다음 줄을 추가하여 사용자를 홈페이지로 리디렉션하세요.<br>
</p>

<pre class="brush:php;toolbar:false"># users/forms.py
from django.contrib.auth import AuthenticationForm

class LoginForm(AuthenticationForm):


이제 로그인 URL이 있으므로 가입이 성공하면 로그인 페이지로 리디렉션되도록 users/views.py 파일에서 SignUpView를 업데이트하겠습니다.

# users/tests/test_forms.py

#   --- other code

class LoginFormTest(TestCase):
  def setUp(self):
    self.user = User.objects.create_user(
      full_name= 'Tester User',
      email= 'tester@gmail.com',
      bio= 'new bio for tester',
      password= 'password12345'
    )

  def test_valid_credentials(self):
    """
    With valid credentials, the form should be valid
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'password12345',
      'remember_me': False
    }

    form = LoginForm(data = credentials)
    self.assertTrue(form.is_valid())

  def test_wrong_credentials(self):
    """
    With wrong credentials, the form should raise Invalid email or password error
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'wrongpassword',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertIn('Invalid email or password', str(form.errors['__all__']))

  def test_credentials_with_empty_email(self):
    """
    Should raise an error when the email field is empty
    """
    credentials = {
      'email': '',
      'password': 'password12345',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['email']))

  def test_credentials_with_empty_password(self):
    """
    Should raise error when the password field is empty
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': '',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['password']))

또한 새로운 동작을 반영하고 변경 사항이 제대로 테스트되도록 SignUpText, 특히 test_signup_corright_data(self)를 업데이트할 예정입니다.

# users/forms.py

# -- other code
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AuthenticationForm # new line
from django.contrib.auth import get_user_model, authenticate # new line


# --- other code

class LoginForm(AuthenticationForm):
  email = forms.EmailField(
    required=True,
    widget=forms.EmailInput(attrs={'placeholder': 'Email','class': 'form-control',})
  )
  password = forms.CharField(
    required=True,
    widget=forms.PasswordInput(attrs={
                                'placeholder': 'Password',
                                'class': 'form-control',
                                'data-toggle': 'password',
                                'id': 'password',
                                'name': 'password',
                                })
  )
  remember_me = forms.BooleanField(required=False)

  def __init__(self, *args, **kwargs):
    super(LoginForm, self).__init__(*args, **kwargs)
    # Remove username field

    if 'username' in self.fields:
      del self.fields['username']

  def clean(self):
    email = self.cleaned_data.get('email')
    password = self.cleaned_data.get('password')

    # Authenticate using email and password
    if email and password:
      self.user_cache = authenticate(self.request, email=email, password=password)
      if self.user_cache is None:
        raise forms.ValidationError("Invalid email or password")
      else:
        self.confirm_login_allowed(self.user_cache)
    return self.cleaned_data

  class Meta:
    model = User
    fields = ('email', 'password', 'remember_me')

2.3 로그인용 템플릿 만들기

그런 다음 텍스트 편집기를 사용하여 users/templates/registration/login.html 파일을 만들고 다음 코드를 포함합니다.

(.venv)$ python3 manage.py test users.tests.test_forms
Found 9 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.........
----------------------------------------------------------------------
Ran 9 tests in 3.334s
OK
Destroying test database for alias 'default'...

이 시리즈 후반부에 비밀번호 찾기 기능을 추가할 예정이지만 지금은 데드 링크일 뿐입니다.
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
이제 로그인, 가입 및 로그아웃 링크를 포함하도록 레이아웃.html 템플릿을 업데이트하겠습니다.

# -- other code 
from .forms import CustomUserCreationForm, LoginForm
from django.contrib.auth import get_user_model, views
# -- other code

class CustomLoginView(views.LoginForm):


우리 템플릿에서는 사용자가 인증되었는지 확인합니다. 사용자가 로그인한 경우 로그아웃 링크와 사용자의 전체 이름이 표시됩니다. 그렇지 않으면 로그인 및 가입 링크가 표시됩니다.
이제 모든 테스트를 실행해 보겠습니다

# users/tests/test_views.py

# -- other code

class LoginTests(TestCase):
  def setUp(self):
    User.objects.create_user(
      full_name= 'Tester User',
      email= 'tester@gmail.com',
      bio= 'new bio for tester',
      password= 'password12345'
    )
    self.valid_credentials = {
      'email': 'tester@gmail.com',
      'password': 'password12345',
      'remember_me': False
    }

  def test_login_url(self):
    """User can navigate to the login page"""
    response = self.client.get(reverse('users:login'))
    self.assertEqual(response.status_code, 200)

  def test_login_template(self):
    """Login page render the correct template"""
    response = self.client.get(reverse('users:login'))
    self.assertTemplateUsed(response, template_name='registration/login.html')
    self.assertContains(response, '<a class="btn btn-outline-dark text-white" href="/users/sign_up/">Sign Up</a>')

  def test_login_with_valid_credentials(self):
    """User should be log in when enter valid credentials"""
    response = self.client.post(reverse('users:login'), self.valid_credentials, follow=True)
    self.assertEqual(response.status_code, 200)
    self.assertRedirects(response, reverse('home'))
    self.assertTrue(response.context['user'].is_authenticated)
    self.assertContains(response, '<button type="submit" class="btn btn-danger"><i class="bi bi-door-open-fill"></i> Log out</button>')

  def test_login_with_wrong_credentials(self):
    """Get error message when enter wrong credentials"""
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'wrongpassword',
      'remember_me': False
    }

    response = self.client.post(reverse('users:login'), credentials, follow=True)
    self.assertEqual(response.status_code, 200)
    self.assertContains(response, 'Invalid email or password')
    self.assertFalse(response.context['user'].is_authenticated)

3. 브라우저에서 모든 것이 정상적으로 작동하는지 테스트합니다.

이제 로그인 및 로그아웃 기능을 구성했으므로 웹 브라우저에서 모든 것을 테스트할 차례입니다. 개발서버를 시작해보자

# django_project/settings.py
INSTALLED_APPS = [
    # "django.contrib.admin",
    "django.contrib.auth",  # 



<p>등록 페이지로 이동하여 유효한 자격 증명을 입력하세요. 등록이 성공적으로 완료되면 로그인 페이지로 리디렉션됩니다. 로그인 양식에 사용자 정보를 입력한 후 로그인 후 로그아웃 버튼을 클릭하세요. 그런 다음 로그아웃하고 홈페이지로 리디렉션되어야 합니다. 마지막으로 더 이상 로그인되어 있지 않은지, 가입 및 로그인 링크가 다시 표시되는지 확인하세요.<br>
모든 것이 완벽하게 작동하지만 사용자가 로그인하여 http://127.0.0.1:8000/users/sign_up/의 등록 페이지를 방문하면 여전히 등록 양식에 액세스할 수 있는 것으로 나타났습니다. 이상적으로는 사용자가 로그인한 후에는 가입 페이지에 액세스할 수 없어야 합니다.<br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172924669044575.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication"><br>
이 동작은 우리 프로젝트에 여러 가지 보안 취약점을 초래할 수 있습니다. 이 문제를 해결하려면 로그인한 모든 사용자를 홈 페이지로 리디렉션하도록 SignUpView를 업데이트해야 합니다.<br>
하지만 먼저 LoginTest를 업데이트하여 시나리오를 다루는 새 테스트를 추가해 보겠습니다. 따라서 users/tests/test_views.py에 이 코드를 추가하세요.<br>
</p>

<pre class="brush:php;toolbar:false"># users/forms.py
from django.contrib.auth import AuthenticationForm

class LoginForm(AuthenticationForm):


이제 SignUpView를 업데이트할 수 있습니다

# users/tests/test_forms.py

#   --- other code

class LoginFormTest(TestCase):
  def setUp(self):
    self.user = User.objects.create_user(
      full_name= 'Tester User',
      email= 'tester@gmail.com',
      bio= 'new bio for tester',
      password= 'password12345'
    )

  def test_valid_credentials(self):
    """
    With valid credentials, the form should be valid
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'password12345',
      'remember_me': False
    }

    form = LoginForm(data = credentials)
    self.assertTrue(form.is_valid())

  def test_wrong_credentials(self):
    """
    With wrong credentials, the form should raise Invalid email or password error
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': 'wrongpassword',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertIn('Invalid email or password', str(form.errors['__all__']))

  def test_credentials_with_empty_email(self):
    """
    Should raise an error when the email field is empty
    """
    credentials = {
      'email': '',
      'password': 'password12345',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['email']))

  def test_credentials_with_empty_password(self):
    """
    Should raise error when the password field is empty
    """
    credentials = {
      'email': 'tester@gmail.com',
      'password': '',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['password']))

위 코드에서는 SignUpView의 dispatch() 메서드를 재정의하여 이미 로그인하여 등록 페이지에 액세스하려고 하는 모든 사용자를 리디렉션합니다. 이 리디렉션은 settings.py 파일에 설정된 LOGIN_REDIRECT_URL을 사용하며, 이 경우 홈 페이지를 가리킵니다.
좋아요! 다시 한 번 모든 테스트를 실행하여 업데이트가 예상대로 작동하는지 확인하겠습니다

# users/forms.py

# -- other code
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AuthenticationForm # new line
from django.contrib.auth import get_user_model, authenticate # new line


# --- other code

class LoginForm(AuthenticationForm):
  email = forms.EmailField(
    required=True,
    widget=forms.EmailInput(attrs={'placeholder': 'Email','class': 'form-control',})
  )
  password = forms.CharField(
    required=True,
    widget=forms.PasswordInput(attrs={
                                'placeholder': 'Password',
                                'class': 'form-control',
                                'data-toggle': 'password',
                                'id': 'password',
                                'name': 'password',
                                })
  )
  remember_me = forms.BooleanField(required=False)

  def __init__(self, *args, **kwargs):
    super(LoginForm, self).__init__(*args, **kwargs)
    # Remove username field

    if 'username' in self.fields:
      del self.fields['username']

  def clean(self):
    email = self.cleaned_data.get('email')
    password = self.cleaned_data.get('password')

    # Authenticate using email and password
    if email and password:
      self.user_cache = authenticate(self.request, email=email, password=password)
      if self.user_cache is None:
        raise forms.ValidationError("Invalid email or password")
      else:
        self.confirm_login_allowed(self.user_cache)
    return self.cleaned_data

  class Meta:
    model = User
    fields = ('email', 'password', 'remember_me')

성취해야 할 일이 더 많다는 것을 알고 있지만, 지금까지 달성한 ​​성과에 대해 잠시 감사해 보도록 하겠습니다. 우리는 함께 프로젝트 환경을 설정하고 PostgreSQL 데이터베이스를 연결했으며 Django 블로그 애플리케이션을 위한 보안 사용자 등록 및 로그인 시스템을 구현했습니다. 다음 부분에서는 사용자 프로필 페이지 만들기, 사용자가 자신의 정보를 편집할 수 있는 방법 및 비밀번호 재설정에 대해 알아보겠습니다! Django 블로그 앱 여정을 계속하면서 더욱 흥미로운 발전을 기대해주세요!

여러분의 피드백은 언제나 소중합니다. 아래 의견에 귀하의 생각, 질문 또는 제안 사항을 공유해 주십시오. 최신 소식을 받아보려면 좋아요, 댓글 남기기, 구독하기를 잊지 마세요!

위 내용은 TDD 방법론과 PostgreSQL을 사용하여 Django로 완전한 블로그 앱을 구축하기 위한 가이드(부분 보안 사용자 인증)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Python 목록에 요소를 어떻게 추가합니까?Python 목록에 요소를 어떻게 추가합니까?May 04, 2025 am 12:17 AM

toAppendElementStoapyThonList, usetHeappend () MethodForsingleElements, extend () formultipleements, andinsert () forspecificpositions.1) useappend () foraddingOneElementatateend.2) usextend () toaddmultipleementsefficially

파이썬 목록을 어떻게 만드나요? 예를 들어보세요.파이썬 목록을 어떻게 만드나요? 예를 들어보세요.May 04, 2025 am 12:16 AM

To TeCreateAtheThonList, usequareBrackets [] andseparateItemswithCommas.1) ListSaredynamicandCanholdMixedDatAtatypes.2) useappend (), remove () 및 SlicingFormAnipulation.3) listlisteforences;) ORSL

수치 데이터의 효율적인 저장 및 처리가 중요한 경우 실제 사용 사례에 대해 토론하십시오.수치 데이터의 효율적인 저장 및 처리가 중요한 경우 실제 사용 사례에 대해 토론하십시오.May 04, 2025 am 12:11 AM

금융, 과학 연구, 의료 및 AI 분야에서 수치 데이터를 효율적으로 저장하고 처리하는 것이 중요합니다. 1) 금융에서 메모리 매핑 파일과 Numpy 라이브러리를 사용하면 데이터 처리 속도가 크게 향상 될 수 있습니다. 2) 과학 연구 분야에서 HDF5 파일은 데이터 저장 및 검색에 최적화됩니다. 3) 의료에서 ​​인덱싱 및 파티셔닝과 같은 데이터베이스 최적화 기술은 데이터 쿼리 성능을 향상시킵니다. 4) AI에서 데이터 샤딩 및 분산 교육은 모델 교육을 가속화합니다. 올바른 도구와 기술을 선택하고 스토리지 및 처리 속도 간의 트레이드 오프를 측정함으로써 시스템 성능 및 확장 성을 크게 향상시킬 수 있습니다.

파이썬 어레이를 어떻게 만드나요? 예를 들어보세요.파이썬 어레이를 어떻게 만드나요? 예를 들어보세요.May 04, 2025 am 12:10 AM

PythonArraysareCreatedusingThearrayModule, Notbuilt-inlikelists.1) importThearrayModule.2) SpecifyTyPeCode (예 : 'forIntegers.3) 초기에 초기화 성과의 공동체 정보가없는 사람들이 플렉스리스트.

Python 통역사를 지정하기 위해 Shebang 라인을 사용하는 몇 가지 대안은 무엇입니까?Python 통역사를 지정하기 위해 Shebang 라인을 사용하는 몇 가지 대안은 무엇입니까?May 04, 2025 am 12:07 AM

Shebang 라인 외에도 Python 통역사를 지정하는 방법에는 여러 가지가 있습니다. 1. 명령 줄에서 직접 Python 명령을 사용하십시오. 2. 배치 파일 또는 쉘 스크립트를 사용하십시오. 3. Make 또는 Cmake와 같은 빌드 도구를 사용하십시오. 4. Invoke와 같은 작업 러너를 사용하십시오. 각 방법에는 장점과 단점이 있으며 프로젝트의 요구에 맞는 방법을 선택하는 것이 중요합니다.

목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?May 03, 2025 am 12:11 AM

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.May 03, 2025 am 12:10 AM

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?May 03, 2025 am 12:06 AM

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기