python+django+jwt开发一个web用户管理系统
时间: 2023-11-17 17:06:23 浏览: 213
python django+bootstrap实现用户管理系统
好的,下面是基于Python Django和JWT的Web用户管理系统的开发步骤:
1. 创建Django项目
在命令行中输入以下命令来创建Django项目:
```
django-admin startproject user_management_system
```
2. 创建Django应用程序
在命令行中输入以下命令来创建Django应用程序:
```
python manage.py startapp users
```
3. 配置Django应用程序
在settings.py文件中添加以下应用程序和数据库的配置:
```python
INSTALLED_APPS = [
'users',
'rest_framework',
'rest_framework.authtoken',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'user_management_system',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}
```
4. 创建模型
在models.py文件中创建用户模型:
```python
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
```
5. 配置REST框架
在settings.py文件中添加以下REST框架的配置:
```python
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
```
6. 配置JWT
在settings.py文件中添加以下JWT的配置:
```python
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': 'secret_key',
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
```
7. 创建视图
在views.py文件中创建视图:
```python
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from django.contrib.auth import authenticate
from django.contrib.auth.models import update_last_login
from .serializers import UserSerializer
from .models import User
class UserRegistrationView(APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserLoginView(TokenObtainPairView):
def post(self, request, *args, **kwargs):
try:
email = request.data['email']
password = request.data['password']
user = authenticate(email=email, password=password)
if user is None:
return Response({'error': 'Invalid email or password'}, status=status.HTTP_400_BAD_REQUEST)
refresh = self.get_token(user)
update_last_login(None, user)
return Response({
'access': str(refresh.access_token),
'refresh': str(refresh),
})
except KeyError:
return Response({'error': 'Email and password are required'}, status=status.HTTP_400_BAD_REQUEST)
class UserRefreshTokenView(TokenRefreshView):
pass
class UserDetailView(APIView):
permission_classes = (IsAuthenticated,)
authentication_classes = (JWTAuthentication,)
def get(self, request):
serializer = UserSerializer(request.user)
return Response(serializer.data)
```
8. 创建序列化器
在serializers.py文件中创建用户序列化器:
```python
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create_user(
email=validated_data['email'],
password=validated_data['password'],
)
return user
```
9. 配置URL
在urls.py文件中配置URL:
```python
from django.urls import path
from .views import UserRegistrationView, UserLoginView, UserRefreshTokenView, UserDetailView
urlpatterns = [
path('register/', UserRegistrationView.as_view(), name='register'),
path('login/', UserLoginView.as_view(), name='login'),
path('refresh_token/', UserRefreshTokenView.as_view(), name='refresh_token'),
path('user_detail/', UserDetailView.as_view(), name='user_detail'),
]
```
10. 运行服务器
在命令行中输入以下命令来运行服务器:
```
python manage.py runserver
```
现在,您可以使用Postman或其他HTTP客户端来测试API。在请求头中传递JWT令牌以验证用户身份。
希望这个简单的Django JWT用户管理系统可以帮助到您!
阅读全文