Beispiel #1
0
def topics(operation=None, topic_id=-1):
    form = NewTopicForm(request.form)

    if request.method == 'POST' and form.validate_on_submit():
        topic = Topic(name=form.topic.data)
        db.session.add(topic)
        db.session.commit()
        flash('New topic is created')
        return redirect(url_for('topics'))
    if operation == 'delete':
        try:
            topic = Topic().query.get(topic_id)
            db.session.delete(topic)
            db.session.commit()
        except:
            flash("Failed to delete topic {}.".format(topic_id))
        return redirect(url_for('topics'))
    if operation == 'update':
        try:
            topic = Topic().query.get(topic_id)
            topic.name = request.values.get("value")
            db.session.add(topic)
            db.session.commit()
        except:
            return 'Error renaming topic.', 400
        else:
            return 'Topic updted successfuly.', 200

    topics = Topic().query.all()
    return render_template('topics.html',
                           title='Topics',
                           form=form,
                           topics=topics)
Beispiel #2
0
def addtopic(t_id):
    form = InputOfTopic()
    if t_id != 0:
        topic = Topic.getById(t_id)
        form.content.data = topic.content
        form.title.data = topic.title
    if form.validate_on_submit():
        flag_id = request.form['radioInline']
        title = form.title.data
        content = form.content.data
        if t_id != 0:
            sess.query(Topic).filter(Topic.id == t_id).update({
                Topic.content:
                content,
                Topic.author:
                g.user.id,
                Topic.title:
                title,
                Topic.flag:
                flag_id
            })
        else:
            sess.add(
                Topic(id=0,
                      content=content,
                      author=g.user.id,
                      title=title,
                      flag=flag_id))
        sess.commit()
        return redirect('/bbslist/0')
    return render_template('add_topic.html', user=g.user, form=form)
def topic_new(request, template_name='private_messages/topic_new.html'):
    if request.method == 'POST':
        form = NewTopicForm(data=request.POST)
        if form.is_valid():
            message = form.save(commit=False)

            topic = Topic(sender=request.user)
            topic.recipient = form.cleaned_data['recipient']
            topic.subject = form.cleaned_data['subject']
            topic.last_sent_at = datetime.now()
            topic.save()

            message.topic = topic
            message.sender = request.user
            message.save()

            return HttpResponseRedirect(topic.get_absolute_url())
    else:
        initial = {}
        if request.GET.has_key('recipient'):
            initial['recipient'] = request.GET['recipient']

        form = NewTopicForm(initial=initial)

    return TemplateResponse(request, template_name, {
        'pm_form': form,
    })
Beispiel #4
0
def create_topic():
    """View for create topic"""
    if request.method == 'POST':

        topic_s = request.form['topic']
        error = None

        if not topic_s:
            error = 'No mandatory property is set.'
        else:
            topic = Topic.query.filter_by(topic=topic_s).first()
            if topic is not None:
                error = "The topic is already exist."      

        if error is not None:
            flash(error)
        else:            
            try:
                topic = Topic(topic=topic_s)
                db.session.add(topic)
                db.session.commit()
                return redirect(url_for('topic.topic_index'))

            except OSError as e:
                flash("Creation of the directory %s failed" % tag)
            except Exception as e:
                print(e)
                flash("DB Creation Failed")

    return render_template('topics/create.html')
    def insert_message(self, msg, device):
        if msg["device_tag"] and msg["keys"] and msg["values"] and msg[
                "device_topic"]:
            device_tag = str(msg["device_tag"])
            device_topic = str(msg["device_topic"])
            db_t = TinyDB('device_data/' + device.tag + "/" + device_tag +
                          ".json")
            table = db_t.table(str(msg["device_topic"]))
            values = {}
            value = 0
            for key in msg["keys"]:
                values[key] = msg["values"][value]
                value += 1
            values["time"] = msg["time"]
            table.insert(values)
            topic = Topic.query.filter_by(topic=device_topic).first()
            device = Device.query.filter_by(tag=device_tag).first()
            if topic is None:
                topic = Topic(topic=device_topic, active_devices=1)
            else:
                add = True
                for top_dev in device.topics:
                    if top_dev.topic == topic.topic:
                        add = False
                if add:
                    topic.active_devices += 1
                topic.last_update = datetime.utcnow()

            device.topics.append(topic)
            db.session.add(device)
            db.session.commit()
