Ejemplo n.º 1
0
def user(username):
    u = User()
    user = u.get_user(username=username)

    title = request.form.get('new-title')
    body = request.form.get('new-body')

    if title and body:
        p = Post(title=title, body=body, user_id=user.id)
        p.add_post()

    posts = u.get_posts_by_user(user.id)

    if not posts:
        posts = [
            Post(id=2,
                 title="There's nothing here yet!",
                 body="There's nothing here yet!",
                 user_id=-1)
        ]

    if user:
        return render_template('user_page.html',
                               username=user.username,
                               posts=posts)

    return "user not found"  # TODO change the custom 404
Ejemplo n.º 2
0
    def post(self, gid):
        body = request.get_json()
        user = request.authorization  # this gives dict
        uid = User.objects.get(username=user['username'])  # this gives user object
        user_id = str(uid.id)  # this gives the user id in string format
        group = Group.objects.get(id=gid)
        if user_id in group.role_dict:
            post = Post(**body, group_id=ObjectId(gid))
            post.date_created = datetime.now()
            post.save()
            # group id is a reference field and rf only takes object id.
            # convert object id to string with str when required
            post_id = post.id
            recipients = []
            # update last active status for user
            temp_dict = group.last_active_dict
            temp_dict[user_id] = datetime.now()
            group.update(set__last_active_dict=temp_dict)

            for x in group.role_dict:
                if group.role_dict[x] == A or group.role_dict[x] == MD:
                    u = User.objects.get(id=x)
                    if u:
                        recipients.append(u.email)

            if group.role_dict[user_id] == M:
                content = "{name} wants to put a post, please accept his request!".format(name=user.username)
                queue.enqueue(printhello())  # this is just a check that q works
                queue.enqueue(send_mail, recipients, content)

            return {'post_id': str(post_id)}, 200
        else:
            return "You ain't a member of this group", 500
Ejemplo n.º 3
0
def newpost():
    # Init form
    form = NewpostForm()

    # If POST
    if request.method == 'POST':

        # Init user from poster
        session_user = User.query.filter_by(
            username=session['username']).first()

        # Init content from form request
        content = request.form['content']

        # Create in DB
        new_post = Post(author=session_user.uid,
                        content=content,
                        createdAt=datetime.now())
        Db.session.add(new_post)
        Db.session.commit()

        return redirect(url_for('index'))

    # If GET
    else:
        return render_template('newpost.html', title='Newpost', form=form)
Ejemplo n.º 4
0
def save_post():
    post_data = json.loads(request.data)
    url = post_data["url"]
    json_data = make_readable(url)

    title = post_data["title"]
    slug = userutils.make_slug(title)
    author = User.objects(username=current_user.username).first()

    p = Post(title=title, slug=slug)
    p.saved_date = datetime.now()
    p.thumbnail = post_data["thumbnail"]
    p.url = url
    p.author = author
    p.content = json_data["content"]
    p.excerpt = json_data["excerpt"]
    p.domain = post_data["domain"]
    p.save()

    q.enqueue(insert_new_relation, p)

    author.posts.append(p)
    author.save()

    return "ok"
Ejemplo n.º 5
0
def index():
    if request.method == 'GET':
        if "user_name" in session:
            name = session["user_name"]
            posts = Post.query.order_by(Post.due, Post.title).all()
            all_user = User.query.order_by(User.user_name).all()
            title_name = 'index'

            return render_template("index.html",
                                   name=name,
                                   posts=posts,
                                   all_user=all_user,
                                   today=date.today(),
                                   title_name=title_name)
        else:
            return redirect(url_for("top", status="logout"))
    else:
        title = request.form.get('title')
        detail = request.form.get('detail')
        due = request.form.get('due')
        due = datetime.strptime(due, '%Y-%m-%d')
        user_name = session['user_name']
        new_post = Post(title=title,
                        detail=detail,
                        due=due,
                        user_name=user_name)
        db_session.add(new_post)
        db_session.commit()
        db_session.close()
        return redirect('/index')
