def callback_inline(call):
    user = session.query(User).filter_by(user_id=call.message.chat.id).first()

    if not call.message:
        bot.delete_message(call.message.chat.id, call.message.message_id)
        user.state = 'main_menu_state'
        session.commit()
        get_state_and_process(call.message, user, True)

    if call.data == "save_categories":
        user.state = 'set_city_state'
        session.commit()
        get_state_and_process(call.message, user, True)
    else:
        subscription = session.query(UserSubscription).filter_by(name=call.data.replace("_on", ""), user_id=user.id).first()
        if not subscription:
            subscription = UserSubscription(name=call.data.replace("_on", ""), user_id=user.id)
            session.add(subscription)
        else:
            session.delete(subscription)
        session.commit()
        bot.edit_message_reply_markup(
            call.message.chat.id,
            call.message.message_id,
            call.message.message_id,
            reply_markup=categories_inline_keyboard(user=user)
        )
示例#2
0
def delete_post(postId=None):
    post = session.query(Post).filter(Post.id==postId).all()[0]
    if (post.author.id != current_user.id):
        return redirect(url_for("posts"))
    session.delete(post)
    session.commit()
    return redirect(url_for("posts"))
示例#3
0
def delete_movie(movie_id):

    movie = session.query(Movie).filter(Movie.id == movie_id).first()

    if not movie:
        return make_response(
            jsonify({
                'response': 'Movie not found',
                'status': 404
            }))

    session.delete(movie)

    try:
        session.commit()
    except Exception as e:
        return make_response(
            jsonify({
                'Error': 'Movie was not deleted',
                'status': 500
            }), 500)

    return make_response(
        jsonify({
            'response': 'Movie has been deleted',
            'status': 200
        }), 200)
示例#4
0
 def delete(id):
     event: TahuraEvent = TahuraEvent.getEventBy(TahuraEvent.id_event == id)
     if event is not None:
         session.delete(event)
         session.commit()
         return True
     return event
示例#5
0
 async def on_voice_state_update(self, member, before, after):
     if after.channel != None:
         channelQ = get_private(after.channel.id)
     else:
         channelQ = get_private(before.channel.id)
     if channelQ != None:
         channels = session.query(Private).all()
         if after.channel == None:
             channelQ.count_members = 0
         else:
             channelQ.count_members = len(after.channel.members)
         for channel in channels:
             channeld = member.guild.get_channel(channel.channel_id)
             if channeld.members == []:
                 await channeld.delete()
                 session.delete(channel)
         session.commit()
     else:
         if after.channel.id == 649676227329654834:
             channel = await member.guild.create_voice_channel(
                 member.name, category=after.channel.category)
             add_private(Private(channel_id=channel.id, count_members=1))
             await member.move_to(channel)
             overwrite = PermissionOverwrite()
             overwrite.manage_channels = True
             await channel.set_permissions(member, overwrite=overwrite)
示例#6
0
 def delete(id):
     wisata: Wisata = Wisata.getWisataBy(Wisata.id_wisata == id)
     if wisata is not None:
         session.delete(wisata)
         session.commit()
         return True
     return wisata
示例#7
0
async def matchmaking(every):
    while True:
        print("Matchmaking started.")
        waiting = session.query(Waffle).filter(
            Waffle.status == WaffleStatus.MATCHMAKING).join(User).all()
        waiting.sort(key=lambda w: len(w.users))
        while len(waiting) > 1:
            first = waiting.pop()
            second = waiting.pop()
            message = "Benvenuto al Waffle #{id}!\n" \
                      "Tutti i messaggi che scriverai qui arriveranno agli altri giocatori.\n" \
                      "Ricordati di non rivelare la tua identità, però!" \
                      "Per abbandonare il Waffle, vota /quit.\n" \
                      "Per scoprire il nome degli altri e concludere la partita, vota /reveal.\n" \
                      "Per ingrandire il Waffle, vota /expand.\n" \
                      "La votazione terminerà tra 18 ore. Se non avrai votato niente, verrai espulso per inattività.\n" \
                      "Giocatori in questo Waffle:\n"
            newwaffle = Waffle(status=WaffleStatus.CHATTING)
            session.add(newwaffle)
            session.commit()
            for user in first.users + second.users:
                user.join_waffle(b, newwaffle.id)
                message += f"- {user.icon}\n"
            session.commit()
            session.delete(first)
            session.delete(second)
            session.commit()
            l.create_task(votes(64800, newwaffle.id))
            await newwaffle.message(b, message.format(id=newwaffle.id))
        await asyncio.sleep(every)