Beispiel #6
0
def saveTopics(item, forum):
    topics = []
    count = 0
    for t in item['topic']:
        if '_id' not in t.keys():
            continue
        if t['_id'] is None:
            continue
        tags = []
        if isinstance(t['tags'], list):
            for tt in t['tags']:
                tags.append(tt['tag'])
        top_key = ndb.Key(Topic, str(t['_id']))
        if not counted(top_key, forum):
            count += 1
        topic = Topic(key=top_key,
                      top_id=str(t['_id']),
                      vote=t['votes'],
                      comment=t['comments'],
                      author=t['author'],
                      disp_topic=t['disp_topic'],
                      topic_type=str(t['topic_type']),
                      utime=datetime.strptime(t['utime'], '%m/%d/%Y %H:%M:%S'),
                      tags=tags,
                      forums=addForum(top_key, forum))
        topics.append(topic)
    ndb.put_multi_async(topics)
    last_id = str(item['last_id_current_page'])
    return count, last_id
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding users
        user = User(
            email='*****@*****.**',
            encrypted_password=encrypt('password'),
            name='john_doe'
        )
        student = Student(user, 'U1722')
        db.session.add(student)

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)
        
        # add lessons
        lesson = Lesson(topic_id='1', id='3', name='se', content='test')
        db.session.add(lesson)

        # add questions
        qn = Question('1', '3', 'easy')
        db.session.add(qn)

        # add questionChoice
        qc = initializeQuestionChoice(1,'A',False)
        db.session.add(qc)

        db.session.commit()
Beispiel #8
0
def addTopic(topic):
    """
    function to add a new topic, creates required classifier files and database entries.
    """
    c = Classifier(classifierDir, [topic, "not"+topic])
    
    newTopic = Topic(title = topic)
Beispiel #9
0
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding users
        user = User(
            email='*****@*****.**',
            encrypted_password=encrypt('password'),
            name='john_doe'
        )
        student = Student(user, 'U1722')
        db.session.add(student)

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)

        # adding lessons
        lesson = Lesson(topic_id=1, id=1, name='se', content='test')
        db.session.add(lesson)

        # adding questions
        qn_1 = Question(1, 1,'easy')
        db.session.add(qn_1)

        qn_2 = Question(1, 1,'medium')
        db.session.add(qn_2)
        
        db.session.commit()
Beispiel #10
0
 def save(self):
     topic_post = False
     if not self.topic:
         topic_type = self.cleaned_data['topic_type']
         if topic_type:
             topic_type = TopicType.objects.get(id=topic_type)
         else:
             topic_type = None
         topic = Topic(
             forum=self.forum,
             posted_by=self.user,
             subject=self.cleaned_data['subject'],
             need_replay=self.cleaned_data['need_replay'],
             need_reply_attachments=self.
             cleaned_data['need_reply_attachments'],
             topic_type=topic_type,
         )
         topic_post = True
         topic.save()
     else:
         topic = self.topic
     post = Post(topic=topic,
                 posted_by=self.user,
                 poster_ip=self.ip,
                 message=self.cleaned_data['message'],
                 topic_post=topic_post)
     post.save()
     attachments = self.cleaned_data['attachments']
     post.update_attachments(attachments)
     return post
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)

        # adding lessons
        lesson = Lesson(topic_id=1, id=1, name='se', content='test')
        db.session.add(lesson)

        # adding users
        user = User('*****@*****.**', encrypt('password'), 'staff_name')
        staff = Staff(user)
        db.session.add(staff)

        # adding quizzes
        quiz = Quiz(1, 'quiz_name', True, '2020-03-21', '2020-03-22')
        db.session.add(quiz)

        db.session.commit()
