コード例 #1
0
def edit(id=0):
    form = PostForm()
    if id == 0:
        # 新增
        post = Post(users=current_user)
    else:
        # 修改
        post = Post.query.get_or_404(id)
        form.title.data = post.title
        form.body.data = post.body

    if form.validate_on_submit():
        form = PostForm()
        post.title = form.title.data
        post.body = form.body.data

        # post = Post(title=form.title.data, body=form.body.data)

        db.session.add(post)
        db.session.commit()
        return redirect(url_for('main.post', id=post.id))

    title = '添加新文章'
    if id > 0:
        title = '编辑 - %s' % post.title
    return render_template('edit.html', title=title, form=form, post=post)
コード例 #2
0
ファイル: controller.py プロジェクト: atyrin/veeamchan
def upload_multimedia(post_request, post: model.Post):
    try:
        photo = post_request.files['file']
        if photo.filename:
            print("Filename = ", photo.filename)
            file_extension = photo.filename.rsplit('.', 1)[-1]
            print("type: " + file_extension)
            post_attachment = model.Image(post_link=post)
            if file_extension == "gif":
                print("It's GIF")
                post_attachment.img_src.put(photo, content_type='image/gif')
                print("put done")
            elif file_extension == "webm":
                print("It's webm")
                post_attachment.img_src.put(photo, content_type='video/webm')
                thumbnail = thumbnail_generator.create_video_thumbnail(photo)
                post_attachment.img_thumbnail_src.put(thumbnail, content_type='image/jpeg')
                print("put done")
            else:
                print("Other extension: ", file_extension)
                post_attachment.img_src.put(photo, content_type='image/jpeg')
                thumbnail = thumbnail_generator.create_image_thumbnail(photo)
                post_attachment.img_thumbnail_src.put(thumbnail, content_type='image/jpeg')

                print("Other extension:", post_attachment.img_src.content_type)
                print("put done")

            post_attachment.img_id = str(hashlib.md5(post_attachment.img_src.read()).hexdigest())
            post_attachment.save()
            post.update(set__content_type=post_attachment.img_src.content_type)
            post.update(set__image_id=post_attachment.img_id)
    except:
        print("Unexpected error:", sys.exc_info()[0])
コード例 #3
0
def test_3_1():
    post = Post(id=1, name="science")
    post2 = Post(id=2, name="history")
    post3 = Post(id=3, name="physical")
    db.session.add(post)
    db.session.add(post2)
    db.session.add(post3)
    db.session.commit()
コード例 #4
0
ファイル: post.py プロジェクト: micanzhang/focus
    def POST(self):
        data = web.input()
        if not data or not data.has_key('content') or len(data['content']) == 0:
            self.response.error = ResponseStatus.STATUS_INCORRECT_PARAMS
            self.response.msg = "invalid parameters"
            return self.render()


        content = data['content']
        p = Post(
            username=self.session.user.username,
            author=self.session.user.username,
            content=content,
            create_time=int(time.time())
        )

        topics = Post.parse_topic(content)
        if not topics or len(topics) == 0:
            self.response.error = ResponseStatus.STATUS_INCORRECT_PARAMS
            self.response.msg = "missing topic"
            return self.render()

        web.ctx.orm.add(p)
        web.ctx.orm.flush()

        if 'position' in data and 'address' in data:
            geodata = data.position.split(',')
            (lat, lng) = geodata if len(geodata) == 2 else (None, None)
            if lat and lng and data.address:
                geo = PostGeo(
                    post_id=p.id,
                    lat=lat,
                    lng=lng,
                    address=data.address
                )
                web.ctx.orm.add(geo)


        for topic in topics:
            post_topic = PostTopic(
            post_id=p.id,
            topic=topic
        )
        web.ctx.orm.add(post_topic)

        mentions = Post.parse_mention(content)
        users = web.ctx.orm.query(User).filter(User.username.in_(mentions)).all() if len(mentions) > 0 else []
        for user in users:
            mention = Mention(
                username=user.username,
                post_id=p.id
            )
            web.ctx.orm.add(mention)

        return self.render()
コード例 #5
0
ファイル: suite.py プロジェクト: HuangChain/job
	def prepare_post(self):
		
		#with self.client:
			self.login()
			post1 = Post(title='this is post 1',
					post='this is some text! #1 job link test', author_id=current_user.id)
			post2 = Post(title='this is post 2',
					post='this is some text too!', author_id=current_user.id)
			db.session.add(post1)
			db.session.add(post2)
			db.session.commit()
