add users and change api

This commit is contained in:
ilia 2022-03-19 20:23:17 +03:00
parent 5856b27dcd
commit 8e60b9cd01
45 changed files with 400 additions and 11 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,5 +1,7 @@
from rest_framework.serializers import ModelSerializer from rest_framework.serializers import ModelSerializer, Serializer, CharField, HyperlinkedModelSerializer, Field
from chat_models.models import Chat, Message from chat_models.models import Chat, Message
from users.models import UserChat, User
from rest_framework import viewsets
class ChatSerializer(ModelSerializer): class ChatSerializer(ModelSerializer):
@ -12,3 +14,73 @@ class MessageSerializer(ModelSerializer):
class Meta: class Meta:
model = Message model = Message
fields = "__all__" fields = "__all__"
class UserChatSerializer(ModelSerializer):
class Meta:
model = UserChat
fields = "__all__"
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = "__all__"
lookup_field = 'user__tg_id'
class UserHyperlinkedSerializer(HyperlinkedModelSerializer):
user_tg = Field(source="user.tg_id")
class Meta:
model = User
fields = "__all__"
lookup_field = 'user_tg'
class MessageCreateWithUsername(Serializer):
author_tg_nickname = CharField(write_only=True)
message = CharField(write_only=True)
chat_id = CharField(write_only=True)
created_message = MessageSerializer(read_only=True)
def create(self, validated_data):
message = validated_data["message"]
author_tg_nickname = validated_data["author_tg_nickname"]
chat_id = validated_data["chat_id"]
messageModel = Message.objects.create(
text=message,
author=User.objects.get(tg_id=author_tg_nickname),
chat=Chat.objects.get(tg_id=chat_id),
)
return {
"created_message": messageModel
}
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
lookup_field = 'tg_id'
queryset = User.objects.all()
class ChatCreateWithTg(Serializer):
name = CharField(write_only=True)
startMessage = CharField(write_only=True)
api_key = CharField(write_only=True)
tg_id = CharField(write_only=True)
admin_tg_id = CharField(write_only=True)
chat = ChatSerializer(read_only=True)
def create(self, validated_data):
name = validated_data['name']
startMessage = validated_data['startMessage']
api_key = validated_data['api_key']
tg_id = validated_data['tg_id']
admin_tg_id = validated_data['admin_tg_id']
chat = Chat.objects.create(name=name,
start_message=startMessage,
api_key=api_key,
admin=User.objects.get(tg_id=admin_tg_id),
tg_id=tg_id)
return {'chat': chat}

View File

@ -1,10 +1,18 @@
from django.urls import path from django.urls import path
from .views import ListCreateMessage, ListCreateChat, RetrieveUpdateMessage, RetrieveUpdateDestroyChat from .views import ListCreateMessage, ListCreateChat, RetrieveUpdateMessage, RetrieveUpdateDestroyChat, \
ListCreateUserChat, ListCreateUser, RetrieveUpdateUserChat, RetrieveUpdateUser, CreateMessageFromUsername, CreateChatWithUsername
from .serializers import UserViewSet
from rest_framework.routers import DefaultRouter
from .viewsets import UserViewSet, MessageViewSet, ChatViewSet
router = DefaultRouter()
router.register('user', UserViewSet, basename='user')
router.register('message', MessageViewSet, basename='message')
router.register('chat', ChatViewSet, basename='chat')
urlpatterns = [ urlpatterns = [
path("chat", ListCreateChat.as_view()), path("message-from-username", CreateMessageFromUsername.as_view()),
path("message", ListCreateMessage.as_view()), path("chat-from-username", CreateChatWithUsername.as_view())
path("chat/<pk>", RetrieveUpdateDestroyChat.as_view()),
path("message/<pk>", RetrieveUpdateMessage.as_view())
] ]
urlpatterns.extend(router.urls)

View File

@ -1,6 +1,8 @@
from .serializers import ChatSerializer, MessageSerializer from .serializers import ChatSerializer, MessageSerializer, UserSerializer, UserChatSerializer, \
MessageCreateWithUsername, UserHyperlinkedSerializer, ChatCreateWithTg
from chat_models.models import Chat, Message from chat_models.models import Chat, Message
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.generics import ListCreateAPIView, RetrieveUpdateAPIView, CreateAPIView
from users.models import User, UserChat
class ListCreateMessage(ListCreateAPIView): class ListCreateMessage(ListCreateAPIView):
@ -21,3 +23,31 @@ class RetrieveUpdateMessage(RetrieveUpdateAPIView):
class RetrieveUpdateDestroyChat(RetrieveUpdateAPIView): class RetrieveUpdateDestroyChat(RetrieveUpdateAPIView):
queryset = Chat.objects.all() queryset = Chat.objects.all()
serializer_class = ChatSerializer serializer_class = ChatSerializer
class ListCreateUser(ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserHyperlinkedSerializer
class ListCreateUserChat(ListCreateAPIView):
queryset = UserChat.objects.all()
serializer_class = UserHyperlinkedSerializer
class RetrieveUpdateUserChat(RetrieveUpdateAPIView):
queryset = UserChat.objects.all()
serializer_class = UserHyperlinkedSerializer
class RetrieveUpdateUser(RetrieveUpdateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class CreateMessageFromUsername(CreateAPIView):
serializer_class = MessageCreateWithUsername
class CreateChatWithUsername(CreateAPIView):
serializer_class = ChatCreateWithTg

22
api/viewsets.py Normal file
View File

@ -0,0 +1,22 @@
from rest_framework import viewsets
from users.models import User
from chat_models.models import Message, Chat
from .serializers import UserSerializer, MessageSerializer, ChatSerializer
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
lookup_field = 'tg_id'
queryset = User.objects.all()
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
lookup_field = 'tg_id'
queryset = Message.objects.all()
class ChatViewSet(viewsets.ModelViewSet):
serializer_class = ChatSerializer
lookup_field = 'tg_id'
queryset = Chat.objects.all()

View File

@ -0,0 +1,18 @@
# Generated by Django 4.0.3 on 2022-03-19 12:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat_models', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='message',
name='time_created',
field=models.DateTimeField(auto_now_add=True, null=True),
),
]