示例#8
0
def delete_restaurant(restaurant_id):
    try:
        restaurant_to_delete = session.query(Restaurant).filter_by(
            id=restaurant_id).one()
    except:
        return "No such restaurant to delete"
    if restaurant_to_delete.user_id != login_session['user_id']:
        return "<script>function myFunction() {" \
               "alert('You are not authorized to delete this restaurant. " \
               "Please create your own restaurant in order to delete.');}" \
               "</script><body onload='myFunction()''>"
    if request.method == 'POST':
        session.delete(restaurant_to_delete)
        menu_items_to_delete = session.query(MenuItem).filter_by(
            restaurant_id=restaurant_id).all()
        for del_menu in menu_items_to_delete:
            session.delete(del_menu)
        flash('%s Successfully Deleted' % restaurant_to_delete.name)
        session.commit()
        return redirect(
            url_for('restaurant.show_restaurants',
                    restaurant_id=restaurant_id))
    else:
        return render_template('deleteRestaurant.html',
                               restaurant=restaurant_to_delete)
示例#9
0
def confirm_tg_account(bot, update, user_data):
    code = update.message.text
    tg_session = session.query(TelegramSession).filter(
        TelegramSession.id == int(user_data['session_id'])).first()
    user = session.query(User).filter(
        User.tg_id == update.message.chat_id).first()
    client = TelegramClient(
        os.path.join(config.TELETHON_SESSIONS_DIR, tg_session.phone_number),
        user.api_id if user.api_id else config.TELEGRAM_API_ID,
        user.api_hash if user.api_hash else config.TELEGRAM_API_HASH)
    client.connect()

    try:
        client.sign_in(tg_session.phone_number,
                       code,
                       phone_code_hash=tg_session.phone_code_hash)
        tg_session.active = True
        update.message.reply_text('Account added successfully.')
    except Exception as e:
        update.message.reply_text('Error: {}.'.format(e))
        path = os.path.join(config.TELETHON_SESSIONS_DIR,
                            '{}.session'.format(tg_session.phone_number))
        if os.path.exists(path):
            os.remove(path)
        session.delete(tg_session)

    session.commit()

    client.disconnect()

    return ConversationHandler.END
示例#10
0
 def delete(self, id):
     note = session.query(Note).filter(Note.id == id).first()
     if not note:
         abort(404, message="Note %s doesn't exist" % id)
     session.delete(note)
     session.commit()
     return note, 202
示例#11
0
文件: api.py 项目: bb071988/tuneful
def song_delete():
    """ delete a song """
    headers = {"Location": url_for("song_delete")}
    # get the data from the form
    
    data = request.json
    
    post_song = models.Song(song_name=data["song_name"],id=data["song_id"])  ## ask sam if we really need to post seperately.
    post_file = models.File(song_id=data["song_id"],file_name=data["file_name"],id=data["file_id"])
  
    if session.query(models.Song).get(post_song.id):  #consider adding a check here for duplicate fileID too
        del_song=session.query(models.Song).get(post_song.id)
        session.delete(del_song)
        
        del_file = session.query(models.File).get(post_file.id)
        session.delete(del_file)
        
        session.commit()
    else:
        print "************* ELSE ***************"
        session.rollback()
        session.flush()
        return Response(json.dumps({"status":"failed - that song doesnt exists"}),500,mimetype="application/json")
    
    return Response(json.dumps({"status":"deleted"}), 200, headers=headers, mimetype="application/json")
