国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) Python教程 使用 Django 使用 TDD 方法和 PostgreSQL 構(gòu)建完整博客應(yīng)用程序的指南(部分安全用戶身份驗(yàn)證)

使用 Django 使用 TDD 方法和 PostgreSQL 構(gòu)建完整博客應(yīng)用程序的指南(部分安全用戶身份驗(yàn)證)

Oct 18, 2024 pm 06:18 PM

歡迎回來,大家!在上一部分中,我們?yōu)?Django 博客應(yīng)用程序建立了安全的用戶注冊流程。然而,注冊成功后,我們被重定向到主頁。一旦我們實(shí)現(xiàn)用戶身份驗(yàn)證,這種行為就會被修改。用戶身份驗(yàn)證確保只有授權(quán)用戶才能訪問某些功能并保護(hù)敏感信息。
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
在本系列中,我們將在以下實(shí)體關(guān)系圖 (ERD) 的指導(dǎo)下構(gòu)建一個完整的博客應(yīng)用程序。這次,我們的重點(diǎn)將是建立安全的用戶身份驗(yàn)證流程。如果您覺得此內(nèi)容有幫助,請點(diǎn)贊、評論和訂閱,以便在下一部分發(fā)布時保持更新。
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
這是我們實(shí)現(xiàn)登錄功能后登錄頁面外觀的預(yù)覽。如果您還沒有閱讀本系列的前面部分,我建議您這樣做,因?yàn)楸窘坛淌乔懊娌襟E的延續(xù)。

好的,我們開始吧!!

Django 附帶了一個名為 contrib.auth 的內(nèi)置應(yīng)用程序,它簡化了我們處理用戶身份驗(yàn)證的過程。你可以檢查 blog_env/settings.py 文件,在 INSTALLED_APPS 下,你會看到 auth 已經(jīng)列出了。

# django_project/settings.py
INSTALLED_APPS = [
    # "django.contrib.admin",
    "django.contrib.auth",  # <-- Auth app
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

auth應(yīng)用程序?yàn)槲覀兲峁┝硕喾N身份驗(yàn)證視圖,用于處理登錄、注銷、密碼更改、密碼重置等。這意味著基本的身份驗(yàn)證功能,例如用戶登錄、注冊和權(quán)限,無需使用即可使用從頭開始構(gòu)建一切。

在本教程中,我們將僅關(guān)注登錄和注銷視圖,并在本系列的后續(xù)部分中介紹其余視圖。

1. 創(chuàng)建登錄表單

按照我們的 TDD 方法,我們首先為登錄表單創(chuàng)建測試。由于我們還沒有創(chuàng)建登錄表單,因此導(dǎo)航到 users/forms.py 文件并創(chuàng)建一個繼承自 AuthenticationForm 的新類。

# users/forms.py
from django.contrib.auth import AuthenticationForm

class LoginForm(AuthenticationForm):


定義表單后,我們可以在 users/tests/test_forms.py 中添加測試用例來驗(yàn)證其功能。

# 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']))

這些測試涵蓋了使用有效憑據(jù)成功登錄、使用無效憑據(jù)登錄失敗以及正確處理錯誤消息等場景。

AuthenticationForm 類默認(rèn)提供一些基本的驗(yàn)證。但是,通過我們的 LoginForm,我們可以定制其行為并添加任何必要的驗(yàn)證規(guī)則來滿足我們的特定要求。

