async def _topic(request, topic_id=None): form = TopicForm(request) form.status.data = int(form.status.data) topic = None if topic_id is not None: topic = await SpecialTopic.get_or_404(topic_id) if request.method in ('POST', 'PUT') and form.validate(): dct = defaultdict(dict) for k in copy.copy(request.form): if k.startswith('posts'): match = FORM_REGEX.search(k) if match: key = match['key'] val = request.form[k][0] dct[match['index']][key] = int(val) if key == 'id' else val del request.form[k] title = form.title.data if topic_id is None: topic = await SpecialTopic.filter(title=title).first() if not topic: topic = SpecialTopic() form.populate_obj(topic) if dct: indexes = [ (i['id'], int(index)) for index, i in sorted(dct.items(), key=lambda i: i[0]) ] else: indexes = [] if topic_id is not None: await topic.set_indexes(indexes) await topic.save() if topic_id is None: await topic.set_indexes(indexes) ok = True else: ok = False topic = await topic.to_sync_dict() return json({'topic': topic if topic else None, 'ok': ok})
async def _topic(request: Request, topic_id: Optional[Any] = None): form = TopicForm(request) form.status.data = int(form.status.data) topic = None if topic_id is not None: topic = await SpecialTopic.get_or_404(topic_id) if request.method in ('POST', 'PUT') and form.validate(): dct: DefaultDict[str, Dict[str, int]] = defaultdict(dict) for k in copy.copy(request.form): if k.startswith('posts'): match = FORM_REGEX.search(k) if (match := FORM_REGEX.search(k)): key = match['key'] # type: ignore val = request.form[k][0] dct[match['index']][key] = ( # type: ignore int(val) if key == 'id' else val) del request.form[k] title = form.title.data if topic_id is None: topic = await SpecialTopic.filter(title=title).first() if not topic: topic = SpecialTopic() form.populate_obj(topic) if dct: indexes = [ (i['id'], int(index)) for index, i in sorted(dct.items(), key=lambda i: i[0]) ] else: indexes = [] if topic_id is not None: await topic.set_indexes(indexes) await topic.save() if topic_id is None: await topic.set_indexes(indexes) ok = True