示例#12
0
def auto_rollback():
    for item in session.query(TodoItem).all():
        session.delete(item)
    session.flush()
    engine.commit = lambda: None
    yield
    session.rollback()
示例#13
0
def delete_event():
    events = session.query(Event).all()
    for event in events:
        html = get_html(URL + str(event.id_site))
        if html.status_code == 404:
            print(f'delete event: {event.id_site}')
            session.delete(event)
示例#14
0
文件: views.py 项目: kjgross/blog
def delete_post_post(post):
    posts= session.query(Post)
    posts= posts[post]

    session.delete(posts)
    session.commit()
    return redirect(url_for("posts"))
示例#15
0
def delete_item(todo_id: int):
    todo_item = session.query(TodoItem).filter(TodoItem.id == todo_id).first()
    if not todo_item:
        raise HTTPException(status_code=404, detail="Item not found")
    session.delete(todo_item)
    session.flush()
    session.commit()
    return {"status": "success"}
示例#16
0
文件: views.py 项目: rygy/trackful
def delete_meal(meal_id=None):

    meal = session.query(Meal).get(meal_id)

    session.delete(meal)

    flash('Meal Deleted!')

    return redirect(url_for('meals'))
示例#17
0
文件: views.py 项目: rygy/trackful
def delete_activity(activity_id=None):

    activity = session.query(Activity).get(activity_id)

    session.delete(activity)

    flash('Activity Deleted!')

    return redirect(url_for('entries'))
示例#18
0
def delete_item(category_name, item_title, item=None):
    """Delete a item."""
    if request.method == "POST":
        session.delete(item)
        session.commit()
        flash("Item '{}' Successfully Deleted".format(item.title), "success")
        return redirect(
            url_for("item.show_items", category_name=category_name))
    else:
        return render_template("delete_item.html", item=item)
示例#19
0
def create_or_update_or_delete():
    schema = {
        'type': 'object',
        'properties': {
            'username': {
                'type': 'string'
            }
        },
        'required': ['username']
    }

    try:
        validate(request.json, schema)
    except ValidationError as e:
        session.close()
        frame = inspect.currentframe()
        abort(400, {'code': frame.f_lineno, 'msg': e.message, 'param': None})

    access_user = session.query(User).filter(
        User.code == api_basic_auth.username()).one()

    if access_user.code == demo_admin_user[
            'code'] or access_user.code == demo_general_user['code']:
        session.close()
        return jsonify({'name': request.json['username']}), 200

    follow = session.query(Follow).filter(
        Follow.user_id == access_user.id).one_or_none()
    new_follow_user = session.query(User).filter(
        User.name == request.json['username'], User.id != access_user.id,
        User.company_id == access_user.company_id).one_or_none()

    if len(request.json['username']) == 0:
        if follow:
            session.delete(follow)
    else:
        if not new_follow_user:
            session.close()
            frame = inspect.currentframe()
            abort(404, {
                'code': frame.f_lineno,
                'msg': '対象ユーザが見つかりませんでした',
                'param': None
            })

        if follow:
            follow.follow_id = new_follow_user.id
        else:
            new_follow = Follow(user_id=access_user.id,
                                follow_id=new_follow_user.id)
            session.add(new_follow)

    session.commit()
    session.close()
    return jsonify({'name': request.json['username']}), 200
示例#20
0
def delete_post_from_db(post_id):
    post = session.query(Post).get(post_id + 1)

    if request.form["action"] == "confirm":
        session.delete(post)
        flash("Your post has been deleted", "danger")
        session.commit()
        return redirect(url_for("posts"))
    else:
        flash("Your post has not been deleted", "danger")
        return redirect(url_for("posts"))
示例#21
0
 def delete(self, list_id, item_id):
     """Delete an item form an existing bucketlist."""
     bucketlist = _get_bucketlist(list_id)
     if bucketlist:
         bucketlistitem = _get_bucketlist_item(item_id, list_id)
         session.delete(bucketlistitem)
         session.commit()
         return {'message': 'BucketlistItem {} has been deleted'
                            .format(item_id)}, 204
     return {'message': 'Bucketlistitem {} could not be found'
                        .format(item_id)}, 404