Ejemplo n.º 6
0
def add_fake(numbers):
    if numbers is not None:
        try:
            for _ in range(int(numbers)):
                new_post = Post(title=fake.name(), content=fake.text())
                db.session.add(new_post)
                db.session.commit()

            response = {
                'success': True,
                'message': '%s Fakes created' % numbers
            }

        except ValueError:
            response = {
                'success': False,
                'message': 'Please submit a number',
            }

    else:
        response = {
            'success': False,
            'message': "Numbers is not define, please add has url parameter"
        }

    return jsonify(response)
Ejemplo n.º 7
0
def newpost():
    # Init form
    form = NewpostForm()

    # If POST
    if request.method == "POST":

        # Init user from poster
        session_user = User.query.filter_by(
            username=session["username"]).first()

        # Init content from form request
        content = request.form["content"]

        # Create in DB
        new_post = Post(author=session_user.uid,
                        content=content,
                        created_at=datetime.now())
        Db.session.add(new_post)
        Db.session.commit()

        flash("You successfully created a post")
        return redirect(url_for("index"))

    # If GET
    else:
        return render_template("newpost.html", title="Newpost", form=form)
Ejemplo n.º 8
0
def new_post():
    form = PostForm()
    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('Your post has been created', 'success')
        return redirect(url_for('main.home'))
    return render_template('create_post.html', form=form)
Ejemplo n.º 9
0
    def post(self):
        csrf_value = self.request.get('csrf-token')

        if not memcache.get(csrf_value):
            return self.write('CSRF attack detected!!')

        title = cgi.escape(self.request.get('title'))
        content = cgi.escape(self.request.get('text'))
        user = users.get_current_user()
        email = user.email()
        new_post = Post(title=title, content=content, user_email=email)

        new_post.put()
        return self.redirect_to('post', post_id=new_post.key.id())
Ejemplo n.º 10
0
    def post(self):
        subject = self.request.get("subject")
        content = self.request.get("content")

        if subject and content:
            post = Post(subject=subject, content=content)
            post.put()
            post_id = str(post.key().id())
            self.redirect('/post/%s' % post_id)
        else:
            error = "both subject and content are required"
            self.render("newpost.html",
                        subject=subject,
                        content=content,
                        error=error)
Ejemplo n.º 11
0
def add_post_comment():
    groups = Group.objects
    for group in groups:
        temp_dict = group.last_active_dict
        for user_id in group.role_dict.keys():
            temp_dict[user_id] = datetime.now()
            name = ''.join([
                random.choice(string.ascii_letters + string.digits)
                for k in range(9)
            ])
            content1 = "post is {name}".format(name=name)
            post = Post(user_id=ObjectId(user_id),
                        group_id=ObjectId(group.id),
                        content=content1).save()
            content2 = "comment is {name}".format(name=name)
            Comment(user_id=ObjectId(user_id),
                    post_id=post.id,
                    content=content2).save()
        group.update(set__last_active_dict=temp_dict)
Ejemplo n.º 12
0
Archivo: main.py Proyecto: sup/fill
def create_post(id=None):
    """Create a Post"""
    # Hacky redirect - refactor in the future
    username = request.cookies.get('username')
    cookie_user = User.get_user(username)
    if request.method == "GET":
        return redirect('timeline/' + str(cookie_user.key.id()))
    if not id:
        return redirect('timeline/' + str(cookie_user.key.id()))
    else:
        user = User.get_user_by_id(id)
    if user == cookie_user and request.method == "POST":
        title = request.form.get("title")
        body = request.form.get("body")
        # Create a Post
        post = Post(title=title, body=body, writer=user.key)
        post.put()
        return redirect('timeline/' + str(cookie_user.key.id()))
    else:
        return redirect('timeline/' + str(cookie_user.key.id()))
