예제 #1
0
    def post(self):
        if not self.user:
            self.redirect('/login')
            return

        postbutton = self.request.get("postbutton")

        if postbutton == "submit":
            subject = self.request.get('subject')
            content = self.request.get('content')

            if subject and content:
                p = Post(parent=blog_key(),
                         subject=subject,
                         content=content,
                         postuser=self.user)
                p.put()
                self.redirect('/blog/%s' % str(p.key().id()))
                return
            else:
                error = "You must enter the subject and the content for the post."
                self.render("newpost.html",
                            subject=subject,
                            content=content,
                            error=error)
        if postbutton == "cancel":
            self.redirect('/')
예제 #2
0
def get_posts() -> Any:
    args = parse_args(Config.ARGS, request.args)
    valid, message = validate_args(Config.ARGS, args)
    if not valid:
        return make_response(jsonify({"error": message}), 400)

    if args["update"] == "sync":
        logger.info("sync update requested")
        Post.fetch_all(Config)
        logger.info("sync update done")
    if args["update"] == "async":
        logger.info("async update requested")
        redis_conn = Redis(host=Config.REDIS_HOST,
                           port=Config.REDIS_PORT,
                           db=Config.REDIS_DB)
        q = Queue(connection=redis_conn)  # no args implies the default queue
        job = q.enqueue(Post.fetch_all, Config)
        logger.info(f"job for async update issued, job id: {job.id}")
        return make_response(
            jsonify({"message": f"update requested, job id: {job.id}"}), 200)

    query = Post.query_posts(
        sort=args["sort"],
        order=args["order"],
        limit=args["limit"],
        offset=args["offset"],
    )

    return make_response(jsonify([p.to_dict() for p in query]), 200)
예제 #3
0
def remove_post(id):
  if not g.db.doc_exist(id):
    abort(404)
  Post.get(id).delete()

  flash('Post was successfully removed')
  return redirect(url_for('show_posts'))
예제 #4
0
def createPost():
    nTitle = request.forms.get('title')
    nBody = request.forms.get('body')
    nDateTime = datetime.datetime.now()

    author = User.get(User.firstname == 'alibi')
    post = Post(title=nTitle,
                body=nBody,
                published_date=nDateTime,
                user=author)
    post.save()
    return template('blog', posts=Post.select())
예제 #5
0
파일: submitpost.py 프로젝트: mattkuo/cs253
    def post(self):
        subject = self.request.get("subject")
        content = self.request.get("content")

        if subject and content:
            post_db = Post(subject = subject, content = content)
            post_db.put()

            post_url = str(post_db.key().id())
            self.redirect("/unit6/blog/%s" % post_url)
        else:
            self.render(subject = subject, content = content,
                error = "Please make sure both fields are submitted correctly")
예제 #6
0
def addPost():
    url = 'editpost.html'
    user = getUserByEmail(login_session['email'])
    if user:
        # POST method add category
        if request.method == 'POST':
            # check if title and content exists
            title = request.form.get('title', None)
            content = request.form.get('post_content', None)
            picture = request.form['picture']
            description = request.form['description']
            if title and content:
                post = Post(
                    title=title,
                    user_id=user.id,
                    picture=picture,
                    description=description,
                    post_content=content,
                    date_added=datetime.datetime.now(),
                )
                session.add(post)
                session.commit()
                keywords = request.form['keywords'].split(',')
                try:
                    for k in keywords:
                        if k:
                            k = Keyword(post_id=post.id, word=k)
                            session.add(k)
                            session.commit()
                except Exception as e:
                    print e
                    flash(create_alert('Error in saving keywords', 'danger'))
                return redirect(url_for('showPost', post_id=post.id))
            else:
                # title or content is empty
                if request.form['origin'] == 'html':
                    # html edit status
                    url = 'editpost_html.html'
                flash(
                    create_alert('Title and Content must not be empty',
                                 'danger'))
                return render_template(url, user_logged=user, post=None)

        # GET method shows add page
        if request.args.get('mode'):
            url = 'editpost_html.html'
        post = Post(title='', description='', post_content='', picture='')
        return render_template(url, post=post, edit=False, user_logged=user)
    else:
        return redirect(url_for('login'))
