In our template, we check whether the user is authenticated. If the user is logged in, we display the log-out link and the user\\'s full name. Otherwise, we show the sign-in and sign-up links.
Now let\\'s run all the tests

(.venv)$ python3 manage.py testFound 22 test(s).Creating test database for alias \\'default\\'...System check identified no issues (0 silenced).......................----------------------------------------------------------------------Ran 22 tests in 9.942sOKDestroying test database for alias \\'default\\'...

3. Test if everything is working as it should in our browser

Now that we\\'ve configured the login and logout functionality, it\\'s time to test everything in our web browser. Let\\'s start the development server

(.venv)$ python3 manage.py runserver

Navigate to the registration page and enter valid credentials. After a successful registration, you should be redirected to the login page. Enter the user information in the login form, and once logged in, click the logout button. You should then be logged out and redirected to the homepage. Finally, verify that you\\'re no longer logged in and that the sign-up and sign-in links are displayed again.
Everything works perfectly, but I noticed that when a user is logged in and visits the registration page at http://127.0.0.1:8000/users/sign_up/, they still have access to the registration form. Ideally, once a user is logged in, they shouldn\\'t be able to access the sign-up page.
\\\"Guide
This behaviour can introduce several security vulnerabilities into our project. To address this, we need to update the SignUpView to redirect any logged-in user to the home page.
But first, let\\'s update our LoginTest to add a new test that covers the scenario. So in the users/tests/test_views.py add this code.

# users/tests/test_views.pyclass LoginTests(TestCase):  # -- other test cases  def test_visiting_registration_after_logged_in(self):    \\\"\\\"\\\"    Logged in user should be redirected when visiting the registration page    \\\"\\\"\\\"    response = self.client.post(reverse(\\'users:login\\'), self.valid_credentials, follow=True)    self.assertTrue(response.context[\\'user\\'].is_authenticated)    sign_up_resp = self.client.get(reverse(\\'users:signup\\'))    self.assertRedirects(sign_up_resp, reverse(\\'home\\'))

Now, we can update our SignUpView

# users/views.pyfrom django.conf import settings # new line...class SignUpView(CreateView):  form_class = CustomUserCreationForm  redirect_authenticated_user = True  model = User  success_url = reverse_lazy(\\'users:login\\')  template_name = \\'registration/signup.html\\'  def dispatch(self, request, *args, **kwargs):    # Check if a user is already authenticated    if request.user.is_authenticated:      # Redirect the user to the login redirect url      return redirect(f\\'{settings.LOGIN_REDIRECT_URL}\\')    return super().dispatch(request, *args, **kwargs)

In the code above, we override the dispatch() method of our SignUpView to redirect any user who is already logged in and tries to access the registration page. This redirect will use the LOGIN_REDIRECT_URL set in our settings.py file, which in this case, points to the home page.
Okay! Once again, let\\'s run all our tests to confirm that our updates are working as expected

(.venv)$ python3 manage.py testFound 23 test(s).Creating test database for alias \\'default\\'...System check identified no issues (0 silenced)........................----------------------------------------------------------------------Ran 23 tests in 11.215sOKDestroying test database for alias \\'default\\'...

I know there\\'s much more to accomplish, but let\\'s take a moment to appreciate what we\\'ve accomplished so far. Together, we\\'ve set up our project environment, connected a PostgreSQL database, and implemented a secure user registration and login system for our Django blog application. In the next part, we\\'ll dive into creating a user profile page, enabling users to edit their information, and password reset! Stay tuned for more exciting developments as we continue our Django blog app journey!

Your feedback is always valued. Please share your thoughts, questions, or suggestions in the comments below. Don\\'t forget to like, leave a comment, and subscribe to stay updated on the latest developments!

","image":"http://www.luping.net/uploads/20241023/17296751096718bf6570e45.png","datePublished":"2024-11-06T19:55:38+08:00","dateModified":"2024-11-06T19:55:38+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 TDD 方法論和 PostgreSQL 使用 Django 建立完整部落格應用程式的指南(部分安全使用者身份驗證)

使用 TDD 方法論和 PostgreSQL 使用 Django 建立完整部落格應用程式的指南(部分安全使用者身份驗證)

發佈於2024-11-06
瀏覽:178

Welcome back, everyone! In the previous part, we established a secure user registration process for our Django blog application. However, after successful registration, we were redirected to the homepage. This behaviour will be modified once we implement user authentication. User authentication ensures that only authorized users can access certain functionalities and protects sensitive information.
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
In this series, we are building a complete blog application, guided by the following Entity-Relationship Diagram (ERD). For this time, our focus will be on setting up a secure user authentication process. If you find this content helpful, please like, comment, and subscribe to stay updated when the next part is released.
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
This is a preview of how our login page will look after we’ve implemented the login functionality. If you haven’t read the previous parts of the series, I recommend doing so, as this tutorial is a continuation of the previous steps.