示例#22
0
 def delete(self, list_id):
     """Delete an existing bucketlist."""
     try:
         bucketlist = _get_bucketlist(list_id)
         session.delete(bucketlist)
         session.commit()
         return {'message': 'Bucketlist {} has been deleted'
                            .format(list_id)}, 200
     except NoResultFound:
         return {'message': 'Bucketlist {} has not been found'
                            .format(list_id)}, 404
示例#23
0
文件: deleteview.py 项目: yeleman/anm
 def delete(self):
     op = self.data[self.box.currentIndex()]
     session.delete(op)
     session.commit()
     self.change_main_context(OperationWidget, account=self.account)
     self.box.removeItem(self.box.currentIndex())
     if len(self.data) == 1:
         self.close()
     else:
         self.data.pop(self.box.currentIndex())
     raise_success(_(u"Deleting"), _(u"Operation succefully removed"))
示例#24
0
def delete_post(id):
    if request.method == "POST":
        post = session.query(Post).get(id)
        if post.author_id == g.user.id:
            session.delete(post)
            session.commit()
            flash("Message deleted!", "success")
        flash("Sorry, you cannot delete that", "danger")
        return redirect(url_for("posts"))

    post = session.query(Post).get(id)
    return render_template("delete_post.html", post=post)
示例#25
0
 def delete(self, username):
     '''Deletes a user and all 
     Attributes:
         username    Username of user
     '''
     user = get_user(username)
     try:
         session.delete(user)
         session.commit()
     except orm_exc.UnmappedInstanceError:
         return 'Unable to delete user: %s' % username
     return 204
示例#26
0
def delete_item(item_name):
    item = session.query(Item).filter_by(title=item_name).one()
    if item.user_id == login_session['user_id']:
        if request.method == 'POST':
            session.delete(item)
            session.commit()
            flash("Item has been deleted.")
            return redirect(url_for('users.display_all'))
        else:
            return render_template('delete_item.html', item_name=item.title)
    else:
        redirect(url_for('users.display_all'))
示例#27
0
文件: api.py 项目: mroswell/posts-api
def delete_post_get(id):
    post = session.query(models.Post).get(id)
    # Check whether the post exists
    # If not return a 404 with a helpful message
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    session.delete(post)
    session.commit()
    return redirect(url_for("posts_get"))
示例#28
0
def delete_quiz_by_id(quiz_id: int):
    """Delete a specific quiz by its id
    """
    quiz = session.query(models.Quiz).filter(models.Quiz.id == quiz_id).first()
    if not quiz:
        raise HTTPException(status_code=400,
                            detail=f'Quiz with id {quiz_id} does not exist')

    session.delete(quiz)
    session.commit()

    return quiz
示例#29
0
def delete(table_id):
    from app import client

    user = session.query(User).filter(User.code == api_basic_auth.username()).one()

    if user.role.name != 'admin':
        session.close()
        frame = inspect.currentframe()
        abort(403, {'code': frame.f_lineno, 'msg': '権限がありません', 'param': None})

    table = session.query(ShiftTable).filter(ShiftTable.id == table_id).one_or_none()

    if table is None:
        session.close()
        frame = inspect.currentframe()
        abort(404, {'code': frame.f_lineno, 'msg': '指定された取り込み済みのシフトはありません', 'param': None})

    if table.company_id != user.company_id:
        session.close()
        frame = inspect.currentframe()
        abort(403, {'code': frame.f_lineno, 'msg': '権限がありません', 'param': None})

    if user.code != demo_admin_user['code']:
        os.remove(table.origin_path)
        os.remove(table.thumbnail_path)

        company_users = session.query(User) \
            .filter(User.company_id == user.company_id,
                    User.token != None,  # is not Noneとかでは正しく比較されない
                    User.id != user.id,
                    User.is_shift_import_notification == True
                    ) \
            .all()

        if len(company_users) != 0:
            tokens = [user.token for user in company_users]
            alert = '{}が{}を削除しました'.format(user.name, table.title)
            res = client.send(tokens,
                              alert,
                              sound='default',
                              badge=1,
                              category='usershift',
                              extra={'updated': DT.strftime(datetime.datetime.now(), '%Y-%m-%d')}
                              )
            print('***************Add Comment*****************')
            print(res.errors)
            print(res.token_errors)
            print('***************Add Comment*****************')

    session.delete(table)
    session.commit()
    session.close()
    return jsonify({'msg': 'OK'}), 200
