Beispiel #1
0
def create_post(id,dt):
    try:
        board = Forum.objects.filter(id = id)
    except Exception as e:
        print " exception value: ", e
        return redirect(url_for('.index'))
    threads = board[0].threads

    t_ret, sve_cnt = Helper().find_thread(threads,dt)
    form = CreatePostForm()
    if form.validate_on_submit():
        p=Helper().build_post(form,session['username'])
        pe = PostArrayEl()
        pe.key = str(len(t_ret.posts) + 1)
        pe.post = p
        t_ret.posts.append(pe)
        threads[sve_cnt - 1].thread=t_ret
        try:
            Forum.objects(slug=slug).update_one(set__threads=threads)
        except Exception as e:
            print " exception update value: ", e
            return redirect(url_for('.index'))


        return redirect(url_for('.board', slug=slug))



    return render_template('forum/create_post1.html', thread=t_ret,
                           form=form)
Beispiel #2
0
 def post(self, forum_id):
   author = cgi.escape(self.request.get('author'))
   forum_name = cgi.escape(self.request.get('forum'))
   title = cgi.escape(self.request.get('title'))
   url = cgi.escape(self.request.get('url'))
   text = cgi.escape(self.request.get('text'))
   forums = forum_name.strip().replace(" ", "").split(",")
   for submissions in forums[0:3]:
     post = ForumPost()
     forum = Forum.query(Forum.name == submissions).get()
     if forum != None:
       forum.posts += 1
     else:
       forum = Forum(name=submissions, posts=1)
     forum.put()
     post.text = text
     post.author = author
     post.forum_name = submissions
     post.title = title
     post.time = datetime.datetime.now() - datetime.timedelta(hours=7) #For PST
     post.url = url
     post.url_host = urlparse(url).hostname
     post.reference = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))
     post.put()
   self.redirect('/tech/{}'.format(forums[0]))
Beispiel #3
0
def create_post(id, dt):
    try:
        board = Forum.objects.filter(id=id)
    except Exception as e:
        print " exception value: ", e
        return redirect(url_for('.index'))
    threads = board[0].threads

    t_ret, sve_cnt = Helper().find_thread(threads, dt)
    form = CreatePostForm()
    if form.validate_on_submit():
        p = Helper().build_post(form, session['username'])
        pe = PostArrayEl()
        pe.key = str(len(t_ret.posts) + 1)
        pe.post = p
        t_ret.posts.append(pe)
        threads[sve_cnt - 1].thread = t_ret
        try:
            Forum.objects(slug=slug).update_one(set__threads=threads)
        except Exception as e:
            print " exception update value: ", e
            return redirect(url_for('.index'))

        return redirect(url_for('.board', slug=slug))

    return render_template('forum/create_post1.html', thread=t_ret, form=form)
Beispiel #4
0
    def post(self, forum_id):
        author = cgi.escape(self.request.get('author'))
        forum_name = cgi.escape(self.request.get('forum'))
        title = cgi.escape(self.request.get('title'))
        url = cgi.escape(self.request.get('url'))
        text = cgi.escape(self.request.get('text'))
        post = ForumPost()
        forum = Forum.query(Forum.name == forum_name).get()
        if forum != None:
            forum.posts += 1
        else:
            forum = Forum(name=forum_name, posts=1)
        forum.put()

        author = author[3:-2]
        post.text = text
        post.author = author
        post.forum_name = forum_name
        post.forumnyn_aty = forum.aty
        post.title = title
        post.time = datetime.datetime.now() - datetime.timedelta(
            hours=8)  #For PST
        post.url = url
        post.url_host = urlparse(url).hostname
        post.reference = ''.join(
            random.choice(string.ascii_lowercase + string.digits)
            for _ in range(8))
        post.put()
        self.redirect('/forum/{}'.format(forum_name))