Okay, let’s get started !!

Django comes with a built-in app called contrib.auth, which simplifies handling user authentication for us. You can check the blog_env/settings.py file, under the INSTALLED_APPS, you’ll see that auth is already listed.

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



The auth app provides us with multiple authentication views for handling login, logout, password change, password reset, etc. This means that the essential authentication functionality, such as user login, registration, and permissions, is ready to use without needing to build everything from scratch.

In this tutorial, we’ll focus solely on the login and logout views, and cover the rest of the views in later parts of the series.

1. Create a login form

Following our TDD approach, let’s begin by creating tests for the login form. Since we haven’t created a login form yet, navigate to the users/forms.py file and create a new class inheriting from AuthenticationForm.

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

class LoginForm(AuthenticationForm):


Once the form is defined, we can add test cases in users/tests/test_forms.py to verify its functionality.

# users/tests/test_forms.py

#   --- other code

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

  def test_valid_credentials(self):
    """
    With valid credentials, the form should be valid
    """
    credentials = {
      'email': '[email protected]',
      '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': '[email protected]',
      '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': '[email protected]',
      'password': '',
      'remember_me': False
    }
    form = LoginForm(data = credentials)
    self.assertFalse(form.is_valid())
    self.assertIn('This field is required', str(form.errors['password']))

These tests cover scenarios like successful login with valid credentials, failed login with invalid credentials, and handling error messages appropriately.

The AuthenticationForm class provides some basic validation by default. However, with our LoginForm, we can tailor its behaviour and add any necessary validation rules to meet our specific requirements.

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

We’ve created a custom login form that includes the following fields: email, password, and remember_me. The remember_me checkbox allows users to maintain their login session across browser sessions.

Since our form extends the AuthenticationForm, we've overridden some default behaviour:

  • ** __init__ method**: We've removed the default username field from the form to align with our email-based authentication.
  • clean() method: This method validates the email and password fields. If the credentials are valid, we authenticate the user using Django's built-in authentication mechanism.
  • confirm_login_allowed() method: This built-in method provides an opportunity for additional verification before login. You can override this method to implement custom checks if needed. Now our tests should pass:
(.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'...

2. Create our login view

2.1 Create tests for the login view

Since we do not have the view for the login yet, let's navigate to the users/views.py file and create a new class inheriting from the auth app’s LoginView

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

class CustomLoginView(views.LoginForm):


At the bottom of the users/tests/test_views.py file add these test cases

# users/tests/test_views.py

# -- other code

class LoginTests(TestCase):
  def setUp(self):
    User.objects.create_user(
      full_name= 'Tester User',
      email= '[email protected]',
      bio= 'new bio for tester',
      password= 'password12345'
    )
    self.valid_credentials = {
      'email': '[email protected]',
      '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, 'Sign Up')

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

  def test_login_with_wrong_credentials(self):
    """Get error message when enter wrong credentials"""
    credentials = {
      'email': '[email protected]',
      '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)

We need to ensure that these tests are failing at this stage.

2.2 Create a login view

In the users/views.py file at the bottom of the file add the code below:

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

class CustomLoginView(views.LoginView):
  form_class = LoginForm
  redirect_authenticated_user = True
  authentication_form = LoginForm
  template_name = 'registration/login.html'

  def form_valid(self, form):
    remember_me = form.cleaned_data.get('remember_me')

    if not remember_me:
      # set session expiry to 0 seconds. So it will automatically close the session after the browser is closed.
      self.request.session.set_expiry(0)
      # Set session as modified to force data updates/cookie to be saved.
      self.request.session.modified = True
    return super(CustomLoginView, self).form_valid(form)

In the code above, we accomplish the following:

  • Set the form_class Attribute: We specify our custom LoginForm as the form_class attribute since we are no longer using the default AuthenticationForm.
  • Override the form_valid Method: We override the form_valid method, which is called when valid form data has been posted. This allows us to implement custom behaviour after the user has successfully logged in.
  • Handle Session Expiration: If the user does not check the remember_me box, the session will expire automatically when the browser is closed. However, if the remember_me box is checked, the session will last for the duration defined in settings.py. The default session length is two weeks, but we can modify this using the SESSION_COOKIE_AGE variable in settings.py. For example, to set the cookie age to 7 days, we can add the following line to our settings:
# blog_app/settings.py
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7

To connect your custom login functionality and allow users to access the login page, we’ll define URL patterns in the users/urls.py file. This file will map specific URLs (/log_in/ in this case) to the corresponding views (CustomLoginView). Additionally, we'll include a path for the logout functionality using Django's built-in LogoutView.

# users/urls.py

# -- other code
from django.contrib.auth import views as auth_views
from . import views

app_name = 'users'
urlpatterns = [
  path('log_in/', views.CustomLoginView.as_view(), name='login' ), # new line
  path('sign_up/', views.SignUpView.as_view(), name='signup'),
  path('log_out/', auth_views.LogoutView.as_view(), name='logout'),# new line
]

Everything seems to be in order, but we should specify where to redirect users upon successful login and logout. To do this, we will use the LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL settings. At the bottom of your blog_app/settings.py file, add the following lines to redirect users to the homepage:

# django_project/settings.py
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

Now that we have the login URL let’s update our SignUpView in the users/views.py file to redirect to the login page when sign-up is successful.

# users/views.py
class SignUpView(CreateView):
  form_class = CustomUserCreationForm
  model = User
  success_url = reverse_lazy('users:login') # Updated line
  template_name = 'registration/signup.html'

We will also update our SignUpTexts, specifically the test_signup_correct_data(self), to reflect the new behaviour and ensure that our changes are properly tested.

# users/tests/test_views.py
  def test_signup_correct_data(self):
    """User should be saved when a correct data is provided"""
    response = self.client.post(reverse('users:signup'), data={
      'full_name': self.full_name,
      'email': self.email,
      'bio': self.bio,
      'password1': self.password,
      'password2': self.password
    })

    self.assertRedirects(response, reverse('users:login')) # Updated line
    users = User.objects.all()
    self.assertEqual(users.count(), 1)
    self.assertNotEqual(users[0].password, self.password)

2.3 Create a template for Login

Then create a users/templates/registration/login.html file with your text editor and include the following code:

{% extends 'layout.html' %}
{% block page %}
  Login
{% endblock %}
{% block content %}

Sign In

{% if form.errors %} {% for field, message in form.errors.items %} {% endfor %} {% endif %}
{{form.email}}
{{form.password}}
{{form.remember_me}}
{% endblock %}

We will add the Forgot Password functionality later in this series but now it’s just a dead link.
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
Now, let us update our layout.html template to include the login, sign-up and logout links.



  {% block page %}{% endblock %} | Blog App
  {% block content %}
  {% endblock %}
  

In our template, we check whether the user is authenticated. If the user is logged in, we display the log-out link and the user's full name. Otherwise, we show the sign-in and sign-up links.
Now let's run all the tests

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

3. Test if everything is working as it should in our browser

Now that we've configured the login and logout functionality, it's time to test everything in our web browser. Let's start the development server

(.venv)$ python3 manage.py runserver

Navigate to the registration page and enter valid credentials. After a successful registration, you should be redirected to the login page. Enter the user information in the login form, and once logged in, click the logout button. You should then be logged out and redirected to the homepage. Finally, verify that you're no longer logged in and that the sign-up and sign-in links are displayed again.
Everything works perfectly, but I noticed that when a user is logged in and visits the registration page at http://127.0.0.1:8000/users/sign_up/, they still have access to the registration form. Ideally, once a user is logged in, they shouldn't be able to access the sign-up page.
Guide to Building a Complete Blog App with Django using TDD Methodology and PostgreSQL (Part  Secure User Authentication
This behaviour can introduce several security vulnerabilities into our project. To address this, we need to update the SignUpView to redirect any logged-in user to the home page.
But first, let's update our LoginTest to add a new test that covers the scenario. So in the users/tests/test_views.py add this code.

# users/tests/test_views.py
class LoginTests(TestCase):
  # -- other test cases

  def test_visiting_registration_after_logged_in(self):
    """
    Logged in user should be redirected when visiting the registration page
    """
    response = self.client.post(reverse('users:login'), self.valid_credentials, follow=True)
    self.assertTrue(response.context['user'].is_authenticated)

    sign_up_resp = self.client.get(reverse('users:signup'))
    self.assertRedirects(sign_up_resp, reverse('home'))

Now, we can update our SignUpView

# users/views.py
from django.conf import settings # new line
...

class SignUpView(CreateView):
  form_class = CustomUserCreationForm
  redirect_authenticated_user = True
  model = User
  success_url = reverse_lazy('users:login')
  template_name = 'registration/signup.html'

  def dispatch(self, request, *args, **kwargs):
    # Check if a user is already authenticated
    if request.user.is_authenticated:
      # Redirect the user to the login redirect url
      return redirect(f'{settings.LOGIN_REDIRECT_URL}')
    return super().dispatch(request, *args, **kwargs)

In the code above, we override the dispatch() method of our SignUpView to redirect any user who is already logged in and tries to access the registration page. This redirect will use the LOGIN_REDIRECT_URL set in our settings.py file, which in this case, points to the home page.
Okay! Once again, let's run all our tests to confirm that our updates are working as expected

(.venv)$ python3 manage.py test
Found 23 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.......................
----------------------------------------------------------------------
Ran 23 tests in 11.215s

OK
Destroying test database for alias 'default'...

I know there's much more to accomplish, but let's take a moment to appreciate what we've accomplished so far. Together, we've set up our project environment, connected a PostgreSQL database, and implemented a secure user registration and login system for our Django blog application. In the next part, we'll dive into creating a user profile page, enabling users to edit their information, and password reset! Stay tuned for more exciting developments as we continue our Django blog app journey!

Your feedback is always valued. Please share your thoughts, questions, or suggestions in the comments below. Don't forget to like, leave a comment, and subscribe to stay updated on the latest developments!

版本聲明 本文轉載於:https://dev.to/lionrouge1/guide-to-building-a-complete-blog-app-with-django-using-tdd-methodology-and-postgresql-part-3-secure-user- authentication-nkc?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何根據 Python 中的條件取代清單中的值?
    如何根據 Python 中的條件取代清單中的值?
    Python 中根據條件替換清單中的值在Python 中,您可能會遇到需要操作清單中元素的情況清單,例如根據特定條件替換值。透過利用有效的技術,您可以有效地執行這些修改。 一種方法涉及利用列表理解。例如,如果您有一個列表[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 並且想要替...
    程式設計 發佈於2024-11-06
  • 如何使用 Docker Scratch 在 Golang 中建立靜態二進位檔案:CGO_ENABLED=0 和 -ldflags?
    如何使用 Docker Scratch 在 Golang 中建立靜態二進位檔案:CGO_ENABLED=0 和 -ldflags?
    在Golang 中建立靜態二進位檔案的標誌當使用Docker 暫存庫在Golang 中建立靜態二進位檔案時,必須包含CGO_ENABLED =0 和-ldflags '-extldflags "-static"' 標誌。雖然這兩個選項可能看起來多餘,但它們在實現靜...
    程式設計 發佈於2024-11-06
  • 我可以將行追加到 CSV 檔案而不覆蓋它嗎?
    我可以將行追加到 CSV 檔案而不覆蓋它嗎?
    在Python 中向現有CSV 檔案追加新行:一種更有效的方法當您需要使用附加行更新CSV文件時,您可能會考慮以下問題:問: 是否可以向現有CSV 文件添加新行,而無需覆蓋和重新創建文件? 答: 絕對!以下是將行追加到 CSV 檔案的更有效方法:您可以利用Python 中的 with 語句。 以下程...
    程式設計 發佈於2024-11-06
  • Nestjs、Firebase、GCloud。如何在 TypeScript 中快速設定 API 後端。
    Nestjs、Firebase、GCloud。如何在 TypeScript 中快速設定 API 後端。
    It's great that you decided to open this article. My name is Fedor, and I've been a full-stack developer on a permanent basis since the end of 2021. J...
    程式設計 發佈於2024-11-06
  • 如何在維護非同步操作的同時避免鍊式函數中的 jQuery Promise?
    如何在維護非同步操作的同時避免鍊式函數中的 jQuery Promise?
    在鍊式函數中迴避jQuery Promise儘管建議避免jQuery Promise,但開發人員在不使用jQuery 的情況下鏈接非同步jQuery 函數時可能會面臨挑戰Promise 處理機制,如.then() 或.when()。為了解決這個問題,請考慮以下方法:jQuery Promise 可以...
    程式設計 發佈於2024-11-06
  • 為什麼「repr」方法在 Python 中至關重要?
    為什麼「repr」方法在 Python 中至關重要?
    探討repr方法的意義在Python程式設計的脈絡中,repr 方法在將物件表示為字串方面起著關鍵作用。這種簡潔而詳細的表示有多種用途:repr的目的方法:repr的主要目標方法的目的是傳回一個物件的字串表示形式,該物件既是人類可讀的,而且重要的是,是明確的。這種表示法應該足以重新建立具有相同狀態和...
    程式設計 發佈於2024-11-06
  • 每個開發人員都應該了解可擴展和高效應用程式的頂級 React 設計模式
    每個開發人員都應該了解可擴展和高效應用程式的頂級 React 設計模式
    隨著 React 繼續主導前端生態系統,掌握其設計模式可以顯著提高應用程式的效率和可擴展性。 React 設計模式提供了組織和建置元件、管理狀態、處理 props 和提高可重複使用性的最佳實踐。在本部落格中,我們將探討一些關鍵的 React 設計模式,這些模式可以讓您的開發流程從優秀走向卓越。 ...
    程式設計 發佈於2024-11-06
  • 在 React 中建立無限滾動元件
    在 React 中建立無限滾動元件
    介绍 我们在应用程序和网页中看到无限滚动,尤其是希望我们滚动的社交媒体。虽然无意识地滚动不好,但构建自己的无限滚动是很棒的。作为开发人员,我们应该尝试重新创建我们在网上冲浪时看到的组件。它可以挑战您在实现某些组件时了解更多信息并跳出框框进行思考。 此外,如果您希望在应用程序中实现无...
    程式設計 發佈於2024-11-06
  • 在 React 中建立響應式會議圖塊的動態網格系統
    在 React 中建立響應式會議圖塊的動態網格系統
    In the era of remote work and virtual meetings, creating a responsive and dynamic grid system for displaying participant video tiles is crucial. Inspi...
    程式設計 發佈於2024-11-06
  • 使用 Spring Boot 和 Spring Cloud 開發微服務
    使用 Spring Boot 和 Spring Cloud 開發微服務
    微服務架構已成為建構可擴展和模組化系統的流行解決方案。透過微服務,您可以將單一應用程式分解為更小的、獨立的和專業的服務,這使得系統的維護和發展變得更加容易。在這篇文章中,我們將探討如何使用 Spring Boot 和 Spring Cloud 來創造健壯且有效率的微服務。 微服務簡介 微服務背後的...
    程式設計 發佈於2024-11-06
  • 克服 PHP DOM XML 解析中的挑戰:問題與解決方案
    克服 PHP DOM XML 解析中的挑戰:問題與解決方案
    簡化PHP DOM XML 解析:揭開要點當您瀏覽PHP DOM 函數的複雜性時,可能會出現某些障礙。為了解決這些挑戰,讓我們開始了解 DOM 的複雜性,並找出常見問題的解決方案。 問題1:使用xml:id 馴服ID當使用ID 來防止樹中出現重複頁面時,PHP 的DOM 遇到了一個難題:getEle...
    程式設計 發佈於2024-11-06
  • 密碼重設功能:使用 OTP 重設密碼
    密碼重設功能:使用 OTP 重設密碼
    後端 2. 重設密碼 轉向下一個 API。 PUT 上 /api/reset-password, req -> otp, email, 新密碼, res -> nocontent // controllers/passwordReset.go func Reset...
    程式設計 發佈於2024-11-06
  • 如何從全域站點套件繼承 Virtualenv 中的特定套件?
    如何從全域站點套件繼承 Virtualenv 中的特定套件?
    從全域網站套件繼承Virtualenv 中的特定套件為了增強虛擬環境(virtualenv) 的功能,您可能會想要從全域網站繼承特定套件網站套件目錄。這種方法允許您選擇性地將重要的程式庫合併到您的 virtualenv 中,而無需直接安裝它們。 繼承方法要實現這種繼承,請使用以下命令建立新的virt...
    程式設計 發佈於2024-11-06
  • 如何解決 EF6 中的“找不到 'MySql.Data.MySqlClient\'\”錯誤?
    如何解決 EF6 中的“找不到 'MySql.Data.MySqlClient\'\”錯誤?
    MySQL 實體框架的提供者註冊使用MySQL 和實體框架時,您可能會遇到錯誤「找不到Entity Framework提供者” 'MySql.Data.MySqlClient' ADO.NET 提供者。 「儘管安裝了最新的MySQL 連接器,您可能仍然會遇到此問題。出現此問題的原因是...
    程式設計 發佈於2024-11-06
  • 如何利用PHP防止郵件傳輸中的惡意輸入?
    如何利用PHP防止郵件傳輸中的惡意輸入?
    保護電子郵件傳輸的使用者輸入在PHP 中,必須在發送電子郵件之前清理使用者輸入,以防止惡意或有害內容外洩你的系統。考慮下面的簡單 PHP 郵件腳本的程式碼片段:<?php $to = "[email protected]"; $name = $_POST['name']; ...
    程式設計 發佈於2024-11-06

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3