コード例 #6
0
ファイル: post.py プロジェクト: micanzhang/focus
    def POST(self):
        data = web.input()
        if not data or not data.has_key('content') or len(data['content']) == 0:
            return "invalid post."

        content = data['content']
        p = Post(
            username=self.session.user.username,
            author=self.session.user.username,
            content=content,
            create_time=int(time.time())
        )

        topics = Post.parse_topic(content)
        if not topics or len(topics) == 0:
            raise web.notfound

        web.ctx.orm.add(p)
        web.ctx.orm.flush()

        if 'position' in data:
            geodata = data.position.split(',')
            (lat, lng) = geodata if len(geodata) == 2 else (None, None)
            if lat and lng:
                geo = postGeo(
                    post_id=p.id,
                    lat=lat,
                    lng=lng
                )
                web.ctx.orm.add(geo)


        for topic in topics:
            post_topic = PostTopic(
                post_id=p.id,
                topic=topic
            )
            web.ctx.orm.add(post_topic)

        mentions = Post.parse_mention(content)
        users = web.ctx.orm.query(User).filter(User.username.in_(mentions)).all() if len(mentions) > 0 else []
        for user in users:
             mention = Mention(
                 username=user.username,
                 post_id=p.id
             )
             web.ctx.orm.add(mention)

        return web.seeother('/post')
コード例 #7
0
ファイル: routes.py プロジェクト: healthmate/HealthMateServer
def get_all_challenges(current_user):
    # challenges = Challenge.get_challenge_by_user_id(current_user.id)
    challenges = Challenge.get_challenge_within_date_by_user_id(current_user.id, datetime.datetime.now())
    resp = []
    for challenge in challenges:
        user = Challenge.get_creator(challenge.id)
        username = User.getusername(user.user_id)
        my_format = "%Y-%m-%d %H:%M:%S"
        start_date = datetime.datetime.strptime(str(challenge.start_date), my_format).date()
        new_date = datetime.datetime.strptime(str(challenge.end_date), my_format).date()
        users = Challenge.get_users_performance(challenge.post_id)
        challenge_users = []
        for user in users:
            user_name = User.getusername(user.user_id)
            challenge_users.append({
                'username': user_name,
                'steps': Challenge.get_user_steps_by_challenge(datetime.datetime.now().date(),
                                                               start_date, user.user_id),
                'role': user.role
            })
        resp.append({
            'steps': Challenge.get_user_steps_by_challenge(datetime.datetime.now().date(), start_date, current_user.id),
            'start_date': challenge.start_date,
            'goal': challenge.goal,
            'role': challenge.role,
            'challenge_name': challenge.challenge_name,
            'challenge_description': challenge.challenge_description,
            'end_date': str(new_date),
            'creator': username,
            'image_url': Post.get_post_image_url(challenge.post_id),
            'challenge_id': challenge.id,
            'users': challenge_users
        })
    return jsonify(resp), 200