# django_project/settings.py
INSTALLED_APPS = [
    # "django.contrib.admin",
    "django.contrib.auth",  # <-- Auth app
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

我們創(chuàng)建了一個自定義登錄表單,其中包含以下字段:電子郵件、密碼remember_me。 Remember_me 復(fù)選框允許用戶跨瀏覽器會話保持登錄會話。

由于我們的表單擴(kuò)展了 AuthenticationForm,因此我們覆蓋了一些默認(rèn)行為:

  • ** __init__ 方法**:我們已從表單中刪除了默認(rèn)的用戶名字段,以與我們基于電子郵件的身份驗(yàn)證保持一致。
  • clean() 方法:此方法驗(yàn)證電子郵件和密碼字段。如果憑據(jù)有效,我們將使用 Django 的內(nèi)置身份驗(yàn)證機(jī)制對用戶進(jìn)行身份驗(yàn)證。
  • confirm_login_allowed() 方法:此內(nèi)置方法提供了登錄前進(jìn)行額外驗(yàn)證的機(jī)會。如果需要,您可以重寫此方法來實(shí)施自定義檢查。 現(xiàn)在我們的測試應(yīng)該通過:
# users/forms.py
from django.contrib.auth import AuthenticationForm

class LoginForm(AuthenticationForm):


2. 創(chuàng)建我們的登錄視圖

2.1 為登錄視圖創(chuàng)建測試

由于我們還沒有登錄視圖,所以讓我們導(dǎo)航到 users/views.py 文件并創(chuàng)建一個繼承自身份驗(yàn)證應(yīng)用程序的 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 創(chuàng)建登錄視圖

在文件底部的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'...

在上面的代碼中,我們完成了以下任務(wù):

  • 設(shè)置form_class 屬性:我們將自定義的LoginForm 指定為form_class 屬性,因?yàn)槲覀儾辉偈褂媚J(rèn)的AuthenticationForm。
  • 重寫 form_valid 方法:我們重寫 form_valid 方法,該方法在發(fā)布有效的表單數(shù)據(jù)時調(diào)用。這允許我們在用戶成功登錄后實(shí)現(xiàn)自定義行為。
  • 處理會話過期:如果用戶沒有選中 Remember_me 框,則會話將在瀏覽器關(guān)閉時自動過期。但是,如果選中 Remember_me 框,會話將持續(xù) settings.py 中定義的持續(xù)時間。默認(rèn)會話長度為兩周,但我們可以使用 settings.py 中的 SESSION_COOKIE_AGE 變量修改它。例如,要將 cookie 期限設(shè)置為 7 天,我們可以將以下行添加到我們的設(shè)置中:
# -- 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/)映射到相應(yīng)的視圖 (CustomLoginView)。此外,我們將使用 Django 的內(nèi)置 LogoutView 添加注銷功能的路徑。

