删除pycharm自带的templates文件夹,删除setting中的TEMPLATES中的DIRS中的内容
更改setting中的语言以及配置项,配置端口,安装包
bashpip install django-cors-headers
在注册app中添加,在中间件中添加
python注册app:
"corsheaders"
中间件:
'corsheaders.middleware.CorsMiddleware'
在设置中配置端口信息
pythonCORS_ALLOWED_ORIGINS = [
'http://localhost:5173',
]
CORS_ALLOWED_METHODS = [
'GET',
'POST',
'OPTIONS',
]
CORS_ALLOWED_HEADERS = [
'Content-Type',
]
安装app
bashpython .\manage.py startapp webServer
注册app
python"Server01.apps.Server01Config",
修改数据库配置,见后文
首先在settings中配置好数据库的相关信息, 注:需要安装好mysqlclient
pythonDATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库的连接类型
'NAME': 'app01', # 数据库的名字
'USER': 'root', # 数据库的登录账号
'PASSWORD': 'dxs666dxs', # 密码
'HOST': '127.0.0.1', # ip
'PORT': '3306', # 端口
}
}
在对应app的models.py文件中编写对应的表结构
下面展示简单的表结构以及外键约束
pythonclass Department(models.Model):
""" 部门表 """
title = models.CharField(max_length=32, verbose_name='部门名称')
class Employee(models.Model):
""" 员工表 """
name = models.CharField(max_length=16, verbose_name='姓名')
password = models.CharField(max_length=64, verbose_name='密码')
age = models.IntegerField(verbose_name='年龄')
account = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='账户余额')
created_at = models.DateTimeField(verbose_name='入职事件')
# 外键约束
# 设置级联删除
department = models.ForeignKey(to="Department", to_field="id", on_delete=models.CASCADE)
# 设置置空
# department = models.ForeignKey(to="Department", to_field="id", null=True, blank=True, on_delete=models.SET_NULL)
# 设置选择,即确立简单的对应关系,由Django自动匹配
gender_choices = (
(1, "男"),
(2, "女"),
)
gender = models.SmallIntegerField(verbose_name='性别', choices=gender_choices)
sqlcreate database your_database_name
bashpython manage.py makemigrations python manage.py migrate
如果是普通的数据,我们使用下面的语言即可
pythonqueryset = models.UserInfo.objects.all()
for obj in queryset:
print(obj.id, obj.name, ...)
# 如果是时间类型
print(obj.create_time.strftime("%Y-%M-%D"))
# 如果是简单的对应关系
print(obj.get_gender_display())
简单解释一下,简单对应关系就是
pythonget_名称_display()
pythondepartment = models.Department.objects.filter(id=1).first()
pythonqueryset = models.UserInfo.objects.all()
for obj in queryset:
obj.depart # 拿到部门
pythonmodels.UserInfo.objects.create(user=user, ..., ...)
ModelForm
pythonclass UserModelForm(forms.ModelForm):
class Meta:
model = models.Employee
fields = ['name', 'password', 'age']
# widgets = {
# "name": forms.TextInput(attrs={'class': 'form-control'}),
# 'password': forms.PasswordInput(attrs={'class': 'form-control'}),
# 'age': forms.TextInput(attrs={'class': 'form-control'}),
# }
def __init__(self, *args, **kwargs):
super().__init__()
# 循环找到所有插件添加样式
for filed in self.fields:
filed.widget.attrs['class'] = 'form-control'
pythondef user_modelForm_add(request):
if request.method == 'GET':
form = UserModelForm()
return render(request, 'home.html', {"form": form})
form = UserModelForm(data=request.POST)
if form.is_valid():
print(form.cleaned_data)
form.save()
else:
print(form.errors)
pythonexists = models.PrettyNum.objects.filter(mobile=text).exists()
pythonclass PrettyNumModel(ModelForm):
...
def clean_mobile(self):
id = self.instence.pk
models.PrettyNum.objects.fileter(mobile=text).exclude(id=id).exists()
...
...
session生成和flask的一致
cookie也是随之自动生成
你可以使用 Django ORM 提供的方法来创建新的用户、帖子、评论以及相关的关系。下面是一个简单的示例:
pythonuser = User.objects.create(username='John', password='password', avatar='avatar.jpg', signature='Hello')
pythonuser = User.objects.get(id=user_id) # 获取已存在的用户对象
post = Post.objects.create(user=user, title='My Post', content='Hello, world!')
pythonpost = Post.objects.get(id=post_id) # 获取已存在的帖子对象
comment = Comment.objects.create(post=post, content='Great post!')
pythonuser1 = User.objects.get(id=user1_id) # 获取已存在的用户对象
user2 = User.objects.get(id=user2_id)
user1.following.add(user2) # user1 关注 user2
pythonuser = User.objects.get(id=user_id) # 获取已存在的用户对象
post = Post.objects.get(id=post_id) # 获取已存在的帖子对象
user.favorites.add(post) # 用户收藏帖子
pythonparent_comment = Comment.objects.get(id=parent_comment_id) # 获取已存在的父级评论对象
post = parent_comment.post # 获取父级评论所属的帖子对象
reply_comment = Comment.objects.create(post=post, parent_comment=parent_comment, content='Reply')
请根据你的具体需求和数据模型来适配这些示例代码,并确保在创建关联关系时使用正确的对象和字段。
bashpip install pyjwt
pythonINSTALLED_APPS = [
...
'rest_framework',
'rest_framework_simplejwt',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}
pythonimport datetime
import jwt
from django.http import JsonResponse
from jwt import exceptions
from webServer.settings import SECRET_KEY
def authenticate_request(view_func):
def wrapper(request, *args, **kwargs):
# 从请求中获取 JWT 令牌
try:
token = request.headers.get('Authorization').split(' ')[1]
verify_payload = jwt.decode(token, SECRET_KEY, ['HS256'], verify=True)
return view_func(request, verify_payload, *args, **kwargs)
except exceptions.ExpiredSignatureError:
error_message = {'error': '登录身份过期'}
return JsonResponse(error_message, status=401)
except jwt.DecodeError:
error_message = {'error': 'jwt认证失败'}
return JsonResponse(error_message, status=401)
except jwt.InvalidTokenError:
error_message = {'error': '非法的token'}
return JsonResponse(error_message, status=401)
except AttributeError:
error_message = {'error': '非法的访问'}
return JsonResponse(error_message, status=401)
return wrapper
def create_token(user):
# 构造头部
headers = {
'typ': 'jwt',
'alg': 'HS256',
}
# 构造payload
payload = {
'user_id': user.id,
'username': user.username,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
}
result = jwt.encode(payload=payload, key=SECRET_KEY, algorithm='HS256', headers=headers)
return result
本文作者:回锅炒辣椒
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!