예제 #7
0
def create():
    ''' Creates a new article '''
    if request.method == 'POST':
        if request.form['title'] != '' and request.form['body'] != '' and request.form['picture'] != '.gitignore':
            # create the new article here :)
            if request.form['topic'] == '_newTopic':
                art = Post(topic = request.form['newTopic'],title=request.form['title'],picture='/static/' + request.form['picture'],body=request.form['body'])
            else:
                art = Post(topic = request.form['topic'],title=request.form['title'],picture='/static/' + request.form['picture'],body=request.form['body'])
            db.session.add(art)
            db.session.commit()
            flash('successfully created new article',category='info')
        else:
            flash('error, missing required portion, or using invalid Image',category='error')
    return render_template('addArticle.html')
예제 #8
0
 def get(self, uid):
     user = User.by_id(int(uid))
     # posts = db.GqlQuery("SELECT * FROM User WHERE postuser = :1 ORDER BY desc", user)
     posts = Post.all().filter('postuser ='******'-created')
     # This will display the posts created by the user or a black page if
     # there are no posts
     self.render('front.html', posts=posts)
예제 #9
0
def fetch_x_days(sub, sub_id, last=None):
    param = {"before": f"t3_{base36.dumps(last)}"} if last is not None else {}
    i = 0

    for s in reddit.subreddit(sub).new(limit=1000, params=param):
        author = getattr(s, "author", {})

        try:
            p = Post(title=s.title,
                     user_id=int(getattr(author, "id", "-1"), 36),
                     username=getattr(author, "name", ""),
                     link=s.url,
                     num_comments=s.num_comments,
                     score=s.score,
                     r_id=int(s.id, 36),
                     date=date.fromtimestamp(
                         s.created_utc).strftime("%Y-%m-%d"),
                     updated=int(time() * 1000),
                     sub_id=sub_id)
        except Exception as e:
            print(f"oopsie\n{e}")
            continue

        session.add(p)

        if i % 100 == 0:
            session.commit()
예제 #10
0
def postmessage():
    if redirect_is_not_logged(session) != True:
        return redirect_is_not_logged(session)
    new_post = {}

    if 'username' in session:
        if request.method == 'POST':
            message = request.form.get('message', None)
            title = request.form.get('title', None)
            redirection = request.form.get('redirection', None)
            if title:

                post = Post(title=title,
                            message=message,
                            user_id=session['id'],
                            created=datetime.datetime.now())
                db.session.add(post)
                db.session.commit()

            if redirection is not None:
                user = db.session.execute(
                    'SELECT user.* FROM user WHERE user.username = :username',
                    {
                        'username': redirection
                    }).first()
                print(redirection)
                if user is not None:

                    return redirect(url_for('profile', username=user.username))
            # new_post['title'] = title
            # new_post['message'] = message

            # return render_template('index.html', page_name="Home", new_post=new_post , session=session)
    return redirect(url_for('index'))
예제 #11
0
파일: newpost.py 프로젝트: mattkuo/cs253
    def get(self, post_id):
        post_lookup = Post.get_by_id(int(post_id))

        if post_lookup:
            self.render(post_lookup=post_lookup)

        else:
            self.write("Sorry, Page could not be found. Please try again.")
예제 #12
0
파일: newpost.py 프로젝트: mattkuo/cs253
    def get(self, post_id):
        post_lookup = Post.get_by_id(int(post_id))

        if post_lookup:
            queried = last_queried(post_id)
            self.render(post_lookup=post_lookup, last_queried = queried)

        else:
            self.write("Sorry, Post could not be found. Please try again.")
예제 #13
0
    def get(self):

        posts = Post.all().order('-created')

        if self.user:
            self.render('front.html', posts=posts, heading_text="")
        else:
            self.redirect('/login')
            return
예제 #14
0
def like_post(id):
  if not g.db.doc_exist(id):
    abort(404)
  post = Post.get(id)
  uid = session.get('uid')
  if uid not in post.likes:
    post.likes.add(uid)
  else:
    post.likes.remove(uid)
  post.save()
  return 'OK', 200, {'Content-Type': 'text/plain'}
예제 #15
0
def about():
    form = Publish()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Post has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('about.html', form=form, legend='New Post')
예제 #16
0
def get_posts(update=False):
    q = Post.query().order(-Post.created)
    q = q.fetch(10, use_cache=False, use_memcache=False)
    mc_key = 'BLOGS'

    posts, age = age_get(mc_key)
    if update or posts is None:
        posts = list(q)
        age_set(mc_key, posts)

    return posts, age