示例#30
0
def perform_tasks():
    tasks = session.query(Task).all()
    for task in tasks:
        if task.last_invite != None:
            delta = datetime.datetime.now() - task.last_invite
            seconds_passed = delta.total_seconds()
            interval = [
                (task.interval * 60) - (task.interval * 60) * 0.1,
                (task.interval * 60) + (task.interval * 60) * 0.3,
            ]
            random_interval = random.randint(interval[0], interval[1])
            if seconds_passed > random_interval:
                contacts = session.query(Contact).filter(
                    Contact.source_group == task.source_group).all()
                invited_contacts = session.query(Contact).filter(
                    Contact.task == task).all()
                if len(invited_contacts) < task.invites_limit and \
                        len(contacts) > len(invited_contacts):
                    invited = invite_contact(task.id)
                    if invited:
                        task.last_invite = datetime.datetime.now()
                        session.commit()
                else:
                    session.delete(task)
                    session.commit()
                    for adm in config.ADMIN_IDS:
                        bot.send_message(
                            adm, f'<code>Inviting to {task.target_group} '
                            f'from {task.source_group}</code> completed.\n'
                            f'Invited {len(task.invited_contacts)} users.',
                            parse_mode=ParseMode.HTML)
            else:
                continue
        else:
            contacts = session.query(Contact).filter(
                Contact.source_group == task.source_group).all()
            invited_contacts = session.query(Contact).filter(
                Contact.task == task).all()
            if len(invited_contacts) < task.invites_limit and \
                    len(contacts) > len(invited_contacts):
                invite_contact(task.id)
                task.last_invite = datetime.datetime.now()
                session.commit()
            else:
                session.delete(task)
                session.commit()
                for adm in config.ADMIN_IDS:
                    bot.send_message(
                        adm, f'<code> Inviting to {task.target_group} '
                        f'from {task.source_group}</code> completed.\n'
                        f'Invited {len(task.invited_contacts)} users.',
                        parse_mode=ParseMode.HTML)
示例#31
0
def delete_post(post_id):
    post = session.query(Post).get(post_id)
    
    if not current_user.is_authenticated():
        flash("Please log in to delete your posts.")
        return redirect(url_for("posts"))
    elif post.author == current_user:
        session.delete(post)
        session.commit()
        return redirect(url_for("posts"))
    else:
        flash("Please only delete your own posts.")
        return redirect(url_for("posts"))
示例#32
0
    def delete(self):  # 주문 삭제 -> 거의 사용할 일 없을 것임.
        data = Order.parser.parse_args()
        # Orders Table에서 삭제할 레코드 pk 조회
        instance = session.query(models.Order).get(data['pk'])

        # 해당 값이 없다면
        if instance is None:
            return Response(status=404)  # Not Found 에러 코드 전송

        # 행 삭제 및 commit
        session.delete(instance)
        session.commit()
        return Response(status=204)  # 처리 완료 코드 전송
示例#33
0
 def delete(self, list_id):
     """Delete an existing bucketlist."""
     try:
         bucketlist = _get_bucketlist(list_id)
         session.delete(bucketlist)
         session.commit()
         return {
             'message': 'Bucketlist {} has been deleted'.format(list_id)
         }, 200
     except NoResultFound:
         return {
             'message': 'Bucketlist {} has not been found'.format(list_id)
         }, 404
def song_delete(id):
    """ Delete an existing song """
    song = session.query(models.Song).get(id)
    if not song:
        message = "Could not find song with id {}".format(id)
        data = json.dumps({"message": message})

    session.delete(song)
    session.commit()

    message = "File id {} has been deleted.".format(id)
    data = json.dumps({"message": message })
    return Response(data, 200, mimetype="application/json")