コード例 #8
0
ファイル: routes.py プロジェクト: sbansa1/Micro-Blog
def index():
    form = PostForm()
    if form.validate_on_submit():
        language = guess_language(form.post.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        post = Post(body=form.post.data,
                    author=current_user,
                    language=language)
        db.session.add(post)
        db.session.commit()
        flash(_('Your post is now live!'))
        return redirect(url_for('main.index'))
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, current_app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('main.index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('main.index', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html',
                           title=_('Home'),
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
コード例 #9
0
ファイル: test_comment.py プロジェクト: TracyOgutu/Blog
    def setUp(self):
        self.new_post = Post(id=1,
                             title='Test_post',
                             content='Am testing a test post')

        self.new_comment = Comment(id=1,
                                   comment='Test comment',
                                   posts_id=self.new_post)
コード例 #10
0
ファイル: api.py プロジェクト: ostapkob/nmtport
def add_usm():
    '''add post by GET request from arduino'''
    mechanism_id = request.args.get('mechanism_id')
    password = request.args.get('password')
    value = request.args.get('value')
    value2 = request.args.get('value2')
    value3 = request.args.get('value3')
    count = request.args.get('count')
    latitude = request.args.get('latitude')
    longitude = request.args.get('longitude')
    try:
        number = dict_mechanisms_number_by_id['usm'][int(mechanism_id)]
    except KeyError:
        return 'Not this id or not usm'
    try:
        mech = Mechanism.query.get(mechanism_id)
    except Exception as e:
        logger.debug(e)
    # if mechanism_id == '33287' and value3 == '0': # FIX
    #     value3 = '15'
    items = mechanism_id, password, latitude, longitude
    test_items = any([item is None for item in items])
    if int(value3) < 5:  # if roller not circle
        value = 0
    if test_items:
        return 'Bad request'
    if password not in post_pass:
        return 'Bad password'
    if int(mechanism_id) not in all_mechanisms_id('usm'):
        return 'Not this id'
    if number in usm_no_move:
        latitude = 0
        longitude = 0
    if latitude == '':
        latitude = 0
        longitude = 0
    if float(latitude) == 0 or float(longitude) == 0:
        try:
            data_mech = db.session.query(Post).filter(
                Post.mechanism_id == mechanism_id).order_by(
                    Post.timestamp.desc()).first()
        except Exception as e:
            logger.debug(e)
        latitude = data_mech.latitude
        longitude = data_mech.longitude
    terminal = which_terminal('usm', number, latitude,
                              longitude)  # exist 9, 11, 13, 15
    new_post = Post(value=value,
                    value2=value2,
                    value3=value3,
                    count=count,
                    latitude=latitude,
                    longitude=longitude,
                    mechanism_id=mechanism_id,
                    terminal=terminal)
    add_fix_post(new_post)
    return f'Success, {str(items)}, {str(datetime.now().strftime("%d.%m.%Y %H:%M:%S"))}'
コード例 #11
0
def fake_posts(count=50):
    for i in range(count):
        with db.auto_commit():
            post = Post(title=fake.sentence(),
                        body=fake.text(200),
                        category=Category.query.get(
                            random.randint(1, Category.query.count())),
                        timestamp=fake.date_time_this_year())
            db.session.add(post)
コード例 #12
0
def forum(page=1):
    form = Send_post()
    if hasattr(current_user, 'id') and form.validate_on_submit():
        post = form.text.data
        new_post = Post(title=form.title.data,
                        post=int_to_link(post),
                        author_id=current_user.id)
        new_post._save()
        return redirect(url_for('forum.forum'))

    paginate = Post.query.order_by(Post.post_time).paginate(page=page,
                                                            per_page=10)
    posts = paginate.items
    return render_template('forum.html',
                           posts=posts,
                           current_page=page,
                           form=form,
                           has_prev=paginate.has_prev,
                           has_next=paginate.has_next)
コード例 #13
0
ファイル: test.py プロジェクト: 182hl/mocroblog2
    def test_follow_posts(self):
        #create for users
        u1 = User(username='******', email='*****@*****.**')
        u2 = User(username='******', email='*****@*****.**')
        u3 = User(username='******', email='*****@*****.**')
        u4 = User(username='******', email='*****@*****.**')
        db.session.add_all([u1, u2, u3, u4])

        #create for posts
        now = datetime.utcnow()
        p1 = Post(body="post from john",
                  author=u1,
                  timestamp=now + timedelta(seconds=1))
        p2 = Post(body="post from susan",
                  author=u2,
                  timestamp=now + timedelta(seconds=2))
        p3 = Post(body="post from mary",
                  author=u3,
                  timestamp=now + timedelta(seconds=3))
        p4 = Post(body="post from davied",
                  author=u4,
                  timestamp=now + timedelta(seconds=4))
        db.session.add_all([p1, p2, p3, p4])
        db.session.commit()

        #setup for followers
        u1.follow(u2)
        u1.follow(u4)
        u2.follow(u3)
        u3.follow(u4)
        db.session.commit()

        # check the followed posts of each user
        f1 = u1.followed_posts().all()
        f2 = u2.followed_posts().all()
        f3 = u3.followed_posts().all()
        f4 = u4.followed_posts().all()

        self.assertEqual(f1, [p4, p2, p1])
        self.assertEqual(f2, [p3, p2])
        self.assertEqual(f3, [p4, p3])
        self.assertEqual(f4, [p4])
コード例 #14
0
ファイル: api.py プロジェクト: ostapkob/nmtport
def add_kran():
    '''add post by GET request from arduino'''
    mechanism_id = request.args.get('mechanism_id')
    password = request.args.get('password')
    value = request.args.get('value')
    value3 = request.args.get('value3')
    latitude = request.args.get('latitude')
    longitude = request.args.get('longitude')
    try:
        mech = Mechanism.query.get(mechanism_id)
    except Exception as e:
        logger.debug(e)

    # if mechanism_id == '15510' and value == '1':
    #     value = '2'

    items = mechanism_id, password, latitude, longitude, value, value3
    test_items = any([item is None for item in items])  # if this id is exist
    if test_items:
        return 'Bad request'
    if password not in post_pass:
        return 'Bad password'
    if int(mechanism_id) not in all_mechanisms_id('kran'):
        return 'Not this id or not kran'
    if latitude == '':
        latitude = 0
        longitude = 0
    if float(latitude) == 0 or float(longitude) == 0:
        try:
            data_mech = db.session.query(Post).filter(
                Post.mechanism_id == mechanism_id).order_by(
                    Post.timestamp.desc()).first()
        except Exception as e:
            logger.debug(e)
        latitude = data_mech.latitude
        longitude = data_mech.longitude
    if mech.number in krans_if_3_then_2 and value == '3':
        value = 2
    if mech.number in krans_if_1_then_0 and value == '1':
        value = 4
    k1, b1 = line_kran(mech.number)
    k2, b2 = perpendicular_line_equation(k1, float(latitude), float(longitude))
    latitude, longitude = intersection_point_of_lines(k1, b1, k2, b2)
    terminal = which_terminal('kran', number, latitude,
                              longitude)  # exist 9, 11, 13, 15
    new_post = Post(value=value,
                    value3=value3,
                    latitude=latitude,
                    longitude=longitude,
                    mechanism_id=mechanism_id,
                    terminal=terminal)
    db.session.add(new_post)
    db.session.commit()
    return f'Success, {str(mech.number)},  {str(items)}, {str(datetime.now().strftime("%d.%m.%Y %H:%M:%S"))}'
コード例 #15
0
def new_post():
    form = PostForm()
    if request.method == 'POST' and form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        category = Category.query.get(form.categories.data)
        post = Post()
        post.title = title
        post.category = category
        post.body = body
        try:
            db.session.add(post)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            raise e
        flash('新建了一篇文章', 'success')
        return redirect(url_for('blog.show_post', post_id=post.id))
    return render_template('admin/new_post.html', form=form)
コード例 #16
0
ファイル: views.py プロジェクト: mwikiaBundi1/Musica-App
def post():
    form = PostForm()
    if form.validate_on_submit():
        title = form.title.data
        content = form.content.data
        
        post = Post(title = title,content=content,rel = current_user)
        db.session.add(post)
        db.session.commit()
        flash('posted','success')
        return redirect(url_for('main'))
    return render_template('post.html',form = form,rel = current_user)
コード例 #17
0
ファイル: views.py プロジェクト: OQJ/myblog
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        tag = int(form.tag.data)
        post = Post(title=title, body=body, tag_id=tag)
        db.session.add(post)
        db.session.commit()
        flash('创建成功', 'success')
        return redirect(url_for('index'))

    return render_template('new_post.html', form=form)
コード例 #18
0
ファイル: routes.py プロジェクト: healthmate/HealthMateServer
def post(current_user):
    """
       create a post
    :return:
    """
    values = request.get_json()
    required = ['description', 'image_url']
    if not all(k in values for k in required):
        return 'Missing values', 400
    description = values.get('description')

    image_url = values.get('image_url')
    userid = current_user.id

    post_item = Post(description, image_url, userid)
    post_id = post_item.save()
    temp = description.lower()
    data = {}
    for word in temp.split():
        if word.startswith("#"):
            if "challenge" in word:
                data['challenge'] = word[1:]
            elif word[1:].startswith("d"):
                data['date'] = word[2:]
            elif word[1:].startswith("g"):
                data['goal'] = word[2:]

    required = ['challenge', 'date', 'goal']
    if all(k in data for k in required):
        end_date = {}
        date = data["date"].split('-')
        end_date['year'] = date[0]
        end_date['month'] = date[1]
        end_date['day'] = date[2]
        challenge = Challenge(user_id=current_user.id, goal=data["goal"], challenge_name=data["challenge"],
                              challenge_description=description, end_date=end_date, post_id=post_id)
        challenge.save()
    return response('success', 'Successfully posted', 200)
コード例 #19
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',
                           title='New Post',
                           form=form,
                           legend='New Post')
コード例 #20
0
def post_baru():
    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('Post Anda telah dibuat!', 'success')
        return redirect(url_for('main.rumah'))
    return render_template('create_post.html',
                           title='Buat Post',
                           form=form,
                           legend='Buat Post')
コード例 #21
0
def upload_multimedia(post_request, post: model.Post):
    try:
        photo = post_request.files['file']
        if photo.filename:
            print("Filename = ", photo.filename)
            file_extension = photo.filename.rsplit('.', 1)[-1]
            print("type: " + file_extension)
            post_attachment = model.Image(post_link=post)
            if file_extension == "gif":
                print("It's GIF")
                post_attachment.img_src.put(photo, content_type='image/gif')
                print("put done")
            elif file_extension == "webm":
                print("It's webm")
                post_attachment.img_src.put(photo, content_type='video/webm')
                thumbnail = thumbnail_generator.create_video_thumbnail(photo)
                post_attachment.img_thumbnail_src.put(
                    thumbnail, content_type='image/jpeg')
                print("put done")
            else:
                print("Other extension: ", file_extension)
                post_attachment.img_src.put(photo, content_type='image/jpeg')
                thumbnail = thumbnail_generator.create_image_thumbnail(photo)
                post_attachment.img_thumbnail_src.put(
                    thumbnail, content_type='image/jpeg')

                print("Other extension:", post_attachment.img_src.content_type)
                print("put done")

            post_attachment.img_id = str(
                hashlib.md5(post_attachment.img_src.read()).hexdigest())
            post_attachment.save()
            post.update(set__content_type=post_attachment.img_src.content_type)
            post.update(set__image_id=post_attachment.img_id)
    except:
        print("Unexpected error:", sys.exc_info()[0])
コード例 #22
0
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
        post = Post(body=form.body.data, author=current_user._get_current_object())
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page,
                                                                     per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
                                                                     error_out=False)
    posts = pagination.items
    return render_template('index.html', form=form, posts=posts,
                           pagination=pagination,
                           current_time=datetime.utcnow())