Beispiel #5
0
def create_thread(id):
    try:
        board = Forum.objects.filter(id = id)
    except Exception as e:
        print " exception value: ", e
        return redirect(url_for('.index'))
    form = CreateThreadForm()
    if form.validate_on_submit():
        t=Helper().build_thread(form,session['username'])
        te=ThreadArrayEl()
        te.key = str(len(board[0].threads)+1)
        te.thread=t
        try:
            Forum.objects(slug=slug).update_one(push__threads=te)
        except Exception as e:
            print " exception update value: ", e
            return redirect(url_for('.index'))



        return redirect(url_for('.board', slug=slug))


    return render_template('forum/create_thread1.html', board=board[0],
                           form=form)
 def create(self, forum_group_slug, **data):
   forum_group = self.db.query(ForumGroup).filter_by(slug=forum_group_slug).first()
   
   if not forum_group:
     raise frame.Error404
   
   forum = Forum(**data)
   forum.forum_group = forum_group
   
   self.db.add(forum)
   self.db.commit()
   
   self.redirect('/')
Beispiel #7
0
def forum(request, forumid):
	forum = Forum.get_by_id(int(forumid))
	return render_to_response('home/forum.html',
	{
		'forum' : forum,
		'threadsviewmodel' : ThreadsViewModel(forum)
	})
Beispiel #8
0
 def post(self, sporocilo_id):
     izbris = Forum.get_by_id(int(sporocilo_id))
     #vmesnoime.key.delete()
     izbris.deleted = True
     izbris.put()
     time.sleep(1)
     self.redirect_to("forum1")
Beispiel #9
0
 def get(self, sporocilo_id):
     sporocilo = Forum.get_by_id(int(sporocilo_id))
     params = {"forum": sporocilo}
     #tale forum gre potem v html vse forum.neki itd.
     paramsif = is_logged_in()
     params.update(paramsif)
     self.render_template("zbrisiforum.html", params=params)
Beispiel #10
0
    def get_recurring_subreddits(self):
        """
        Utility method returns a list of recurring Forums aka subreddits 
        in top 100 'hot' Submissions of r/popular
        """
        # Get recurring subreddits
        seen_subreddits = {}  # dictionary for seen subreddits
        recurring_subreddits = []
        for submission in self.hot_submissions:
            try:
                # This subredit has already been seen at least once
                seen_subreddits[submission.subreddit] += 1  # increment count

                if seen_subreddits[submission.subreddit] == 2:
                    # First time subreddit has been seen more than once
                    new_forum = Forum(
                        title=submission.subreddit.display_name,
                        description=submission.subreddit.public_description)
                    # Add to list
                    recurring_subreddits.append(new_forum)

            except KeyError:
                # First time seeing this subreddit
                seen_subreddits[submission.subreddit] = 1

        # Return list of recurring Forums (subreddits)
        return recurring_subreddits
Beispiel #11
0
 def post(self, sporocilo_id):
     izbris = Forum.get_by_id(int(sporocilo_id))
     #vmesnoime.key.delete()
     izbris.deleted=True
     izbris.put()
     time.sleep(1)
     self.redirect_to("forum1")
Beispiel #12
0
 def get(self, sporocilo_id):
     sporocilo = Forum.get_by_id(int(sporocilo_id))
     params = {"forum": sporocilo}
     #tale forum gre potem v html vse forum.neki itd.
     paramsif = is_logged_in()
     params.update(paramsif)
     self.render_template("zbrisiforum.html", params=params)
Beispiel #13
0
def create_thread(request, forumid):
    forum = Forum.get_by_id(int(forumid))

    return render_to_response('home/create_thread.html', {
        'forum': forum,
        'thread_form': ThreadForm()
    })
Beispiel #14
0
    def post(self):
        imeforum = self.request.get("fime")
        print imeforum
        priimekforum = self.request.get("fpriimek")
        email = self.request.get("femail")

        sporocilo = self.request.get("fsporocilo")
        #params = {"fime" : imeforum }
        if sporocilo != "Obvezno vpisi kaj notri":
            forum = Forum(fime=imeforum, fpriimek=priimekforum, fsporocilo=sporocilo, femail=email)
            forum.put()
            time.sleep(1)
        fseznam = Forum.query().fetch()
        print fseznam
        params = {"forumseznam" : fseznam }
        return self.render_template("redirect.html" , params=params)