Beispiel #12
0
    def post(self):
        """
        POST method adds new topic to collection
        """
        if not request.json:
            return create_error_response(415, "Unsupported media type",
                                         "Request must be JSON")

        try:
            validate(request.json, BoardBuilder.topic_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid JSON document", str(e))

        new_topic = Topic(id=request.json["id"],
                          header=request.json["header"],
                          message=request.json["message"],
                          time=request.json["time"],
                          user_id=request.json["user_id"])

        try:
            db.session.add(new_topic)
            db.session.commit()
        except IntegrityError:
            return create_error_response(409, "Already exists",
                                         "Topic already inserted")

        return Response(
            status=201,
            headers={"Location": api.url_for(TopicItem, id=new_topic.id)})
Beispiel #13
0
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding users
        user_1 = User('*****@*****.**', encrypt('password'), 'student_1')
        student_1 = Student(user_1, 'U00000000A')
        db.session.add(student_1)

        user_2 = User('*****@*****.**', encrypt('password'), 'student_2')
        student_2 = Student(user_2, 'U00000000B')
        db.session.add(student_2)

        user_3 = User('*****@*****.**', encrypt('password'), 'teacher_1')
        staff_1 = Staff(user_3)
        db.session.add(staff_1)

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)

        # adding lessons
        lesson = Lesson(1, 1, 'lesson_1', 'content')
        db.session.add(lesson)

        # adding quizzes
        quiz = Quiz(3, 'quiz_1', True, '2020-03-30', '2020-03-31')
        db.session.add(quiz)

        db.session.commit()
Beispiel #14
0
def new_topic(request, gname):
    '''
		login user add a new topic
	'''
    vars = {}
    group = Group.objects.get(name=gname)
    vars['group'] = group
    if request.method == "POST":
        rev_title = request.POST.get("rev_title", "")
        rev_text = request.POST.get("rev_text", "")
        image_names = request.POST.get("image_names", "")
        if rev_text == "" or rev_title == '':
            vars["msg"] = "标题和内容不能不写啊"
            return render(request, 'new_topic.html', vars)
        images = image_names.split("|")[:-1]
        image_str = ""
        for im in images:
            image_str += "%s<br/>" % im
        rev_text = image_str + ">>>>||>>>>" + rev_text
        topic = Topic(name=rev_title, content=rev_text, group=group, creator=request.user)
        topic.save()
        topic_amount = Topic_reply_amount(topic=topic, amount=0)
        topic_amount.save()
        return redirect("topic", id=topic.id)
    return render(request, 'new_topic.html', vars)
Beispiel #15
0
 def save(self):
     topic_post = False
     if not self.topic:
         topic_type = self.cleaned_data['topic_type']
         if topic_type:
             topic_type = TopicType.objects.get(id=topic_type)
         else:
             topic_type = None
         topic = Topic(
             forum=self.forum,
             posted_by=self.user,
             subject=self.cleaned_data['subject'],
             topic_type=topic_type,
         )
         topic_post = True
         topic.save()
     else:
         topic = self.topic
     #print 'self.cleaned_data\n',self.cleaned_data
     post = Post(topic=topic,
                 posted_by=self.user,
                 poster_ip=self.ip,
                 message=self.cleaned_data['message'],
                 secret=self.cleaned_data["secret"],
                 topic_post=topic_post)
     post.save()
     if topic_post:
         topic.post = post
         topic.save()
     return post
Beispiel #16
0
def addTopic():
    form = AddTopicForm()
    if form.validate_on_submit():
        topic = form.name.data
        newTopic = Topic(body=topic)
        db.session.add(newTopic)
        db.session.commit()
        return redirect('/')