示例#35
0
 def delete(self, list_id, item_id):
     """Delete an item form an existing bucketlist."""
     bucketlist = _get_bucketlist(list_id)
     if bucketlist:
         bucketlistitem = _get_bucketlist_item(item_id, list_id)
         session.delete(bucketlistitem)
         session.commit()
         return {
             'message': 'BucketlistItem {} has been deleted'.format(item_id)
         }, 204
     return {
         'message': 'Bucketlistitem {} could not be found'.format(item_id)
     }, 404
示例#36
0
文件: api.py 项目: DesPenny/tuneful
def delete_song(id):
	""" Delete a single song """
	song = session.query(models.Song).get(id)
	if not song:
		message = "Could not find song with id {}".format(id)
		data = json.dumps({"message": message})
		return Response(data, 404, mimetype="application/json")

	session.delete(song)
	session.commit()

	message = "Successfully deleted song with id {}".format(id)
	data = json.dumps({"message": message})
	return Response(data, 200, mimetype="application/json")
示例#37
0
文件: api.py 项目: bb071988/endpoints
def post_delete(id):
    post = session.query(models.Post).get(id)
    # Check whether the post exists
    # if not return a 404 with a message
    if not post:
        return post_not_found(id)
        
    session.delete(post)
    session.commit()
    
    # Return the post as JSON
    data = message = "Post deleted {}".format(id)
    data = json.dumps({"message": message})
    return Response(data, 200, mimetype="application/json")
示例#38
0
def deleteAdopter(key):
    delAdopter = session.query(Adopter).filter_by(id=key).one()

    if request.method == 'POST':
        session.delete(delAdopter)
        session.commit()

        return redirect(url_for('listAdopter'))

    else:
        return render_template('delete.html',
                               viewType="adopter",
                               key=key,
                               name=delAdopter.name)
示例#39
0
def delete_item(bot, update, args):
    if len(args) == 1:
        item = session.query(Item).filter(Item.link == args[0]).first()
        if item:
            session.delete(item)
            session.commit()
            update.message.reply_text("Item deleted from monitoring.")
        else:
            update.message.reply_text("No items found.")
    else:
        update.message.reply_text(
            "Please, send me the link like in the example:\n"
            "/delete <code>[link]</code>",
            parse_mode=ParseMode.HTML)
示例#40
0
文件: api.py 项目: s-ben/tuneful
def songs_delete(id):
    """ Delete songs endpoint """
    # Get the song from the database
    song = session.query(models.Song).get(id)
    # Check to make sure the post exists
    if not song:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    # Return the post as JSON
    data = json.dumps(song.as_dictionary())
    session.delete(song)
    return Response(data, 200, mimetype="application/json")
示例#41
0
def delete(table):
    try:
        model = get_model_by_tablename(table)
        idxs = request.get_json()
        for idx in idxs:
            if idx != 'selectall':
                obj = session.query(model).get(int(idx))
                session.delete(obj)
        flash('Записи удалены', 'delete')
        res = make_response(jsonify({"message": "OK"}), 200)
        logger.info('Deleted {} rows from "{}" table'.format(len(idxs), table))
        return res
    except Exception as e:
        logger.error('Error occurred. Details: {}'.format(e))
        abort(500)
示例#42
0
def delete_post(id):
    """ Delete a single post """
    # check if the post exists, if not return a 404 with a helpful message
    post = session.query(models.Post).get(id)
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    # otherwise just delete the post
    session.delete(post)
    session.commit()

    message = "Successfully deleted post with id {}".format(id)
    data = json.dumps({"message": message})
    return Response(data, 200, mimetype="application/json")
示例#43
0
def deleteAdopter(key):
    delAdopter = session.query(Adopter).filter_by(id = key).one()

    if request.method == 'POST':
        session.delete(delAdopter)
        session.commit()

        return redirect( url_for('listAdopter') )

    else:
        return render_template(
            'delete.html',
            viewType = "adopter",
            key = key,
            name = delAdopter.name
        )