예제 #17
0
def show_posts():
  form = PostForm(request.form)
  posts = list(Post.view('posts/by_date'))[::-1]
  errors = []
  if request.method == 'POST' and form.validate():
    new_post = make_post_from_request(request)
    g.db.save_doc(new_post)
    flash('New post was successfully created')
    return redirect(url_for('show_posts'))

  errors.extend(format_form_errors(form.errors.items()))
  return render_template \
    ('main.html', form = form, posts = posts, submit = 'Share', errors = errors)
예제 #18
0
 def query(self, id):
     try:
         item = db.session.query(Item).get(id)
         post = db.session.query(Post).get(item.post_id)
         if post is None:
             post = Post(**config.POST_TEMPLATE)
         return {
             "name": item.name,
             "post": post,
             "display": item.display
         }
     except:
         db.session.rollback()
         return None
예제 #19
0
def star_post(id):
  if not g.db.doc_exist(id):
    abort(404)
  post = Post.get(id)
  uid = session.get('uid')
  user = User.get(uid)
  if uid not in post.stars:
    post.stars.add(uid)
    user.starred.add(post._id)
  else:
    post.stars.remove(uid)
    user.starred.remove(post._id)
  post.save()
  user.save()
  return 'OK', 200, {'Content-Type': 'text/plain'}
예제 #20
0
    def get(self):
        posts, age = utils.get_posts()

        if self.request.url.endswith('.json'):
            self.response.headers['Content-Type'] = ('application/json; '
                                                     'charset=UTF-8')
            allPosts = [{'content': p.content,
                         'created': p.created.strftime('%c'),
                         'subject': p.subject}
                        for p in Post.query().order(-Post.created)]
            self.response.write(json.dumps(allPosts))
        else:
            self.render('/templates/blogfront.html',
                        posts=posts,
                        age=utils.age_str(age))
예제 #21
0
 def add(self, title, description, usage, complexity, code, note):
     try:
         post = Post(title=title,
                     description=description,
                     usage=usage,
                     complexity=complexity,
                     code=code,
                     note=note,
                     author=current_user.name)
         db.session.add(post)
         db.session.commit()
         return True
     except:
         db.session.rollback()
         return False
예제 #22
0
def newPosts():
    if 'username' not in login_session:
        return redirect('/login')
    if 'username' in login_session:
        if request.method == 'POST':
            newpost = Post(name=request.form['name'],
                           user_id=login_session['user_id'],
                           post_type=request.form['post_type'],
                           description=request.form['description'],
                           image=request.form['image'],
                           ratings=request.form['ratings'])
            session.add(newpost)
            flash("New Post Created Successfully")
            session.commit()
            return redirect(url_for('showPosts'))
        else:
            return render_template('newPost.html')
예제 #23
0
 def apply(self, id, title, description, usage, complexity, code, note):
     try:
         post = Post(title=title,
                     description=description,
                     usage=usage,
                     complexity=complexity,
                     code=code,
                     note=note,
                     author=current_user.name)
         db.session.add(post)
         db.session.flush()
         item = db.session.query(Item).get(id)
         item.post_id = post.id
         db.session.commit()
         return True
     except:
         db.session.rollback()
         return False
예제 #24
0
파일: pipeline.py 프로젝트: smg7d/canary
def addNewPosts(subredditName, session):

    subreddit = reddit.subreddit(subredditName)

    newPosts = []
    existingPosts = [pId for pId, in session.query(Post.postId)]

    for submission in subreddit.new(limit=100):
        if submission.id not in existingPosts:
            post = Post(postId=submission.id,
                        title=submission.title,
                        subreddit=submission.subreddit.display_name,
                        created=int(submission.created_utc),
                        author=submission.author.name)
            newPosts.append(post)

    session.add_all(newPosts)
    session.commit()
    logging.info(f"{subredditName}: added {len(newPosts)} new posts")
    def new_post(self):
        post = Post()
        txt = input()
        self.__posts = self.__data.get_posts()

        # checks if posts.txt is empty (ternary doesn't work)
        if self.__posts == []:
            temp = str()
        else:
            temp = self.__posts[-1]

        post.set_crt(self.__cur_user.get_id())

        # to avoid 'index out of range' error (ternary doesn't work)
        if isinstance(temp, str):
            id = 0
        else:
            id = temp.get_id()

        post.set_id(id + 1)
        post.set_txt(txt)
        self.__data.push_post(post)
