build:project build
This commit is contained in:
BIN
website/db.sqlite3
Normal file
BIN
website/db.sqlite3
Normal file
Binary file not shown.
22
website/manage.py
Normal file
22
website/manage.py
Normal file
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run administrative tasks."""
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Couldn't import Django. Are you sure it's installed and "
|
||||
"available on your PYTHONPATH environment variable? Did you "
|
||||
"forget to activate a virtual environment?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
0
website/smalltalkapp/__init__.py
Normal file
0
website/smalltalkapp/__init__.py
Normal file
3
website/smalltalkapp/admin.py
Normal file
3
website/smalltalkapp/admin.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
6
website/smalltalkapp/apps.py
Normal file
6
website/smalltalkapp/apps.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class SmalltalkappConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'smalltalkapp'
|
||||
24
website/smalltalkapp/migrations/0001_initial.py
Normal file
24
website/smalltalkapp/migrations/0001_initial.py
Normal file
@@ -0,0 +1,24 @@
|
||||
# Generated by Django 5.2.6 on 2025-09-10 11:41
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Smalltalk',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('username', models.CharField(max_length=100)),
|
||||
('content', models.TextField()),
|
||||
('score', models.IntegerField()),
|
||||
('created', models.DateTimeField(auto_now_add=True)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.2.6 on 2025-09-10 14:11
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('smalltalkapp', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='smalltalk',
|
||||
name='score',
|
||||
field=models.IntegerField(choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]),
|
||||
),
|
||||
]
|
||||
0
website/smalltalkapp/migrations/__init__.py
Normal file
0
website/smalltalkapp/migrations/__init__.py
Normal file
20
website/smalltalkapp/models.py
Normal file
20
website/smalltalkapp/models.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from django.db import models
|
||||
from .unity.username_random import RandomName
|
||||
|
||||
# Create your models here.
|
||||
|
||||
class Smalltalk(models.Model):
|
||||
username = models.CharField(max_length=100)
|
||||
content = models.TextField()
|
||||
score = models.IntegerField(choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)])
|
||||
created = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.username:
|
||||
self.username = RandomName.generate_name()
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
14
website/smalltalkapp/serializers.py
Normal file
14
website/smalltalkapp/serializers.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import Smalltalk
|
||||
|
||||
class SmalltalkSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Smalltalk
|
||||
fields = ['id','username','content','score','created']
|
||||
|
||||
class SmalltalkCreateSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Smalltalk
|
||||
fields = ['username','content','score','created']
|
||||
read_only_fields = ['created','username']
|
||||
3
website/smalltalkapp/tests.py
Normal file
3
website/smalltalkapp/tests.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
0
website/smalltalkapp/unity/__init__.py
Normal file
0
website/smalltalkapp/unity/__init__.py
Normal file
26
website/smalltalkapp/unity/exceptions.py
Normal file
26
website/smalltalkapp/unity/exceptions.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# exceptions.py
|
||||
from rest_framework.views import exception_handler
|
||||
from rest_framework.response import Response
|
||||
|
||||
def custom_exception_handler(exc, context):
|
||||
# 调用默认的异常处理器获取标准错误响应
|
||||
response = exception_handler(exc, context)
|
||||
|
||||
# 如果是已知的异常类型,进行统一格式化
|
||||
if response is not None:
|
||||
data = {
|
||||
'msg': str(exc) if not hasattr(exc, 'detail') else exc.detail,
|
||||
'data': None,
|
||||
'code': response.status_code
|
||||
}
|
||||
response.data = data
|
||||
else:
|
||||
# 处理未捕获的异常(比如 500)
|
||||
data = {
|
||||
'msg': 'Internal Server Error',
|
||||
'data': None,
|
||||
'code': 500
|
||||
}
|
||||
response = Response(data, status=500)
|
||||
|
||||
return response
|
||||
66
website/smalltalkapp/unity/preprocess_response.py
Normal file
66
website/smalltalkapp/unity/preprocess_response.py
Normal file
@@ -0,0 +1,66 @@
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.status import is_success
|
||||
|
||||
|
||||
class ResponseFormat:
|
||||
def __init__(self,msg,data,code):
|
||||
self.msg = msg
|
||||
self.data = data
|
||||
self.code = code
|
||||
def response(self):
|
||||
# if self.code == 201:
|
||||
# return Response({'msg':self.msg,'data':self.data,'code':self.code})
|
||||
print(self.data)
|
||||
if is_success(self.code):
|
||||
return Response({'msg':self.msg,'data':self.data,'code':self.code})
|
||||
return Response({'msg':'here is some error','data':self.data,'code':self.code})
|
||||
|
||||
|
||||
class UnifiedResponseAPIView:
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
response = super().create(request, *args, **kwargs)
|
||||
res = ResponseFormat(
|
||||
msg='success',
|
||||
data=response.data,
|
||||
code=response.status_code
|
||||
)
|
||||
return res.response()
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
response = super().list(request, *args, **kwargs)
|
||||
res = ResponseFormat(
|
||||
msg='success',
|
||||
data=response.data,
|
||||
code=response.status_code
|
||||
)
|
||||
return res.response()
|
||||
def retrieve(self, request, *args, **kwargs):
|
||||
response = super().retrieve( request, *args, **kwargs)
|
||||
res = ResponseFormat(
|
||||
msg='success',
|
||||
data=response.data,
|
||||
code=response.status_code
|
||||
)
|
||||
return res.response()
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
# no request.data
|
||||
response = super().update( request, *args, **kwargs)
|
||||
res = ResponseFormat(
|
||||
msg='success',
|
||||
data=response.data,
|
||||
code=response.status_code
|
||||
)
|
||||
return res.response()
|
||||
def destroy(self, request, *args, **kwargs):
|
||||
response = super().destroy( request, *args, **kwargs)
|
||||
res = ResponseFormat(
|
||||
msg='success',
|
||||
data=response.data,
|
||||
code=response.status_code
|
||||
)
|
||||
return res.response()
|
||||
|
||||
|
||||
|
||||
27
website/smalltalkapp/unity/username_random.py
Normal file
27
website/smalltalkapp/unity/username_random.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import random
|
||||
CHINESE_NAMES = [
|
||||
"脆皮的青年", "熬夜的冠军", "电子的咸鱼",
|
||||
"人间的清醒", "情绪的废物", "精神的股东",
|
||||
"网瘾的患者", "发疯的文学", "摆烂的艺术家",
|
||||
"赛博的菩萨", "数字的游民", "元宇宙的房东",
|
||||
"情绪的过山车", "抽象的废话", "深夜的emo",
|
||||
"心跳的漏拍", "心动的限定", "宇宙的浪漫",
|
||||
"银河的失眠者", "反向的安利王", "冷笑话的供应商",
|
||||
"气氛的组长", "离谱的博士", "人间的暂停键",
|
||||
"系统加载中", "404号的人类", "今天装死的我",
|
||||
"假装很酷的人", "沉默的金子", "氧气的泡泡",
|
||||
"碳酸的少年", "冰美式的上头", "晚风的贩卖机",
|
||||
"月光的收容所", "星星的收藏家", "情绪的调节器",
|
||||
"心跳的同步率", "梦境的漫游者", "灵魂的信号弱",
|
||||
"电量的残血", "缓存的满载", "更新中的系统",
|
||||
"人间的观察员", "生活BUG的反馈员", "快乐的代餐",
|
||||
"悲伤的收割机", "温柔的暴击", "心动的延迟",
|
||||
"宇宙的碎屑", "量子的心动", "平行世界的我",
|
||||
"今日份的发呆", "脑内的小剧场", "意识流的主播"
|
||||
]
|
||||
|
||||
class RandomName:
|
||||
|
||||
@staticmethod
|
||||
def generate_name():
|
||||
return random.choice(CHINESE_NAMES)
|
||||
8
website/smalltalkapp/urls.py
Normal file
8
website/smalltalkapp/urls.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path('smalltalk/', views.SmalltalkList.as_view() ),
|
||||
path('smalltalk/create/', views.SmalltalkCreateView.as_view() ),
|
||||
path('smalltalk/<int:pk>/', views.SmalltalkDetailView.as_view() ),
|
||||
]
|
||||
22
website/smalltalkapp/views.py
Normal file
22
website/smalltalkapp/views.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from django.shortcuts import render
|
||||
from rest_framework import generics
|
||||
|
||||
from .models import Smalltalk
|
||||
from .serializers import SmalltalkSerializer, SmalltalkCreateSerializer
|
||||
from .unity.preprocess_response import UnifiedResponseAPIView
|
||||
|
||||
|
||||
# Create your views here.
|
||||
|
||||
class SmalltalkCreateView(UnifiedResponseAPIView,generics.CreateAPIView):
|
||||
queryset = Smalltalk.objects.all()
|
||||
serializer_class = SmalltalkCreateSerializer
|
||||
|
||||
class SmalltalkList(UnifiedResponseAPIView,generics.ListAPIView):
|
||||
queryset = Smalltalk.objects.all()
|
||||
serializer_class = SmalltalkSerializer
|
||||
|
||||
|
||||
class SmalltalkDetailView(UnifiedResponseAPIView,generics.RetrieveUpdateDestroyAPIView):
|
||||
queryset = Smalltalk.objects.all()
|
||||
serializer_class = SmalltalkSerializer
|
||||
0
website/website/__init__.py
Normal file
0
website/website/__init__.py
Normal file
16
website/website/asgi.py
Normal file
16
website/website/asgi.py
Normal file
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
ASGI config for website project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')
|
||||
|
||||
application = get_asgi_application()
|
||||
130
website/website/settings.py
Normal file
130
website/website/settings.py
Normal file
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
Django settings for website project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 5.2.6.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/5.2/ref/settings/
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'django-insecure-6ehh*7^wfs=d6cwcddgqu_0k)da%%ph(8gdh0_-)v#9pm4rikz'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'rest_framework',
|
||||
'drf_yasg',
|
||||
'smalltalkapp'
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'website.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'website.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/5.2/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'zh-hans'
|
||||
TIME_ZONE = 'Asia/Shanghai'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/5.2/howto/static-files/
|
||||
|
||||
STATIC_URL = 'static/'
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
|
||||
'PAGE_SIZE': 10, # 每页显示10条
|
||||
'EXCEPTION_HANDLER': 'smalltalkapp.unity.exceptions.custom_exception_handler'
|
||||
}
|
||||
46
website/website/urls.py
Normal file
46
website/website/urls.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
URL configuration for website project.
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/5.2/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.urls import path, include
|
||||
from rest_framework import permissions
|
||||
from drf_yasg.views import get_schema_view
|
||||
from drf_yasg import openapi
|
||||
|
||||
|
||||
|
||||
schema_view = get_schema_view(
|
||||
openapi.Info(
|
||||
title="Snippets API",
|
||||
default_version='v1',
|
||||
description="Test description",
|
||||
terms_of_service="https://www.google.com/policies/terms/",
|
||||
contact=openapi.Contact(email="contact@snippets.local"),
|
||||
license=openapi.License(name="BSD License"),
|
||||
),
|
||||
public=True,
|
||||
permission_classes=[permissions.AllowAny,],
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
path('smalltalkapp/', include('smalltalkapp.urls') ),
|
||||
|
||||
path('swagger.<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'),
|
||||
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
|
||||
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
|
||||
|
||||
]
|
||||
16
website/website/wsgi.py
Normal file
16
website/website/wsgi.py
Normal file
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
WSGI config for website project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')
|
||||
|
||||
application = get_wsgi_application()
|
||||
Reference in New Issue
Block a user