Beispiel #15
0
def create_thread(request, forumid):
	forum = Forum.get_by_id(int(forumid))
	
	return render_to_response('home/create_thread.html',
	{
		'forum' : forum,
		'thread_form' : ThreadForm()
	})
Beispiel #16
0
  def get(self):
    user = self.user_model
    search = cgi.escape(self.request.get('search'))
    #TODO normalize names in User model to ignore case
    search_list = search.split(',')
    results = []
    # For recuiters' advance search #
    jobs = []
    employers = []
    skills = []
    names = []
    forum_query = []
    search_type = " "
    if user.account_type == "Recruiter":
      search_type = "advanced"

    #Search Algorithm
    for search_string in search_list:
      search_string = search_string.strip(' ').lower()
      if "@" in search_string:
        q = User.query(User.email_address == search_string)
        if q:
          results.append(q.get())
      elif " " in search_string:
        person = search_string.split(' ')
        first_name = person[0]
        last_name = person[1]
        full_name = User.query(ndb.OR(User.lower_profession == search_string, 
          User.lower_employer == search_string, ndb.AND(User.lower_first_name == first_name, User.lower_last_name == last_name))).fetch()
        if search_type is "advanced":
          profession_name = User.query(User.lower_profession == search_string).fetch()
          employer_name = User.query(User.lower_employer == search_string).fetch()
          jobs.extend(profession_name)
          employers.extend(employer_name) 
        if full_name:
          results.extend(full_name)
      else:
        if search_type is "advanced":
          jobs_list = User.query(ndb.OR(User.lower_profession == search_string, User.profession == search_string)).fetch()
          employers_list = User.query(ndb.OR(User.lower_employer == search_string, User.employer == search_string)).fetch()
          jobs.extend(jobs_list)
          employers.extend(employers_list)
          # Get Users with skills
          skill_query = Skill.query(Skill.name == search_string).get()
          if skill_query != None:
            users_with_skills = []
            # TODO limit fetch returns entities
            skilled_users = User.query(User.skills == skill_query.key).fetch()
            skills.extend(skilled_users)
            results.extend(skilled_users)
          forum_query = Forum.query(Forum.name == search_string).get()

        name_list = User.query(ndb.OR(User.username == search_string, User.lower_first_name == search_string, User.lower_last_name == search_string, 
          User.lower_employer == search_string, User.lower_profession == search_string)).fetch()
        results.extend(name_list)
      self.response.out.write(template.render('views/search.html', {'results':results, 'users':name_list, 'employers': employers,
        'jobs': jobs, 'search_string':search_string, 'viewer':user, 'skills':skills, 'forums':forum_query}))
Beispiel #17
0
  def get(self):
    user = self.user_model
    search = cgi.escape(self.request.get('search'))
    #TODO normalize names in User model to ignore case
    search_list = search.split(',')
    results = []
    # For recuiters' advance search #
    jobs = []
    employers = []
    skills = []
    names = []
    forum_query = []
    search_type = " "
    if user.account_type == "Recruiter":
      search_type = "advanced"

    #Search Algorithm
    for search_string in search_list:
      search_string = search_string.strip(' ').lower()
      if "@" in search_string:
        q = User.query(User.email_address == search_string)
        if q:
          results.append(q.get())
      elif " " in search_string:
        person = search_string.split(' ')
        first_name = person[0]
        last_name = person[1]
        full_name = User.query(ndb.OR(User.lower_profession == search_string, 
          User.lower_employer == search_string, ndb.AND(User.lower_first_name == first_name, User.lower_last_name == last_name))).fetch()
        if search_type is "advanced":
          profession_name = User.query(User.lower_profession == search_string).fetch()
          employer_name = User.query(User.lower_employer == search_string).fetch()
          jobs.extend(profession_name)
          employers.extend(employer_name) 
        if full_name:
          results.extend(full_name)
      else:
        if search_type is "advanced":
          jobs_list = User.query(ndb.OR(User.lower_profession == search_string, User.profession == search_string)).fetch()
          employers_list = User.query(ndb.OR(User.lower_employer == search_string, User.employer == search_string)).fetch()
          jobs.extend(jobs_list)
          employers.extend(employers_list)
          # Get Users with skills
          skill_query = Skill.query(Skill.name == search_string).get()
          if skill_query != None:
            users_with_skills = []
            # TODO limit fetch returns entities
            skilled_users = User.query(User.skills == skill_query.key).fetch()
            skills.extend(skilled_users)
            results.extend(skilled_users)
          forum_query = Forum.query(Forum.name == search_string).get()

        name_list = User.query(ndb.OR(User.username == search_string, User.lower_first_name == search_string, User.lower_last_name == search_string, 
          User.lower_employer == search_string, User.lower_profession == search_string)).fetch()
        results.extend(name_list)
      self.response.out.write(template.render('views/search.html', {'results':results, 'users':name_list, 'employers': employers,
        'jobs': jobs, 'search_string':search_string, 'viewer':user, 'skills':skills, 'forums':forum_query}))