def _populate_db():
    """
    Pre-populate database with 2 topics, 2 users and 2 messages
    """
    topic1 = Topic(
        id=1,
        header="Pervo",
        message="prv o prvo",
        date="Aika",
        user_id=1,
    )

    topic2 = Topic(
        id=2,
        header="Pervo",
        message="prv o prvo",
        date="Aika",
        user_id=2,
    )

    message1 = Message(id=1,
                       message="asdasdasdasd",
                       date="Aika",
                       user_id=1,
                       parent_topic_id=1)

    message2 = Message(id=2,
                       message="asdasdasdasd",
                       date="Aika",
                       user_id=2,
                       parent_topic_id=2)

    user1 = User(id=1, name="paavo", password="******")

    user2 = User(id=2, name="pertti", password="******")

    db.session.add(topic1)
    db.session.add(topic2)

    db.session.add(message1)
    db.session.add(message2)

    db.session.add(user1)
    db.session.add(user2)
    db.session.commit()
Beispiel #18
0
def new_interest_group(message):
    print("message = ", message)
    print(message['data']['message'])
    myEmail = session.get('email')
    user = User.query.filter_by(email=myEmail).first()
    others = User.query.filter(User.email != myEmail).all()
    interests = user.interests
    interests_set = set()
    for i in interests:
        print(i.interest_name)
        interests_set.add(i.interest_name.lower())

    same_interests = []
    interest_to_users = {}

    topic_name = ""

    for i in interests_set:
        count = 0
        friends = []
        for other in others:
            for other_i in other.interests:
                if other_i.interest_name.lower() == i:
                    count += 1
                    friends.append(other.username)
        if count > 0:
            heappush(same_interests, (-count, i))
            interest_to_users[i] = friends

    print(same_interests)

    interest = ""
    while len(same_interests) > 0:
        interest = heappop(same_interests)[1]
        print("interest" + interest)
        if Topic.query.filter_by(topicname=interest).first() != None:
            continue
        topic_name = interest
        room = Topic(topic_name, user.uid)
        db.session.add(room)
        db.session.commit()
        room = Topic.query.filter_by(topicname=topic_name).first()
        mod = Moderator(user.uid, room.uid)
        db.session.add(mod)
        db.session.commit()
        break

    if topic_name == "":
        emit('redirect', '/random_setting')
    else:
        emit('redirect', '/chat/' + room.topicname)
        emit('alert', {
            'topic': room.topicname,
            'users': json.dumps(interest_to_users[interest])
        },
             namespace='/',
             broadcast=True)
Beispiel #19
0
def topic_questions(topic_id=None):
    if topic_id == None:
        return "Topic id not found", 404
    topic = Topic().query.get(topic_id)

    return render_template('topic_questions.html',
                           title='Questions for topic {}'.format(topic.name),
                           topic_id=topic_id,
                           questions=topic.questions)
def topic():
    if request.method == 'POST':
        topic = Topic(title=request.form['title'],
                      description=request.form['description'])
        db_session.add(topic)
        db_session.commit()
        flash("New topic has been added")
        return redirect(url_for('index'))
    return render_template('topics.html')
Beispiel #21
0
 def post(self):
     """
     Creates topic
     """
     name = request.json.get('name')
     new_topic = Topic(name=name)
     db.session.add(new_topic)
     db.session.commit()
     return {'id': new_topic.id, 'name': new_topic.name}, 201
Beispiel #22
0
 def process_item(self, item, spider):
     topic = Topic(title=item["title"].encode("utf-8"),
                   created_at=item["publish_time"].encode("utf-8"))
     post = Post(content=item["body"].encode("utf-8"),
                 created_at=item["publish_time"].encode("utf-8"),
                 topic=topic)
     with session_scope(self.Session) as session:
         session.add(topic)
         session.add(post)
Beispiel #23
0
    def create_topic(cls, user_id, subject, description):
        new_topic = Topic(created_by=user_id,
                          updated_by=user_id,
                          topic_subject=subject,
                          topic_description=description)

        session.add(new_topic)
        session.commit()

        return new_topic
Beispiel #24
0
 def test_postSave(self):
     a = Topic(name='My special topic')
     a.save()
     # For each topic in the Topic model we need a self
     # referencing element in the closure table.
     topics = Topic.objects.all()
     for topic in topics:
         ct = Topic.index._ctModel.objects.get(ancestor=topic)
         self.assertTrue(ct.ancestor == ct.descendant
                         and ct.path_length == 0)