# django_project/settings.py
INSTALLED_APPS = [
    # "django.contrib.admin",
    "django.contrib.auth",  # <-- Auth app
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

一切似乎都井然有序,但我們應(yīng)該指定在成功登錄和注銷后將用戶重定向到何處。為此,我們將使用 LOGIN_REDIRECT_URL 和 LOGOUT_REDIRECT_URL 設(shè)置。在 blog_app/settings.py 文件的底部,添加以下行以將用戶重定向到主頁:

# users/forms.py
from django.contrib.auth import AuthenticationForm

class LoginForm(AuthenticationForm):


現(xiàn)在我們有了登錄 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']))

我們還將更新我們的 SignUpTexts,特別是 test_signup_ Correct_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 創(chuàng)建登錄模板

然后使用文本編輯器創(chuàng)建一個 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'...

我們將在本系列后面添加忘記密碼功能,但現(xiàn)在它只是一個死鏈接。
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
現(xiàn)在,讓我們更新 layout.html 模板以包含登錄、注冊和注銷鏈接。

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

class CustomLoginView(views.LoginForm):


在我們的模板中,我們檢查用戶是否經(jīng)過身份驗(yàn)證。如果用戶已登錄,我們將顯示注銷鏈接和用戶的全名。否則,我們會顯示登錄和注冊鏈接。
現(xiàn)在讓我們運(yùn)行所有測試

# 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. 測試瀏覽器中的一切是否正常

現(xiàn)在我們已經(jīng)配置了登錄和注銷功能,是時候測試網(wǎng)絡(luò)瀏覽器中的所有內(nèi)容了。讓我們啟動開發(fā)服務(wù)器

# django_project/settings.py
INSTALLED_APPS = [
    # "django.contrib.admin",
    "django.contrib.auth",  # <-- Auth app
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

導(dǎo)航到注冊頁面并輸入有效的憑據(jù)。成功注冊后,您應(yīng)該被重定向到登錄頁面。在登錄表單中輸入用戶信息,登錄后單擊注銷按鈕。然后您應(yīng)該注銷并重定向到主頁。最后,驗(yàn)證您是否不再登錄,并且注冊和登錄鏈接是否再次顯示。
一切都很完美,但我注意到,當(dāng)用戶登錄并訪問注冊頁面(http://127.0.0.1:8000/users/sign_up/)時,他們?nèi)匀豢梢栽L問注冊表單。理想情況下,用戶登錄后,他們不應(yīng)該能夠訪問注冊頁面。
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
這種行為可能會給我們的項目帶來一些安全漏洞。為了解決這個問題,我們需要更新 SignUpView 以將任何登錄的用戶重定向到主頁。
但首先,讓我們更新 LoginTest 以添加涵蓋該場景的新測試。因此,在 users/tests/test_views.py 中添加此代碼。

# users/forms.py
from django.contrib.auth import AuthenticationForm

class LoginForm(AuthenticationForm):


現(xiàn)在,我們可以更新我們的 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() 方法來重定向任何已登錄并嘗試訪問注冊頁面的用戶。此重定向?qū)⑹褂梦覀兊膕ettings.py 文件中設(shè)置的 LOGIN_REDIRECT_URL,在本例中指向主頁。
好的!再次運(yùn)行所有測試以確認(rèn)我們的更新按預(yù)期工作

# 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')

我知道還有很多事情需要完成,但讓我們花點(diǎn)時間欣賞一下我們迄今為止所取得的成就。我們一起設(shè)置了項目環(huán)境,連接了 PostgreSQL 數(shù)據(jù)庫,并為 Django 博客應(yīng)用程序?qū)崿F(xiàn)了安全的用戶注冊和登錄系統(tǒng)。在下一部分中,我們將深入創(chuàng)建用戶個人資料頁面,使用戶能夠編輯其信息并重置密碼!隨著我們繼續(xù)我們的 Django 博客應(yīng)用程序之旅,請繼續(xù)關(guān)注更多令人興奮的開發(fā)!

我們始終重視您的反饋。請在下面的評論中分享您的想法、問題或建議。不要忘記點(diǎn)贊、發(fā)表評論并訂閱以了解最新動態(tài)!

以上是使用 Django 使用 TDD 方法和 PostgreSQL 構(gòu)建完整博客應(yīng)用程序的指南(部分安全用戶身份驗(yàn)證)的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

Python的UNITDEST或PYTEST框架如何促進(jìn)自動測試? Python的UNITDEST或PYTEST框架如何促進(jìn)自動測試? Jun 19, 2025 am 01:10 AM

Python的unittest和pytest是兩種廣泛使用的測試框架,它們都簡化了自動化測試的編寫、組織和運(yùn)行。1.二者均支持自動發(fā)現(xiàn)測試用例并提供清晰的測試結(jié)構(gòu):unittest通過繼承TestCase類并以test\_開頭的方法定義測試;pytest則更為簡潔,只需以test\_開頭的函數(shù)即可。2.它們都內(nèi)置斷言支持:unittest提供assertEqual、assertTrue等方法,而pytest使用增強(qiáng)版的assert語句,能自動顯示失敗詳情。3.均具備處理測試準(zhǔn)備與清理的機(jī)制:un

如何將Python用于數(shù)據(jù)分析和與Numpy和Pandas等文庫進(jìn)行操作? 如何將Python用于數(shù)據(jù)分析和與Numpy和Pandas等文庫進(jìn)行操作? Jun 19, 2025 am 01:04 AM

pythonisidealfordataanalysisionduetonumpyandpandas.1)numpyExccelSatnumericalComputationswithFast,多dimensionalArraysAndRaysAndOrsAndOrsAndOffectorizedOperationsLikenp.sqrt()

什么是動態(tài)編程技術(shù),如何在Python中使用它們? 什么是動態(tài)編程技術(shù),如何在Python中使用它們? Jun 20, 2025 am 12:57 AM

動態(tài)規(guī)劃(DP)通過將復(fù)雜問題分解為更簡單的子問題并存儲其結(jié)果以避免重復(fù)計算,來優(yōu)化求解過程。主要方法有兩種:1.自頂向下(記憶化):遞歸分解問題,使用緩存存儲中間結(jié)果;2.自底向上(表格化):從基礎(chǔ)情況開始迭代構(gòu)建解決方案。適用于需要最大/最小值、最優(yōu)解或存在重疊子問題的場景,如斐波那契數(shù)列、背包問題等。在Python中,可通過裝飾器或數(shù)組實(shí)現(xiàn),并應(yīng)注意識別遞推關(guān)系、定義基準(zhǔn)情況及優(yōu)化空間復(fù)雜度。

如何使用__ITER__和__NEXT __在Python中實(shí)現(xiàn)自定義迭代器? 如何使用__ITER__和__NEXT __在Python中實(shí)現(xiàn)自定義迭代器? Jun 19, 2025 am 01:12 AM

