1
1
# ruff: noqa: S311, S106
2
2
"""create_demo management command"""
3
3
4
+ import base64
4
5
import logging
5
6
import math
6
7
import random
7
8
import time
8
9
from collections import defaultdict
10
+ from uuid import uuid4
9
11
10
12
from django import db
11
13
from django .conf import settings
12
14
from django .core .management .base import BaseCommand , CommandError
13
15
16
+ import pycrdt
14
17
from faker import Faker
15
18
16
19
from core import models
@@ -27,6 +30,16 @@ def random_true_with_probability(probability):
27
30
return random .random () < probability
28
31
29
32
33
+ def get_ydoc_for_text (text ):
34
+ """Return a ydoc from plain text for demo purposes."""
35
+ ydoc = pycrdt .Doc ()
36
+ paragraph = pycrdt .XmlElement ("p" , {}, [pycrdt .XmlText (text )])
37
+ fragment = pycrdt .XmlFragment ([paragraph ])
38
+ ydoc ["document-store" ] = fragment
39
+ update = ydoc .get_update ()
40
+ return base64 .b64encode (update ).decode ("utf-8" )
41
+
42
+
30
43
class BulkQueue :
31
44
"""A utility class to create Django model instances in bulk by just pushing to a queue."""
32
45
@@ -48,7 +61,7 @@ def _bulk_create(self, objects):
48
61
self .queue [objects [0 ]._meta .model .__name__ ] = [] # noqa: SLF001
49
62
50
63
def push (self , obj ):
51
- """Add a model instance to queue to that it gets created in bulk."""
64
+ """Add a model instance to queue so that it gets created in bulk."""
52
65
objects = self .queue [obj ._meta .model .__name__ ] # noqa: SLF001
53
66
objects .append (obj )
54
67
if len (objects ) > self .BATCH_SIZE :
@@ -139,17 +152,19 @@ def create_demo(stdout):
139
152
# pylint: disable=protected-access
140
153
key = models .Document ._int2str (i ) # noqa: SLF001
141
154
padding = models .Document .alphabet [0 ] * (models .Document .steplen - len (key ))
142
- queue . push (
143
- models .Document (
144
- depth = 1 ,
145
- path = f" { padding } { key } " ,
146
- creator_id = random . choice ( users_ids ) ,
147
- title = fake . sentence ( nb_words = 4 ),
148
- link_reach = models . LinkReachChoices . AUTHENTICATED
149
- if random_true_with_probability ( 0.5 )
150
- else random . choice ( models . LinkReachChoices . values ),
151
- )
155
+ title = fake . sentence ( nb_words = 4 )
156
+ document = models .Document (
157
+ id = uuid4 () ,
158
+ depth = 1 ,
159
+ path = f" { padding } { key } " ,
160
+ creator_id = random . choice ( users_ids ),
161
+ title = title ,
162
+ link_reach = models . LinkReachChoices . AUTHENTICATED
163
+ if random_true_with_probability ( 0.5 )
164
+ else random . choice ( models . LinkReachChoices . values ),
152
165
)
166
+ document .save_content (get_ydoc_for_text (f"Content for { title :s} " ))
167
+ queue .push (document )
153
168
154
169
queue .flush ()
155
170
0 commit comments