コード例 #23
0
def add_blog():
    # create author object
    posted_post = PostSchema(only=('title', 'thumbnail', 'author_id', 'preview', 'content'))\
        .load(request.form)

    post = Post(**posted_post.data)

    # add new author to database
    session = db.session()
    session.add(post)
    session.commit()

    # return newly added author
    new_post = PostSchema().dump(post)
    return jsonify(new_post)
コード例 #24
0
ファイル: routes.py プロジェクト: healthmate/HealthMateServer
def getuserprofile(current_user):
    global user_steps
    count = Community.get_community_count(current_user.id)
    post_count = Post.get_post_count(current_user.id)
    steps = Steps.get_steps(current_user.id, 1)
    for item in steps:
        user_steps = item.steps_no
    data = {
        'user_id': current_user.id,
        'username': current_user.username,
        'community': count,
        'posts': post_count,
        'steps_today': user_steps
    }

    return jsonify(data), 200
コード例 #25
0
ファイル: api.py プロジェクト: ostapkob/nmtport
def add_sennebogen():
    '''add post by GET request from arduino'''
    type_mechanism = 'sennebogen'
    number = request.args.get('number')
    password = request.args.get('password')
    x = request.args.get('x')
    y = request.args.get('y')
    count = request.args.get('count')
    latitude = request.args.get('lat')
    longitude = request.args.get('lon')
    mechanism_id = id_by_number(type_mechanism, number)
    try:
        mech = Mechanism.query.get(mechanism_id)
    except Exception as e:
        logger.debug(e)
    items = mechanism_id, password, latitude, longitude, x, y
    test_items = any([item is None for item in items])

    if test_items:
        return 'Bad request'
    if password not in post_pass:
        return 'Bad password'
    if int(mechanism_id) not in all_mechanisms_id(type_mechanism):
        return 'Not this id'
    if latitude == '':
        latitude = 0
        longitude = 0
    if float(latitude) == 0 or float(longitude) == 0:  # get last find value
        try:
            data_mech = db.session.query(Post).filter(
                Post.mechanism_id == mechanism_id).order_by(
                    Post.timestamp.desc()).first()
        except Exception as e:
            logger.debug(e)
        latitude = data_mech.latitude
        longitude = data_mech.longitude
    terminal = which_terminal('sennebogen', number, latitude,
                              longitude)  # exist 9, 11, 13, 15
    new_post = Post(value=x,
                    value2=y,
                    count=count,
                    latitude=latitude,
                    longitude=longitude,
                    mechanism_id=mechanism_id,
                    terminal=terminal)
    add_fix_post(new_post)
    return f'Success, {str(items)}, {str(datetime.now().strftime("%d.%m.%Y %H:%M:%S"))}'