Beispiel #18
0
    def get_list(self, *args, **kwargs):
        count, threads = super().get_list(*args, **kwargs)

        for thread in threads:
            thread.forum = Forum.get(thread.forum).title
            thread.section = Section.get(thread.section).title
            thread.author = User.get(thread.author).username

        return count, threads
Beispiel #19
0
 def get(self):
     user = self.user_model_
     url = self.request.url
     if url[-1] == '/':
         self.redirect('/forum')
     forums = Forum.query().order(-Forum.posts)
     self.render_google('forumViewer.html', {
         'viewer': self.user_model_,
         'forums': forums
     })
Beispiel #20
0
 def post(self):
   forum_name = cgi.escape(self.request.get('forum_name'))
   user_key = self.user_model.key
   forum_model = Forum.query(Forum.name == forum_name).get()
   forum_model.subscribers.append(user_key)
   forum_model.put()
   user = self.user_model
   user.subscriptions.append(forum_name)
   user.put()
   self.redirect('/tech/{}'.format(forum_name))   
Beispiel #21
0
def create_forum_submit(request):
    forum = Forum(user=request._user, name="DEFAULT")

    data = ForumForm(request.POST, instance=forum)
    if data.is_valid():
        entity = data.save(commit=False)
        entity.put()
        return HttpResponseRedirect('/')

    return render_to_response('home/create_forum.html', {'forum_form': data})
Beispiel #22
0
class SectionForm(wt.Form):

    title = wt.StringField(validators=(wt.validators.required(), ))
    forum = wt.SelectField(choices=[(forum.id, forum.title)
                                    for forum in Forum.all()],
                           coerce=int)
    # TODO(a.telishev): Section relates from forum
    parent = wt.SelectField(choices=[(section.id, section.title)
                                     for section in Section.all()],
                            coerce=int)
Beispiel #23
0
    def post(self):
        imeforum = self.request.get("fime")
        print imeforum
        priimekforum = self.request.get("fpriimek")
        email = self.request.get("femail")

        sporocilo = self.request.get("fsporocilo")
        #params = {"fime" : imeforum }
        if sporocilo != "Obvezno vpisi kaj notri":
            forum = Forum(fime=imeforum,
                          fpriimek=priimekforum,
                          fsporocilo=sporocilo,
                          femail=email)
            forum.put()
            time.sleep(1)
        fseznam = Forum.query().fetch()
        print fseznam
        params = {"forumseznam": fseznam}
        return self.render_template("redirect.html", params=params)
Beispiel #24
0
    def convert_forums(self):
        start_time = time.time()
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM smf_boards;")
        rows = cursor.fetchall()

        for row in rows:
            forum = Forum()
            category = Category.objects.get(old_category_id=row[1])

            forum.category = category
            forum.old_forum_id = row[0]
            forum.position = row[4]
            forum.name = row[10]
            forum.description = row[11]
            forum.active = True
            forum.save()

        self.calculate_time(start_time, time.time())