示例#44
0
def post_delete(id):
    """ Single post endpoint """
    # Get the post from the database
    post = session.query(models.Post).get(id)

    # Check whether the post exists
    # If not return a 404 with a helpful message
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    # Return the post as JSON
    data = json.dumps(post.as_dictionary())
    session.delete(post)
    return Response(data, 200, mimetype="application/json")
示例#45
0
def post_delete(id):
    """ Single post endpoint """
    # Get the post from the database
    post = session.query(models.Post).get(id)

    # Check whether the post exists
    # If not return a 404 with a helpful message
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    # Return the post as JSON
    data = json.dumps(post.as_dictionary())
    session.delete(post)
    return Response(data, 200, mimetype="application/json")
示例#46
0
def delete_post(id):
    """ Delete a single post """
    # check if the post exists, if not return a 404 with a helpful message
    post = session.query(models.Post).get(id)
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    # otherwise just delete the post
    session.delete(post)
    session.commit()

    message = "Successfully deleted post with id {}".format(id)
    data = json.dumps({"message": message})
    return Response(data, 200, mimetype="application/json")
示例#47
0
def delete_song(id):
    """ Delete a single song """
    # check if the song exists, if not return a 404 with a helpful message
    song = session.query(models.Song).get(id)
    if not song:
        message = "Could not find song with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    # otherwise just delete the song
    session.delete(song)
    session.commit()

    message = "Successfully deleted song with id {}".format(id)
    data = json.dumps({"message": message})
    return Response(data, 200, mimetype="application/json")
def song_delete(id):
	song = session.query(models.Song).get(id)

	if not song:
		message = "Could not find song with id {}".format(id)
		data = json.dumps({"message":message})
		return Response(data, 404, mimetype="application/json")

	song_file = session.query(models.File).filter_by(id=song.file_id).first()
	print song_file.filename
	os.remove(upload_path(song_file.filename))
	session.delete(song_file)
	session.commit()

	message = "Song with id {} has been deleted".format(id)
	data = json.dumps({"message":message})
	return Response(data, 201, mimetype="application/json")
示例#49
0
def post_delete(id):
    """deletes the post with the given id"""
    # Get the post from the database
    post = session.query(models.Post).get(id)

    # Check whether the post exists
    # If not return a 404 with a helpful message
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    # delete the post with the given id, provided it exists
    session.delete(post)
    session.commit()

    return Response(200, mimetype="application/json")
示例#50
0
def post_delete(id):
    """ Single post endpoint for deletion """
    # Check whether post exists in database
    post = session.query(models.Post).get(id)
    
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")
    
    # Save parameters of post to be deleted to return it in response as confirmation
    #     that post was successfully deleted
    postCopy = post
    session.delete(post)
    session.commit()
    data = json.dumps(postCopy.as_dictionary())
    return Response(data, 200, mimetype="application/json")
def post_delete(id):
    """ Delete single post endpoint """
    post = session.query(models.Post).get(id)
    
    # Check whether the post exists
    # If not return a 404 with a helpful message
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    session.delete(post)
    session.commit()

    message = "Post id {} has been deleted.".format(id)
    data = json.dumps({"message": message}) 
    return Response(data, 200, mimetype="application/json")
示例#52
0
文件: api.py 项目: bharbron/posts
def post_delete(id):
  """ Delete single post endpoint """
  # Get the post from the database
  post = session.query(models.Post).get(id)
  
  # Check whether the post exists
  # If not return a 404 with a helpful message
  if not post:
    message = "Could not find post with id {}".format(id)
    data = json.dumps({"message": message})
    return Response(data, 404, mimetype="application/json")
  
  # Delete the post
  # Then return a 204 No Content with no data
  session.delete(post)
  session.commit()
  return Response(None, 204, mimetype="application/json")
示例#53
0
文件: api.py 项目: annanymouse/posts
def post_delete(id):
    """ Single post endpoint deletion """
    # Delete a post from the database
    post = session.query(models.Post).get(id)

    # Check if the post exists first
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")

    # Delete the post
    session.delete(post)
    session.commit()
    message = "Deleted post with id {}".format(id)
    data = json.dumps({"message": message})
    return Response(data, 204, mimetype="application/json")