View File

@ -0,0 +1,20 @@
# Generated by Django 4.0.3 on 2022-03-19 12:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0002_alter_user_joined'),
('chat_models', '0002_message_time_created'),
]
operations = [
migrations.AlterField(
model_name='message',
name='author',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='users.user'),
),
]

View File

@ -0,0 +1,30 @@
# Generated by Django 3.1.7 on 2022-03-19 13:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20220319_1617'),
('chat_models', '0003_alter_message_author'),
]
operations = [
migrations.AddField(
model_name='chat',
name='admin',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='users.user'),
),
migrations.AlterField(
model_name='chat',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='message',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.1.7 on 2022-03-19 15:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat_models', '0004_auto_20220319_1617'),
]
operations = [
migrations.AddField(
model_name='message',
name='tg_id',
field=models.CharField(max_length=100, null=True),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.1.7 on 2022-03-19 15:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat_models', '0005_message_tg_id'),
]
operations = [
migrations.AddField(
model_name='chat',
name='tg_id',
field=models.CharField(max_length=100, null=True),
),
]

View File

@ -5,9 +5,13 @@ class Chat(models.Model):
name = models.TextField() name = models.TextField()
start_message = models.TextField(blank=True) start_message = models.TextField(blank=True)
api_key = models.TextField() api_key = models.TextField()
admin = models.ForeignKey("users.User", on_delete=models.CASCADE, null=True)
tg_id = models.CharField(max_length=100, null=True)
class Message(models.Model): class Message(models.Model):
text = models.TextField() text = models.TextField()
author = models.TextField() author = models.ForeignKey("users.User", on_delete=models.CASCADE, null=True)
chat = models.ForeignKey(Chat, on_delete=models.CASCADE) chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
time_created = models.DateTimeField(auto_now_add=True, null=True)
tg_id = models.CharField(null=True, max_length=100)

View File

@ -29,7 +29,6 @@ ALLOWED_HOSTS = ['*']
# Application definition # Application definition
INSTALLED_APPS = [ INSTALLED_APPS = [
'django.contrib.admin', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.auth',
@ -37,15 +36,19 @@ INSTALLED_APPS = [
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'corsheaders',
'rest_framework', 'rest_framework',
'chat_models', 'chat_models',
'api' 'api',
'users',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
@ -82,6 +85,7 @@ DATABASES = {
'NAME': BASE_DIR / 'db.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3',
} }
} }
CORS_ORIGIN_ALLOW_ALL = True
# Password validation # Password validation

View File

@ -1,5 +1,6 @@
asgiref==3.5.0 asgiref==3.5.0
Django==4.0.3 Django==4.0.3
django-cors-headers==3.11.0
djangorestframework==3.13.1 djangorestframework==3.13.1
pytz==2021.3 pytz==2021.3
sqlparse==0.4.2 sqlparse==0.4.2

0
users/__init__.py Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

3
users/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
users/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'

View File

@ -0,0 +1,32 @@
# Generated by Django 4.0.3 on 2022-03-19 12:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('chat_models', '0002_message_time_created'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.TextField()),
('joined', models.DateTimeField()),
],
),
migrations.CreateModel(
name='UserChat',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('chat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chat_models.chat')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.user')),
],
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 4.0.3 on 2022-03-19 12:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='joined',
field=models.DateTimeField(auto_now_add=True),
),
]

View File

@ -0,0 +1,23 @@
# Generated by Django 3.1.7 on 2022-03-19 13:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_alter_user_joined'),
]
operations = [
migrations.AlterField(
model_name='user',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='userchat',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.1.7 on 2022-03-19 13:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20220319_1617'),
]
operations = [
migrations.AddField(
model_name='user',
name='tg_id',
field=models.CharField(max_length=100, null=True),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.1.7 on 2022-03-19 15:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_user_tg_id'),
]
operations = [
migrations.AlterField(
model_name='user',
name='tg_id',
field=models.CharField(max_length=100, null=True, unique=True),
),
]

View File

Binary file not shown.

20
users/models.py Normal file
View File

@ -0,0 +1,20 @@
from django.db import models
from chat_models.models import Chat
class User(models.Model):
username = models.TextField()
joined = models.DateTimeField(auto_now_add=True)
tg_id = models.CharField(max_length=100, null=True, unique=True)
def __str__(self):
return "User({}, {})".format(self.username, self.tg_id)
class UserChat(models.Model):
chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return "Chat rel with {} chat and {} user".format(self.chat, self.user)

3
users/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
users/views.py Normal file
View File

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.