Beispiel #25
0
 def test_get_topic_by_uid_and_jsonp(self):
     t = Topic(name="foobar",
               category="cat",
               system="asystem",
               body="",
               excerpt="abody").put()
     r = self.c.get(path='/topics/' + t.uid + '/jsonp?callback=foo')
     self.assertEquals(r.status_code, 200)
     self.assertEquals(r.data,
                       'foo({"excerpt": "abody", "name": "foobar"})')
Beispiel #26
0
    def setUp(self):
        print('\r')
        # drop all tables in the database
        db.session.remove()
        db.drop_all()
        # crete all tables in the database
        db.create_all()

        # adding topics
        topic = Topic(name='seng')
        db.session.add(topic)
        db.session.commit()
Beispiel #27
0
def new_topic():
    if request.method == 'GET':
        return render_template('new_topic.html')

    elif request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        topic = Topic(name=name, description=description)
        db_session.add(topic)
        db_session.commit()

        return redirect(url_for('main'))
Beispiel #28
0
 def post(self):
     forum = self.request.get('title')
     forum_key = ndb.Key(Forum, forum)
     loops = int(self.request.get('loops'))
     last_id = self.request.get('last_id')
     url = 'https://pantip.com/forum/topic/ajax_json_all_topic_info_loadmore'
     headers = {
         'User-Agent': '*****@*****.**',
         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
         'x-requested-with': 'XMLHttpRequest'
     }
     payload = [('last_id_current_page', '0'), ('dataSend[room]', forum),
                ('dataSend[topic_type][type]', '0'),
                ('dataSend[topic_type][default_type]', '1'),
                ('thumbnailview', 'false'), ('current_page', '1')]
     if last_id != '0':
         payload[0] = (payload[0][0], last_id)
     res = requests.post(url, payload, headers=headers)
     j = res.json()
     item = j['item']
     looping = 0
     while len(item['topic']) > 0 and looping < loops:
         topics = []
         for t in item['topic']:
             if '_id' not in t.keys():
                 continue
             tags = []
             if isinstance(t['tags'], list):
                 for tt in t['tags']:
                     tags.append(ndb.Key(Tag, tt['tag']))
             top_key = ndb.Key(Topic, str(t['_id']))
             topic = Topic(key=top_key,
                           top_id=str(t['_id']),
                           vote=t['votes'],
                           comment=t['comments'],
                           author=t['author'],
                           disp_topic=t['disp_topic'],
                           topic_type=str(t['topic_type']),
                           utime=datetime.strptime(t['utime'],
                                                   '%m/%d/%Y %H:%M:%S'),
                           tags=tags,
                           forums=self._addForum(top_key, forum_key))
             topics.append(topic)
             # counting += 1
         ndb.put_multi_async(topics)
         # task.put_async()
         looping += 1
         last_id = str(item['last_id_current_page'])
         payload[0] = (payload[0][0], last_id)
         res = requests.post(url, payload, headers=headers)
         j = res.json()
         item = j['item']
Beispiel #29
0
def addTopic():
	form = NewTopic()
	if form:
		data = request.form
		newTopic = Topic(Title = data['title'],content = data['content'])
		newPost = Post(content = data['content'],topic = data['title'],author = current_user.username)
		activity = Activity(name = current_user.username, type = 't', topic = newPost.topic)
		db.session.add(newTopic)
		db.session.add(newPost)
		db.session.add(activity)
		db.session.commit()
		return redirect(url_for('allTopics'))
	return redirect(url_for('allTopics'))
Beispiel #30
0
 def test_edit_form(self):
     t = Topic(name="foo",
               category="cat",
               system="asystem",
               body="abody",
               meta_description=META_DESCRIPTION).put()
     r = self.c.get(path='/asystem/cat/foo/edit',
                    environ_overrides={'REMOTE_USER': '******'})
     self.assertEquals(r.status_code, 200)
     self.assertTrue('abody' in r.data)
     self.assertTrue('foo' in r.data)
     self.assertTrue('cat' in r.data)
     self.assertTrue('asystem' in r.data)