要實(shí)現(xiàn)自定義迭代器,需在類中定義__iter__和__next__方法。①__iter__方法返回迭代器對象自身,通常為self,以兼容for循環(huán)等迭代環(huán)境;②__next__方法控制每次迭代的值,返回序列中的下一個元素,當(dāng)無更多項時應(yīng)拋出StopIteration異常;③需正確跟蹤狀態(tài)并設(shè)置終止條件,避免無限循環(huán);④可封裝復(fù)雜邏輯如文件行過濾,同時注意資源清理與內(nèi)存管理;⑤對簡單邏輯可考慮使用生成器函數(shù)yield替代,但需結(jié)合具體場景選擇合適方式。

Python編程語言及其生態(tài)系統(tǒng)的新興趨勢或未來方向是什么? Python編程語言及其生態(tài)系統(tǒng)的新興趨勢或未來方向是什么? Jun 19, 2025 am 01:09 AM

Python的未來趨勢包括性能優(yōu)化、更強(qiáng)的類型提示、替代運(yùn)行時的興起及AI/ML領(lǐng)域的持續(xù)增長。首先,CPython持續(xù)優(yōu)化,通過更快的啟動時間、函數(shù)調(diào)用優(yōu)化及擬議中的整數(shù)操作改進(jìn)提升性能;其次,類型提示深度集成至語言與工具鏈,增強(qiáng)代碼安全性與開發(fā)體驗(yàn);第三,PyScript、Nuitka等替代運(yùn)行時提供新功能與性能優(yōu)勢;最后,AI與數(shù)據(jù)科學(xué)領(lǐng)域持續(xù)擴(kuò)張,新興庫推動更高效的開發(fā)與集成。這些趨勢表明Python正不斷適應(yīng)技術(shù)變化,保持其領(lǐng)先地位。

如何使用插座在Python中執(zhí)行網(wǎng)絡(luò)編程? 如何使用插座在Python中執(zhí)行網(wǎng)絡(luò)編程? Jun 20, 2025 am 12:56 AM

Python的socket模塊是網(wǎng)絡(luò)編程的基礎(chǔ),提供低級網(wǎng)絡(luò)通信功能,適用于構(gòu)建客戶端和服務(wù)器應(yīng)用。要設(shè)置基本TCP服務(wù)器,需使用socket.socket()創(chuàng)建對象,綁定地址和端口,調(diào)用.listen()監(jiān)聽連接,并通過.accept()接受客戶端連接。構(gòu)建TCP客戶端需創(chuàng)建socket對象后調(diào)用.connect()連接服務(wù)器,再使用.sendall()發(fā)送數(shù)據(jù)和.recv()接收響應(yīng)。處理多個客戶端可通過1.線程:每次連接啟動新線程;2.異步I/O:如asyncio庫實(shí)現(xiàn)無阻塞通信。注意事

如何在Python中切片列表? 如何在Python中切片列表? Jun 20, 2025 am 12:51 AM

Python列表切片的核心答案是掌握[start:end:step]語法并理解其行為。1.列表切片的基本格式為list[start:end:step],其中start是起始索引(包含)、end是結(jié)束索引(不包含)、step是步長;2.省略start默認(rèn)從0開始,省略end默認(rèn)到末尾,省略step默認(rèn)為1;3.獲取前n項用my_list[:n],獲取后n項用my_list[-n:];4.使用step可跳過元素,如my_list[::2]取偶數(shù)位,負(fù)step值可反轉(zhuǎn)列表;5.常見誤區(qū)包括end索引不

如何使用DateTime模塊在Python中使用日期和時間? 如何使用DateTime模塊在Python中使用日期和時間? Jun 20, 2025 am 12:58 AM

Python的datetime模塊能滿足基本的日期和時間處理需求。1.可通過datetime.now()獲取當(dāng)前日期和時間,也可分別提取.date()和.time()。2.能手動創(chuàng)建特定日期時間對象,如datetime(year=2025,month=12,day=25,hour=18,minute=30)。3.使用.strftime()按格式輸出字符串,常見代碼包括%Y、%m、%d、%H、%M、%S;用strptime()將字符串解析為datetime對象。4.利用timedelta進(jìn)行日期運(yùn)

See all articles