Beispiel #25
0
    def get_list(self, *args, **kwargs):
        count, sections = super().get_list(*args, **kwargs)

        for section in sections:
            section.forum = Forum.get(section.forum).title
            parent = Section.get(section.parent)
            if parent:
                section.parent = parent.title
            section.created_by = User.get(section.created_by).username

        return count, sections
Beispiel #26
0
 def get(self):
   user = self.user_model
   url = self.request.url
   if url[-1] == '/':
     self.redirect('/tech')
   forums = Forum.query().order(-Forum.posts)
   if user == None:
     override_base = "visitorBase.html"
   else:
     override_base = "base.html"
   self.response.out.write(template.render('views/forumViewer.html', {'viewer': self.user_model, 'forums':forums, 'override_base':override_base}))
Beispiel #27
0
 def forum(self, request):
     forum_key = ndb.Key(Forum, request.title)
     forum = Forum.get_or_insert(request.title,
                                 key=forum_key,
                                 forum=request.title)
     taskqueue.add(params={
         'title': request.title,
         'loops': request.loops,
         'last_id': request.last_id
     },
                   url='/collect_topics/forum')
     return TaskForm(title=request.title)
Beispiel #28
0
 def get(self, forum_id):
   forum_id = forum_id.lower()
   user = self.user_model
   forum_posts = ForumPost.query(ForumPost.forum_name == forum_id)
   forum = Forum.query(Forum.name == forum_id).get()
   if user == None:
     override_base = "visitorBase.html"
   else:
     override_base = "base.html"
   self.response.out.write(template.render('views/forum.html', {'viewer': user,
                                     'posts': forum_posts, 'forum': forum, 'forum_name': forum_id, 
                                     'override_base': override_base}))
Beispiel #29
0
 def post(self):
     args = self.parser.parse_args()
     if not current_user.is_authenticated:
         return JSON_abort(401, message="You should login first.")
     if not check_title(args["title"]):
         return JSON_abort(400, message="Forbidden symbols")
     editors = ""
     if args["editors"]:
         for nickname in args["editors"].split(", "):
             user = session.query(User).filter(
                 User.nickname == nickname).first()
             if not user:
                 return JSON_abort(
                     400, message=f"Nickname {nickname} not exist.")
             editors += str(user.id) + ","
     forum = Forum()
     forum.title = args["title"]
     forum.private = args["private"]
     forum.editors = editors
     forum.admin_id = current_user.id
     session.add(forum)
     session.commit()
     current_user.follow += str(
         session.query(Forum).order_by(Forum.id.desc()).first().id) + ","
     session.commit()
     return jsonify({'success': 'OK'})
Beispiel #30
0
 def get(self):
     #tole spodaj mi preveri ce je user prijavljen
     paramsif = is_logged_in()
     #spodnje je vse pober
     #fseznam = Forum.query().fetch()
     #v query das notri pogoj
     fseznam = Forum.query(Forum.deleted == False).fetch()
     # SORT order takole zgleda... reverse za najvecjega navzdol
     fseznam = sorted(fseznam, key=lambda dat:dat.nastanek, reverse=True)
     params = {"forumseznam" : fseznam }
     #zdruzi dva dictionarija
     params.update(paramsif)
     return self.render_template("forum.html" , params=params)
Beispiel #31
0
 def get(self):
     #tole spodaj mi preveri ce je user prijavljen
     paramsif = is_logged_in()
     #spodnje je vse pober
     #fseznam = Forum.query().fetch()
     #v query das notri pogoj
     fseznam = Forum.query(Forum.deleted == False).fetch()
     # SORT order takole zgleda... reverse za najvecjega navzdol
     fseznam = sorted(fseznam, key=lambda dat: dat.nastanek, reverse=True)
     params = {"forumseznam": fseznam}
     #zdruzi dva dictionarija
     params.update(paramsif)
     return self.render_template("forum.html", params=params)
Beispiel #32
0
    def convert_forums(self):
        start_time = time.time()
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM smf_boards;")
        rows = cursor.fetchall()

        for row in rows:
            forum = Forum()
            category = Category.objects.get(old_category_id=row[1])

            forum.category              = category
            forum.old_forum_id          = row[0]
            forum.position              = row[4]
            forum.name                  = row[10]
            forum.description           = row[11]
            forum.active                = True
            forum.save()

        self.calculate_time(start_time, time.time())