Ejemplo n.º 13
0
    def post(self):
        if not self.user:
            self.redirect('/login')

        subject = self.request.get('subject')
        content = self.request.get('content')

        if subject and content:
            post = Post(parent=blog_key(),
                        subject=subject,
                        content=content,
                        author=self.user.key)
            post.put()
            self.redirect('/blog/%s' % str(post.key.id()))
        else:
            error = 'Both subject and content must be filled in!'
            self.render('newpost.html',
                        subject=subject,
                        conetent=content,
                        error=error)
Ejemplo n.º 14
0
def save_post_pdf():
    post_data = request.form
    title = post_data.get("title")
    slug = userutils.make_slug(title)
    author = User.objects(username=current_user.username).first()

    print post_data.get("domain")

    if not title:
        return "please provide a title"

    p = Post(title=title, slug=slug)
    p.saved_date = datetime.now()
    p.thumbnail = post_data.get("thumbnail")
    p.url = post_data.get("url")
    p.author = author
    p.content = ""
    p.excerpt = ""
    p.post_type = "pdf"
    p.domain = post_data.get("domain")
    p.save()
    return redirect('/user/profile')
Ejemplo n.º 15
0
def create_database():
    for nick_name in NICK_NAMES:
        author = Author()
        author.nick_name = nick_name
        author.first_name = choice(NAMES)
        author.last_name = f'{choice(NAMES)}ченко'
        author.posts = 0
        author.save()

    for post_text in POSTS:
        post_words = post_text.split(' ')
        post_words = list(filter(None, post_words))
        post_tags = [word for word in post_words if word[0] == '#']
        tags_ids = []
        for tag_text in post_tags:
            try:
                tag = Tag.objects(tag=tag_text.lower())[0]
            except IndexError:
                tag = Tag()
                tag.tag = tag_text.lower()
                tag.save()
            tags_ids.append(tag.id)

        print(tags_ids)
        post = Post()
        post.name = f'{post_words[0]}_{post_words[1]}'
        post.content = post_text

        author = Author.objects(nick_name=choice(NICK_NAMES))[0]
        author.posts += 1
        author.save()

        post.author = author.id
        post.datetime = datetime.now()
        post.views = 0
        post.tag = tags_ids
        post.save()
Ejemplo n.º 16
0
from models.models import Tag, Author, Post
from random import choice

tag = []
author = []

for i in range(1, 6):
    tag_ex = Tag(**{'title': f'#tag{i}'}).save()
    tag.append(tag_ex)

for i in range(1, 3):
    author_ex = Author(**{
        'first_name': f'First Name {i}',
        'last_name': f'Last Name {i}'
    }).save()
    author.append(author_ex)

for i in range(1, 11):
    post_ex = {
        'title': f'title by post number {i}',
        'content': f'content by post number {i}',
        'author': choice(author),
        'tag': [choice(tag), choice(tag)]
    }
    Post(**post_ex).save()