コード例 #26
0
ファイル: api.py プロジェクト: ostapkob/nmtport
def add_kran2():
    '''add post by GET request from arduino'''
    number = int(request.args.get('number'))
    password = request.args.get('passw')
    value = int(request.args.get('value'))
    count = request.args.get('count')
    latitude = request.args.get('lat')
    longitude = request.args.get('lon')
    x = abs(int(request.args.get('x')))  # accelerometr x-axis
    y = abs(int(request.args.get('y')))  # accelerometr y-axis
    try:
        mechanism_id = dict_mechanisms_id_by_number['kran'][number]
    except KeyError:
        return 'Not this id or not kran'
    try:
        mech = Mechanism.query.get(mechanism_id)
    except Exception as e:
        logger.debug(e)
    # if mechanism_id == 4513 and value == 1: # FIX
    #     value = 2
    items = mechanism_id, password, latitude, longitude, value, count
    test_items = any([item is None for item in items])  # if this id is exist
    if test_items:
        return 'Bad request'
    if password not in post_pass:
        return 'Bad password'
    if number in krans_if_3_then_2 and value == 3:
        value = 2
    if number in krans_if_1_then_0 and value == 1:
        value = 4  # 4 work how 0
    if value == 0 and ((x > 500 and y > 500) or x > 850 or y > 850):
        value = 5  # kran move
    if latitude == '':
        latitude = 0
        longitude = 0
    latitude, longitude = corect_position(mech, latitude, longitude)
    terminal = which_terminal('kran', number, latitude,
                              longitude)  # exist 9, 11, 13, 15
    new_post = Post(value=value,
                    count=count,
                    latitude=latitude,
                    longitude=longitude,
                    mechanism_id=mechanism_id,
                    terminal=terminal)
    db.session.add(new_post)
    db.session.commit()
    return f'Success, {str(mech.number)},  {str(items)}, {str(datetime.now().strftime("%d.%m.%Y %H:%M:%S"))}'