Beispiel #33
0
def create_thread(id):
    try:
        board = Forum.objects.filter(id=id)
    except Exception as e:
        print " exception value: ", e
        return redirect(url_for('.index'))
    form = CreateThreadForm()
    if form.validate_on_submit():
        t = Helper().build_thread(form, session['username'])
        te = ThreadArrayEl()
        te.key = str(len(board[0].threads) + 1)
        te.thread = t
        try:
            Forum.objects(slug=slug).update_one(push__threads=te)
        except Exception as e:
            print " exception update value: ", e
            return redirect(url_for('.index'))

        return redirect(url_for('.board', slug=slug))

    return render_template('forum/create_thread1.html',
                           board=board[0],
                           form=form)
Beispiel #34
0
 def get(self, forum_id):
     forum_id = forum_id.lower()
     user = self.user_model_
     forum_posts = ForumPost.query(ForumPost.forum_name == forum_id).order(
         ForumPost.time)
     forum = Forum.query(Forum.name == forum_id).get()
     self.render_google(
         'forum.html', {
             'viewer': user,
             'posts': forum_posts,
             'forum': forum,
             'forum_name': forum_id,
             'forum_aty': forum.aty
         })
Beispiel #35
0
 def post(self, sporocilo_id):
     vnosi = self.request.get("ime")
     vnosp = self.request.get("priimek")
     vnose = self.request.get("email")
     vnoss = self.request.get("sporocilo")
     if not vnosi:
         vnosi = "Neznanec"
     vmesnoime = Forum.get_by_id(int(sporocilo_id))
     vmesnoime.fime = vnosi
     vmesnoime.fpriimek = vnosp
     vmesnoime.femail = vnose
     vmesnoime.fsporocilo = vnoss
     vmesnoime.put()
     time.sleep(1)
     self.redirect_to("forum1")
Beispiel #36
0
 def post(self, sporocilo_id):
     vnosi = self.request.get("ime")
     vnosp = self.request.get("priimek")
     vnose = self.request.get("email")
     vnoss = self.request.get("sporocilo")
     if not vnosi:
         vnosi="Neznanec"
     vmesnoime = Forum.get_by_id(int(sporocilo_id))
     vmesnoime.fime = vnosi
     vmesnoime.fpriimek = vnosp
     vmesnoime.femail = vnose
     vmesnoime.fsporocilo = vnoss
     vmesnoime.put()
     time.sleep(1)
     self.redirect_to("forum1")
Beispiel #37
0
def create_thread_submit(request, forumid):
	forum = Forum.get_by_id(int(forumid))
	thread = Thread(forum=forum,user=request._user, content="Default", title="Default")
	data = ThreadForm(request.POST, instance=thread)
	if data.is_valid():
		entity = data.save(commit=False)
		entity.put()
		forum.increment_thread_count()
		forum.set_last_thread(entity)
		return HttpResponseRedirect('/forum/{0}'.format(forum.key().id()))

	return render_to_response('home/create_thread.html',
	{
		'thread_form' : data
	})
Beispiel #38
0
def create_thread_submit(request, forumid):
    forum = Forum.get_by_id(int(forumid))
    thread = Thread(forum=forum,
                    user=request._user,
                    content="Default",
                    title="Default")
    data = ThreadForm(request.POST, instance=thread)
    if data.is_valid():
        entity = data.save(commit=False)
        entity.put()
        forum.increment_thread_count()
        forum.set_last_thread(entity)
        return HttpResponseRedirect('/forum/{0}'.format(forum.key().id()))

    return render_to_response('home/create_thread.html', {'thread_form': data})
def send():
    try:
        req_data = request.get_json()
        u_id = req_data["u_id"]
        title = req_data["title"]
        content = req_data["content"]
    except:
        return jsonify({'status': 400, 'msg': "请求参数错误"})
    else:
        add_text = Forum(u_id=u_id, f_title=title, f_content=content)
        db.session.add(add_text)
        db.session.commit()
        return jsonify({
            "status": 200,
            "msg": "发送帖子成功",
        })