Ejemplo n.º 17
0
def upload():
    try:
        # 投稿のpostリクエストが来たらS3に画像を保存し、
        # データベースへの追記、更新を行う。
        user_id = get_user_id()
        # user_id=1
        dt_now = datetime.datetime.now()
        payload = request.json
        # アップロードファイルを取得
        image = payload.get('image')
        with urlopen(image) as response:
            data = response.read()
        uploaded_file = data
        file_name = dt_now.strftime('%Y-%m-%d-%H:%M:%S')
        # S3アップロード処理
        # アップロード先URL{https://s3-ap-northeast-1.amazonaws.com/rakuten.intern2020/img/{user_id}/{file_name}}
        s3 = boto3.resource('s3')
        response = s3.Bucket('rakuten.intern2020').put_object(
            Key="img/{}/{}".format(user_id, file_name),
            Body=uploaded_file,
            ContentType="image/jpeg")
        # URL生成
        image_url = "https://s3-ap-northeast-1.amazonaws.com/rakuten.intern2020/img/{}/{}".format(
            user_id, file_name)
        # データベースへ追記する為に必要なものを取ってくる
        # 料理名
        meal_name = []
        for i in range(1, 6):
            if payload.get('meal_name{}'.format(i)) != '':
                meal_name.append(payload.get('meal_name{}'.format(i)))
            else:
                break
        recipe_url = payload.get('meal_url')
        post_comment = payload.get('post_comment')

        # 日付、日時を取ってくるget_date,created_at
        get_date = dt_now.strftime('%Y-%m-%d')
        # ボーナス料理名を取ってくる
        created_at = dt_now.strftime('%Y-%m-%d %H:%M:%S')
        date = int(dt_now.strftime('%d'))
        bonus_id = date % 15 + 1
        bonus_name = MealContent.query.filter(
            MealContent.meal_id == bonus_id).all()[0].name
        # meal_nameの情報を元にデータベースからmeal_idとmeal_pointを取ってくる
        meal_id, meal_point = [], []
        print(meal_name)
        for meal in meal_name:
            if meal == bonus_name:
                meal_point.append(
                    MealContent.query.filter(
                        MealContent.name == meal).all()[0].point * 2)
            else:
                meal_point.append(
                    MealContent.query.filter(
                        MealContent.name == meal).all()[0].point)
            meal_id.append(
                MealContent.query.filter(
                    MealContent.name == meal).all()[0].meal_id)
        meal_num = len(meal_id)
        for i in range(5 - meal_num):
            meal_id.append(None)
        # PointUserに送る為にpointの合計を計算する
        total_points = sum(meal_point)
        # postにuser_id,meal_id{1,2,3,4,5},image_url,post_comment,recipe_url追記
        print(meal_id)
        add_data(
            Post(user_id, meal_id[0], meal_id[1], meal_id[2], meal_id[3],
                 meal_id[4], image_url, recipe_url, post_comment, created_at))
        # postidを取ってくる
        post_id = MealContent.query.all()[-1].meal_id
        # CookHistoryにmeal_id,user_id,post_id追記
        for i in range(meal_num):
            add_data(CookHistory(meal_id[i], user_id, post_id))
        # userテーブルから現在のポイントを取ってくる+ポイントの上書き
        user = User.query.filter(User.user_id == user_id).first()
        user.total_points += total_points
        db_session.commit()

        # PointUserにuser_id,point,get_date追記
        add_data(PointUser(user_id, total_points, get_date))

        # push users' graph

        def push_graph():
            point_list = PointUser.query.filter(
                PointUser.user_id == user_id).all()
            graph_dic = {}
            # 同じ日に獲得したポイントは加算
            for p in point_list:
                graph_dic[p.get_date] = 0
            for p in point_list:
                graph_dic[p.get_date] += p.point

            # グラフ定義
            graph_list = list(graph_dic.values())
            for i in range(len(graph_list) - 1):
                graph_list[i + 1] += graph_list[i]
            xs = list(graph_dic.keys())
            # グラフ描画
            y_one = np.ones(len(xs))
            d_l = 200
            fig = go.Figure()
            fig.add_trace(
                go.Scatter(x=xs,
                           y=d_l * y_one,
                           hoverinfo='x+y',
                           mode='lines',
                           line=dict(width=0.5, color='rgb(217, 217, 217)'),
                           stackgroup='one'))
            fig.add_trace(
                go.Scatter(x=xs,
                           y=d_l * y_one,
                           hoverinfo='x+y',
                           mode='lines',
                           line=dict(width=0.5, color='rgb(217, 197, 178)'),
                           stackgroup='one'))
            fig.add_trace(
                go.Scatter(x=xs,
                           y=d_l * y_one,
                           hoverinfo='x+y',
                           mode='lines',
                           line=dict(width=0.5, color='rgb(178, 217, 178)'),
                           stackgroup='one'))
            fig.add_trace(
                go.Scatter(x=xs,
                           y=d_l * y_one,
                           hoverinfo='x+y',
                           mode='lines',
                           line=dict(width=0.5, color='rgb(178, 236, 236)'),
                           stackgroup='one'))

            fig.add_trace(
                go.Scatter(x=xs,
                           y=d_l * y_one,
                           hoverinfo='x+y',
                           mode='lines',
                           line=dict(width=0.5, color='rgb(236, 236, 178)'),
                           stackgroup='one'))
            fig.add_trace(
                go.Scatter(x=xs,
                           y=d_l * y_one,
                           hoverinfo='x+y',
                           mode='lines',
                           line=dict(width=0.5, color='rgb(255, 217, 178)'),
                           stackgroup='one'))
            fig.add_trace(
                go.Scatter(x=xs,
                           y=d_l * y_one,
                           hoverinfo='x+y',
                           mode='lines',
                           line=dict(width=0.5, color='rgb(255, 178, 178)'),
                           stackgroup='one'))
            fig.add_trace(
                go.Scatter(x=xs,
                           y=graph_list,
                           name="point",
                           line=dict(color='rgb(3,16,252)')))

            # 現状はグラフのy軸最大を1400固定
            fig.update_layout(
                showlegend=False,
                # yaxis_range=(0,graph_list[-1]+100),
                yaxis_range=(0, 1400),
                xaxis_range=(xs[0], xs[-1]))

            fig.write_html("point_graph.html")

            with open("point_graph.html", 'rb') as f:
                # S3アップロード処理
                # アップロード先URL{https://s3-ap-northeast-1.amazonaws.com/rakuten.intern2020/graph/{user_id}}
                s3 = boto3.resource('s3')
                response = s3.Bucket('rakuten.intern2020').put_object(
                    Key="graph/{}".format(user_id),
                    Body=f,
                    ContentType="text/html")
                # URL生成

        push_graph()

        print("バッチ処理開始")

        # return jsonify(status=0, message=''), 200

        # データベース内容変更 judge_budges関数内で使用

        def change_badges(user, meal, level):
            # Userテーブルのtotal_badgesを変更
            user_table = User.query.filter(User.user_id == user).first()
            user_table.total_badges += 1
            # Badgesテーブルにカラム追加
            badges_table = Badge.query.filter(Badge.user_id == user,
                                              Badge.meal_id == meal).all()
            if len(badges_table) == 0:
                add_data(Badge(user, meal, level))
            else:
                print("level", level)
                badges_table[0].level = level
            db_session.commit()

        # バッチを付与するか判定

        def judge_budges(meal_id):
            # 料理nameを取得 meal_name
            meal_name = MealContent.query.filter(
                MealContent.meal_id == meal_id).all()[0].name
            # 料理を過去何回作ったかを取ってくる meal_count
            user_cook = CookHistory.query.filter(
                CookHistory.user_id == user_id,
                CookHistory.meal_id == meal_id).all()
            meal_count = len(user_cook)
            # 閾値を超えたか判定し、badge_levelを取得 badge_level
            # badge_level 1 バッチ1個(仮)
            if meal_count == 1:
                change_badges(user_id, meal_id, 1)
                return {'meal_name': meal_name, 'badge_level': 1}
            # badge_level 2 バッチ5個(仮)
            elif meal_count == 5:
                change_badges(user_id, meal_id, 2)
                return {'meal_name': meal_name, 'badge_level': 2}
            # badge_level 3 バッチ10個(仮)
            elif meal_count >= 10:
                change_badges(user_id, meal_id, 3)
                return {'meal_name': meal_name, 'badge_level': 3}
            else:
                return {'meal_name': meal_name, 'badge_level': None}

        # meal_id_list=[meal_id1,meal_id2,meal_id3,meal_id4,meal_id5]
        post = []
        for m_id in meal_id:
            print(m_id)  # back確認用
            if m_id == None:
                pass
            else:
                b = judge_budges(m_id)
                if b['badge_level'] == None:
                    pass
                else:
                    post.append(b)
        print(post)  # back確認用
        return jsonify(get_badges=post)
    except Exception as e:
        abort(404, {'code': 'Not found', 'message': str(e)})
Ejemplo n.º 18
0
 def post(self):
     validity = PostSchema().validate(request.json)
     if validity:
         return validity
     obj = Post(**request.json).save()
     return PostSchema().dump(obj)