示例#54
0
文件: api.py 项目: DesPenny/posts
def post_delete(id):
        # Single post endpoint 
        # Delete the post from the database
        post = session.query(models.Post).get(id)

        # Check whether the post exists
        # If not return a 404 with a helpful message
        if not post:
            message = "Could not find post with id {}".format(id)
            data = json.dumps({"message": message})
            return Response(data, 404, mimetype="application/json")
        session.delete(post)
        session.commit()
        # Return the post as JSON
        success = "Successfully deleted post"
        data = json.dumps({"message": success})
        return Response(data, 204, mimetype="application/json")
示例#55
0
文件: api.py 项目: jlybianto/tuneful
def song_delete(id):
    """ Delete a song """    
    # Get the song file from the database
    file = session.query(models.File).get(id)
    
    # Check whether the song file exists
    # If no, return a 404 with a helpful message
    if not file:
        message = "Could not find song file with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")
    
    # If yes, delete the song from database with confirmation message
    session.delete(song)
    session.commit()
    message = "Deleted song with id {} from database".format(id)
    data = json.dumps({"message": message})
    return Response(data, 200, mimetype="application/json")
示例#56
0
def post_delete(id):
    """ Delete single post """    
    # Get the post from the database
    post = session.query(models.Post).get(id)
    
    # Check whether the post exists
    # If no, return a 404 with a helpful message
    if not post:
        message = "Could not find post with id {}".format(id)
        data = json.dumps({"message": message})
        return Response(data, 404, mimetype="application/json")
    
    # If yes, delete the post from database with confirmation message
    session.delete(post)
    session.commit()
    message = "Deleted post with id {} from database".format(id)
    data = json.dumps({"message": message})
    return Response(data, 200, mimetype="application/json")
示例#57
0
def delete_game(game_id):
    try:
        game = models.Game.query.filter_by(id=game_id).first()
        db.delete(game)

        for score in models.Score.query.filter_by(game_id=game_id):
            db.delete(score)

        db.commit()

        response = {
            "status": {
                "success": True
            }
        }
    except Exception as e:
        response = return_error(e)

    return jsonify(response)
示例#58
0
def deleteCategory(key):
    """Allow an Authorized User to delete a new Category or Process the
    deletion of a Category.

    Args:
        key (int): The primary key of the category.

    Returns:
        For a GET operation returns a View querying whether the user wants to
        delete the Category or cancel and go back to viewing it.

        A successful POST request deletes the Category and redirects to the
        list of Categories.

    """
    # Only an Authenticated User can add delete a category.
    if isActiveSession() is False:
        return redirect(url_for("listCategory"))

    deleteCategory = Category.query.filter_by(id=key).one()

    # If the logged in user did not create this Category then redirect.
    if canAlter(deleteCategory.user_id) is False:
        return redirect(url_for("viewCategory", key=deleteCategory.id))

    # Remove the Category from the Database
    if request.method == "POST":
        session.delete(deleteCategory)
        session.commit()

        flash("Category deleted!")
        # Back to the List of Categories
        return redirect(url_for("listCategory"))
    else:
        # Present options to Delete the Category or Cancel.
        return render_template(
            "generic.html",
            modelType="category",
            viewType=os.path.join("partials", "delete.html"),
            key=key,
            name=deleteCategory.name,
        )
示例#59
0
def deletePuppy(key):
    deleteProfile = session.query(Profile).filter_by(puppy_id = key).one()
    deletePuppy = session.query(Puppy).filter_by(id = key).one()

    if request.method == 'POST':
        session.delete(deleteProfile)
        session.commit()

        session.delete(deletePuppy)
        session.commit()
        flash("Puppy and Profile deleted!")
        return redirect( url_for('listPuppy') )

    else:
        return render_template(
            'delete.html',
            viewType = "profile",
            key = key,
            name = deleteProfile.name
        )