Beispiel #40
0
def module002_new_forum():
    form = ForumForm()
    for course in Course.query.filter(Course.user_id == current_user.id):
        form.course_id.choices += [(course.id, str(course.id) + '-' + course.name + '-' + course.institution_name)]
    if request.method == 'POST':
        if current_user.is_authenticated and form.validate_on_submit():
            forum = Forum(author_id=current_user.id,
                          title=form.title.data,
                          course_id=form.course_id.data)
            db.session.add(forum)
            db.session.commit()
            flash("Successfully created a new forum")
            return redirect(url_for('module002.module002_index'))
        else:
            flash("Couldn't create new forum. Form error: {}".format(form))

    return render_template('module002_new_forum.html', module="module002", form=form)
Beispiel #41
0
    def get_unique_subreddits(self):
        """
        Utility method returns a list of unique Forums aka subreddits 
        in top 100 'hot' Submissions of r/popular.
        """
        unique_subreddits = []
        seen_subreddits = []
        for submission in self.hot_submissions:
            if submission.subreddit not in seen_subreddits:
                # List subreddit as seen
                seen_subreddits.append(submission.subreddit)
                # Translate subreddit into Forum and append to list
                new_forum = Forum(
                    title=submission.subreddit.display_name,
                    description=submission.subreddit.public_description)
                unique_subreddits.append(new_forum)

        # Return list of unique Forums (subreddits)
        return unique_subreddits
Beispiel #42
0
    def index(self):
        counts = {
            'forums': Forum.count(),
            'sections': Section.count(),
            'threads': Thread.count(),
            'labels': ThreadLabel.count(),
            'answers': Answer.count(),
            'users': User.count(),
        }
        for item, count in counts.items():
            counts[item] = '{:,}'.format(counts[item])

        date = datetime.now().strftime('%d.%m.%Y %H:%M')

        return self.render(
            'admin/statistics.html',
            date=date,
            counts=counts,
        )
Beispiel #43
0
    def post(self):
        """
		Creates forum
		"""
        data = request.json
        name = data.get('name')
        author_id = data.get('author_id')
        author_name = data.get('author_name')
        description = data.get('description')
        if (name == "" or author_id == "") or description == "":
            return {'error': 'Missing arguments'}, 400
        if db.session.query(Forum).filter(Forum.name == name).first():
            return {'error': 'Forum name already exist'}, 400
        new_forum = Forum(name=name,
                          author_name=author_name,
                          author_id=int(author_id),
                          description=description)
        db.session.add(new_forum)
        db.session.commit()

        return 201
Beispiel #44
0
def create_forum():
    form = ForumForm()
    if form.validate_on_submit():
        if not check_title(form.title.data):
            return render_template(
                'create_forum.html',
                title='Создать форум',
                form=form,
                message=f"Название содержит недопустимые символы.")
        editors = ""
        if form.editors.data:
            for nickname in form.editors.data.split(", "):
                user = session.query(User).filter(
                    User.nickname == nickname).first()
                if not user:
                    return render_template(
                        'create_forum.html',
                        title='Создать форум',
                        form=form,
                        message=
                        f"Пользователя с ником {nickname} не существует.")
                editors += str(user.id) + ","
        forum = Forum()
        forum.title = form.title.data
        forum.private = form.private.data
        forum.editors = editors
        forum.admin_id = current_user.id
        session.add(forum)
        session.commit()
        current_user.follow += str(
            session.query(Forum).order_by(Forum.id.desc()).first().id) + ","
        session.commit()
        return redirect('/forums')
    return render_template('create_forum.html',
                           title='Создать форум',
                           form=form,
                           message="")
Beispiel #45
0
	def __init__(self, category):
		self.forums = []
		forums = Forum.all().filter('category =',category).order('-datetime').fetch(10, offset=0)
		for forum in forums:
			self.forums.append(ForumViewModel(forum))