コード例 #27
0
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data,author = current_user)
        db.session.add(post)
        db.session.commit()
        flash("Your post is now Live !")
        return redirect(url_for('index'))
    #user = {'username': "******"}
    posts = current_user.followed_posts().all()
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(page,app.config["POSTS_PER_PAGE"],False)
    next_url = url_for('index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('index', page = posts.prev_num)\
        if posts.has_prev else None
    return render_template('index.html', title = 'HomePage', posts = posts.items, form=form, next_url=next_url,prev_url=prev_url)
コード例 #28
0
ファイル: views.py プロジェクト: OQJ/myblog
def edit_post(id):
    post = Post.query.get_or_404(id)
    form = PostForm()

    form.title.data = post.title
    form.body.data = post.body
    form.tag.data = post.tag_id
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        tag = int(form.tag.data)
        post = Post(title=title, body=body, tag_id=tag)
        db.session.add(post)
        db.session.commit()
        flash('创建成功', 'success')
        return redirect(url_for('index'))

    return render_template('edit_post.html', form=form, post=post)
コード例 #29
0
def index():
    # user = {"username": "******"}
    # # return "hello,World" #返回一个字符串
    #提交博客方法
    form = PostForm()
    if form.validate_on_submit():
        language = guess_language(form.post.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ' '
        post = Post(body=form.post.data,
                    author=current_user,
                    language=language)
        db.session.add(post)
        db.session.commit()
        #_()函数将文本包装在基本语言中
        flash(_('Your post is now live!'))
        #重定向的好处是刷新页面的时候不会把之前的表单内容再请求一次
        return redirect(url_for('main.index'))

    # if current_user.is_authenticated:
    # 加载用户提交过的博客内容
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, current_app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('main.index',
                       page=posts.next_num) if posts.has_next else None
    prev_url = url_for('main.index',
                       page=posts.prev_num) if posts.has_prev else None
    return render_template('index.html',
                           title='Home Page',
                           posts=posts.items,
                           form=form,
                           next_url=next_url,
                           prev_url=prev_url)
    # posts = [
    #     {
    #         'author': {'username': '******'},
    #         'body': 'Beautiful day in Portland!'
    #     },
    #     {
    #         'author': {'username': '******'},
    #         'body': 'The Avengers movie was so cool!'
    #     }]
    return render_template('index.html', title='Home', posts=posts)
コード例 #30
0
ファイル: routes.py プロジェクト: healthmate/HealthMateServer
def getuserpost(current_user, user_id):
    """
    get posts
    :return:
    """
    posts = []
    post = Post.get_posts(user_id)
    comments = []
    is_liked = False

    for item in post:

        comments.clear()
        comment = Comments.getcomments(item.id)
        user = User.get_by_id(item.user_id)

        likers = Likes.getlikers(post_id=item.id)
        for liker in likers:
            if liker.user_id == current_user.id:
                is_liked = True

        for c in comment:
            comments.append({
                'comment': c.comment,
                'username': User.getusername(c.user_id),
                'create_at': c.create_at
            })

        posts.append({
            'post_id': item.id,
            'description': item.description,
            'image_url': item.image_url,
            'create_at': item.create_at,
            'user_id': item.user_id,
            'profile_pic': user.profile_pic,
            'username': user.username,
            'likes': item.likes,
            'comments': comments,
            'is_liked': is_liked
        })
    return jsonify(posts), 200
コード例 #31
0
def new_post():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        tag = request.form['tag']
        file = request.files['file']

        if len(body) >= 200:
            if [True for t in tag.split(',') if ('investment' in t.lower().strip()) or ('business' in t.lower().strip()) or ('life' in t.lower().strip()) or ('money' in t.lower().strip())]:
                if file.filename != "" and [True for file_s in file.filename.split('.') if file_s.isalnum()]:
                    # checking file extension
                    def check_file(file__):
                        return '.' in file__ and file__.rsplit('.', 1)[1].lower() in ALLOW_EXTENSIONS

                    if check_file(file.filename):
                        file_name = os.path.join(
                            app.config['UPLOAD_FOLDER'], file.filename)
                        file.save(file_name)

                        post = Post(title=title, body=body, tag=tag, url=file_name, date=date)
                        db.session.add(post)
                        db.session.commit()
                        flash('Successfully posted!', 'success')
                        return redirect(url_for('user.index'))

                    else:
                        flash('This file isn\'t secure!', 'danger')
                        return redirect(url_for('new_post'))
                else:
                    flash('No file selected!', 'danger')
                    return redirect(url_for('new_post'))
            else:
                flash('Ours platform is based on four catageory,  (i.e. investment, money, life, business).', 'danger')
                return redirect(url_for('user.new_post'))
        else:
            flash('Body length should be greater than two thousand!', 'danger')
            return redirect(url_for('user.new_post'))
    else:
        return render_template('add_post.html')
コード例 #32
0
def add():
    user = current_user.uname
    form = AddForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            title = form.title.data
            author = current_user.uname
            head = form.head.data
            body = form.body.data
            user = User.query.filter(User.uname == author).first()
            author_id = user.uid
            post = Post(title=title,
                        author_id=author_id,
                        head=head,
                        body=body,
                        user=user)
            db.session.add(post)
            db.session.commit()
            return redirect('/admin/')
        return '提交失败'

    return render_template('admin/add.html', form=form, user=user)
コード例 #33
0
ファイル: routes.py プロジェクト: healthmate/HealthMateServer
def getuser():
    global user_steps
    values = request.get_json()
    required = ['user_id']
    if not all(k in values for k in required):
        return 'Missing values', 400
    user = User.get_by_id(values.get('user_id'))
    count = Community.get_community_count(values.get('user_id'))
    post_count = Post.get_post_count(values.get('user_id'))
    steps = Steps.get_steps(values.get('user_id'), 1)
    for item in steps:
        user_steps = item.steps_no
    if user:
        data = {
            'user_id': user.id,
            'username': user.username,
            'community': count,
            'posts': post_count,
            'steps_today': user_steps
        }
    else:
        return response('failed', 'User Does not exist', 401)
    return jsonify(data), 200