예제 #26
0
def addpost():
    if request.method == 'GET':
        return render_template('addpost.html')
    else:
        post_title = request.form.get('title')
        post_continent = request.form.get('continent')
        post_country = request.form.get('country')
        post_city = request.form.get('city')
        if post_city != "":
            post_country += ","
        post_text = request.form.get('textish')
        post_pic_url = request.form.get('pic_url')
        thepost = Post(title=post_title,
                       continent=post_continent,
                       country=post_country,
                       city=post_city,
                       text=post_text,
                       img_url=post_pic_url)
        session.add(thepost)
        session.commit()
        return redirect(url_for('feed'))
예제 #27
0
    def get(self, post_id):
        post_key = 'POST_' + post_id

        post, age = utils.age_get(post_key)
        if not post:
            post = Post.get_by_id(long(post_id))
            if not post:
                self.response.write('This page doesn\'t exist!')
            utils.age_set(post_key, post)
            age = 0

        if self.request.url.endswith('.json'):
            self.response.headers['Content-Type'] = ('application/json; '
                                                     'charset=UTF-8')
            p = {'content': post.content,
                 'created': post.created.strftime('%c'),
                 'subject': post.subject}
            self.response.write(json.dumps(p))
        else:
            self.render('/templates/permanent.html',
                        post=post,
                        age=utils.age_str(age))
예제 #28
0
def edit_post(id):
  if not g.db.doc_exist(id):
    abort(404)

  form = PostForm(request.form)
  post = Post.get(id)
  errors = []

  if request.method == 'POST' and form.validate():
    post.title = form.title.data
    post.text = form.text.data
    post.tags = set(form.tags.data.split())
    post.save()
    flash('Post was successfully updated')
    return redirect(url_for('show_posts'))
  elif request.method == 'POST' and not form.validate():
    errors.extend(format_form_errors(form.errors.items()))
  elif request.method == 'GET':
    form.title.data = post.title
    form.text.data = post.text
    form.tags.data = ' '.join(post.tags)

  return render_template \
    ('edit_post.html', id = id, form = form, submit = 'Update', errors = errors)
예제 #29
0
def before_request():
  g.db = connect_db(app.config['DB'])

  User.set_db(g.db)
  Post.set_db(g.db)
예제 #30
0
 def process_post(data):
     nonlocal req
     user = get_current_user(req)
     with db:
         Post.create(user=user, content=data['content'])
     return
예제 #31
0
async def home_screen(req, resp):
    user = get_current_user(req)
    friends = get_friends(user)
    posts = Post.select().where(Post.user << [user, *friends]).order_by(
        Post.date.desc())
    resp.content = api.template('home.html', user=user, posts=posts)
예제 #32
0
def show_posts_tag(tag):
  posts = list(Post.view('posts/by_tag', key=tag))
  return render_template('posts.html', posts = posts)
예제 #33
0
def show_posts_starred():
  # I think it's not a good idea to use such implementation.
  user = User.get(session.get('uid'))
  posts = [elem for elem in Post.view('posts/by_date') if elem._id in user.starred]
  return render_template('posts.html', posts = posts)
예제 #34
0
from database import db, User,Post,Comment,Anon,Target
from werkzeug.security import generate_password_hash, check_password_hash
from app import ap
#from database import db

db.init_app(ap)
with ap.app_context():
    db.create_all()
    #two example users
    b = User(name='test',password='******',email='[email protected]')
    a = User(name='ethan',password='******',email='a',permission=999)
    # add and save the users
    db.session.add(a)
    db.session.add(b)
    db.session.commit()
    #example of an article
    p1 = Post(topic='misc',title='Example Article',picture='/static/Pic.jpg',body='This is the body of the article, which accepts <i> HTML tags </i>')
    p2 = Post(topic='misc',title='Ex2',picture='/static/Pic.jpg',body='some random placeholder text here please')
    p3 = Post(topic='a new topic appears',title='Example Article',picture='/static/Pic.jpg',body='I yote a duck off a cliff... turns out they can fly, so everything was fine')

    db.session.add(p1)
    db.session.add(p2)
    db.session.add(p3)
    db.session.commit()
    #c = Comment(title='test',message='I love testing',poster='testman',article=1)
    #db.session.add(c)
    db.session.commit()
    quit()
예제 #35
0
def blog_view():
    return template('blog', posts=Post.select())