Beispiel #46
0
 def get(self, forum_id):
     sporocilo = Forum.get_by_id(int(forum_id))
     paramsif = is_logged_in()
     params = {"forum": sporocilo}
     params.update(paramsif)
     self.render_template("posamezen-forum.html", params=params)
Beispiel #47
0
if not admin:
    admin = User.create(
        username=settings.ADMIN_USERNAME,
        email=settings.ADMIN_EMAIL,
        password=settings.ADMIN_PASSWORD,
    )

current_dir = os.path.dirname(os.path.abspath(__file__))
forums_data_path = os.path.join(current_dir, 'forum.json')

with open(forums_data_path) as forums_data:
    forums = json.load(forums_data)['forums']

print('Create forums and sections...')
for fdata in forums:
    is_forum_exist = len(Forum.filter(title=fdata['title']))
    if is_forum_exist:
        print(f' - Skip initialization for forum `{fdata["title"]}`')
        continue

    forum = Forum.create(
        **{
            'title': fdata['title'],
            'created_at': datetime.datetime.now(),
            'created_by': admin.id,
        })

    for section_data in fdata['sections']:
        section = Section.create(
            **{
                'forum': forum.id,
Beispiel #48
0
def section_view(section_id):
    section = Section.get(section_id)
    forum = Forum.get(section.forum)
    parent_section = Section.get(section.parent)
    subsections = Section.filter(parent=section.id)

    # Threads
    try:
        page = int(request.args.get('page'))
    except (TypeError, ValueError):
        page = 1

    if not page or page < 1:
        page = 1

    threads_count = len(Thread.filter(section=section.id))
    # FIXME(a.telishev): Threads per page by search
    pages_count = threads_count // THREADS_PER_PAGE

    if page > pages_count:
        page = pages_count

    prev_page = page - 1
    next_page = page + 1
    if page == 1:
        prev_page = None
    if page == pages_count:
        next_page = None

    offset = (page - 1) * THREADS_PER_PAGE

    search = request.args.get('search', '')
    search_condition = f'AND thread.title LIKE "%{search}%"' if search else ''
    query = f"""
        SELECT
            thread.id thread_id,
            thread.title thread_title,
            thread.created_at thread_created_at,
            thread.last_answer_time thread_last_answer_time,
            user.id user_id,
            user.username username
        FROM thread
        INNER JOIN user ON thread.author = user.id
        WHERE section = %(section_id)s {search_condition}
        ORDER BY thread.last_answer_time DESC
        LIMIT %(limit)s
        OFFSET %(offset)s;
    """
    cursor = get_connector().cursor()
    cursor.execute(query, {
        'section_id': section.id,
        'limit': THREADS_PER_PAGE,
        'offset': offset,
    })
    threads = {
        thread_id: {
            'id':
            thread_id,
            'title':
            thread_title,
            'created_at':
            thread_created_at.strftime('%d %b %Y'),
            'created_at_h':
            thread_created_at.strftime('%d %b %Y\n%H:%M:%S'),
            'last_answer_time':
            (thread_last_answer_time.strftime('%d %b %Y\n%H:%M:%S')
             if thread_last_answer_time else None),
            'user_id':
            user_id,
            'username':
            username,
        }
        for (
            thread_id,
            thread_title,
            thread_created_at,
            thread_last_answer_time,
            user_id,
            username,
        ) in cursor
    }

    if threads:
        answers_count_query = f"""
            SELECT
                thread.id,
                COUNT(*)
            FROM thread INNER JOIN answer on thread.id = answer.thread
            WHERE thread.id IN ({
                ', '.join(str(thread_id) for thread_id in threads)
            })
            GROUP BY thread.id;
        """
        cursor.execute(answers_count_query)
        for thread_id, answers_count in cursor:
            threads[thread_id]['answers_count'] = answers_count

    cursor.close()

    return render_template(
        'section.html',
        section=section,
        forum=forum,
        parent_section=parent_section,
        subsections=subsections,
        threads=threads.values(),
        search=search,
        next_page=next_page,
        curr_page=page,
        prev_page=prev_page,
    )