def create_thread(slug): json_data = request.get_json() user = User().get_by_nickname(json_data['author'], hide_id=False) forum = Forum().get_by_slug_with_id(slug) if not (user and forum): return json_response({ "message": "Can't find user or forum" }, 404) if 'slug' in json_data.keys(): thread_exists = Thread.get_serialised_with_forum_user_by_id_or_slug(slug=json_data['slug']) if thread_exists: thread_exists['created'] = format_time(thread_exists['created']) return json_response(thread_exists, 409) thread = Thread.create_and_get_serialized( user_id=user['id'], forum_id=forum['id'], title=json_data['title'], message=json_data['message'], user_nickname=user['nickname'], forum_slug=forum['slug'], created=json_data['created'] if 'created' in json_data else None, slug=json_data['slug'] if 'slug' in json_data else None, ) thread['author'] = user['nickname'] thread['forum'] = forum['slug'] thread['created'] = format_time(thread['created']) return Response( response=json.dumps(thread), status=201, mimetype="application/json" )
def create(): # use @jwt_required and get_jwt_identity() to get the id of the current user. can use it to assign as an id value user_id = get_jwt_identity() file = request.files.get('image') file.filename = secure_filename(file.filename) content = request.form.get('caption') if not user_id or not file or not content: response = { 'message': 'All field were not provided' } return jsonify(response), 400 if not upload_file_to_s3(file): return jsonify({'msg': 'upload to s3 failed'}), 400 post_thread = request.get_json() post_thread = Thread(user_id=user_id, template=file.filename, content=content) post_thread.save() return jsonify({ 'message': 'thread made', 'user': post_thread.user_id, 'template': post_thread.template, 'content': post_thread.content }), 200
def update_thread(slug_or_id): json_data = request.get_json() thread = Thread.get_by_slug_or_id(slug_or_id) if not thread: return json_response({'message': 'Thread not found'}, 404) thread = Thread.update_thread(thread['id'], json_data, thread) thread['created'] = format_time(thread['created']) return json_response(thread, 200)
async def handle_thread_update(request): data = await request.json() thread_slug_or_id = request.match_info['slug_or_id'] message = data.get('message', False) title = data.get('title', False) connection_pool = request.app['pool'] connection = connection_pool.getconn() cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) if not thread_slug_or_id.isdigit(): cursor.execute(Thread.query_get_thread_id(thread_slug_or_id)) result = cursor.fetchone() if not result: connection_pool.putconn(connection) return web.json_response( status=404, data={"message": "Can't find user with id #41\n"}) thread_id = result['id'] else: thread_id = thread_slug_or_id if not title and not message: cursor.execute(Thread.query_get_thread_by_id(thread_id)) thread = cursor.fetchone() thread['created'] = thread['created'].astimezone().isoformat() if thread['slug'] == 'NULL': thread.pop('slug') connection_pool.putconn(connection) return web.json_response(status=200, data=thread) try: cursor.execute(Thread.query_update_thread(thread_id, message, title)) connection.commit() except psycopg2.Error: connection.rollback() connection_pool.putconn(connection) return web.json_response( status=404, data={"message": "Can't find user with id #42\n"}) else: cursor.execute(Thread.query_get_thread_by_id(thread_id)) thread = cursor.fetchone() connection_pool.putconn(connection) if not thread: return web.json_response( status=404, data={"message": "Can't find user with id #42\n"}) thread['created'] = thread['created'].astimezone().isoformat() if thread['slug'] == 'NULL': thread.pop('slug') return web.json_response(status=200, data=thread)
def index(): threads = Thread.select() thread_data = [] for thread in threads: thread = model_to_dict(thread) thread_data.append(thread) return jsonify(thread_data), 200
async def handle_get_posts(request): thread_slug_or_id = request.match_info['slug_or_id'] limit = request.rel_url.query.get('limit', False) desc = request.rel_url.query.get('desc', False) since = request.rel_url.query.get('since', False) sort = request.rel_url.query.get('sort', 'flat') connection_pool = request.app['pool'] connection = connection_pool.getconn() cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cursor.execute(Thread.query_get_thread(thread_slug_or_id)) result = cursor.fetchone() if not result: connection_pool.putconn(connection) return web.json_response( status=404, data={"message": "Can't find user with id #42\n"}) thread_id = result['id'] cursor.execute(Post.query_get_posts(thread_id, since, sort, desc, limit)) result = cursor.fetchall() for item in result: item['created'] = item['created'].astimezone().isoformat() connection_pool.putconn(connection) return web.json_response(status=200, data=result)
def create_thread(slug_or_id): posts_data = request.get_json() thread = Thread.get_by_slug_or_id_with_forum_id(slug_or_id) usernames = [i['author'] for i in posts_data] authors = User.get_user_ids_by_slug(usernames) posts_ids = set([i['parent'] for i in posts_data if 'parent' in i]) if posts_ids: posts = Post.get_posts_by_id_in_thread(thread['id'], posts_ids) if len(posts) != len(posts_ids): return json_response({'message': 'Parent in other thread'}, 409) if len(authors) != len(set(usernames)): return json_response({'message': 'user not found'}, 404) for post in posts_data: for a in authors: if a['nickname'] == post['author'].lower(): post['author_id'] = a['id'] post['author_nickname'] = a['nickname'] post['parent_id'] = post['parent'] if 'parent' in post else 0 if len(thread) > 0: posts = Post.create_posts(posts_data, thread['id'], thread['forum_id']) else: return json_response({'message': 'thread not found'}, 404) for item in posts: item['created'] = format_time(item['created']) return json_response(posts, 201)
async def handle_get(request): forum_slug = request.match_info['slug'] limit = request.rel_url.query.get('limit', 0) desc = request.rel_url.query.get('desc', False) since = request.rel_url.query.get('since', 0) connection_pool = request.app['pool'] connection = connection_pool.getconn() cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cursor.execute(Thread.query_get_threads(forum_slug, limit, desc, since)) result = cursor.fetchall() if not result: cursor.execute(Forum.query_get_forum(forum_slug)) result = cursor.fetchall() connection_pool.putconn(connection) if result: return web.json_response(status=200, data=[]) return web.json_response( status=404, data={"message": "Can't find forum by slug " + forum_slug}) connection_pool.putconn(connection) for item in result: item['created'] = item['created'].astimezone().isoformat() return web.json_response(status=200, data=result)
def get_db_status(): data = { 'forum': Forum.get_count(), 'post': Post.get_count(), 'thread': Thread.get_count(), 'user': User.get_count(), } return json_response(data, 200)
def vote_thread(slug_or_id): post_data = request.get_json() thread_id, user_id = Thread.check_user_and_thread( thread_slug_or_id=slug_or_id, nickname=post_data['nickname']) if not user_id and not thread_id: return json_response({'message': 'Thread OR USER not found'}, 404) thread = Vote.vote_for_thread(user_id, post_data['voice'], thread_id) thread['created'] = format_time(thread['created']) return json_response(thread, 200)
def create(): params = request.form new_course = Course(title=params.get("course_title"), teacher_id=current_user.id) if new_course.save(): # print("new_course.id",new_course.id) new_thread = Thread(course=new_course.id) new_thread.save() # print("new thread", new_thread.id) flash("Successfully Created a Course!", "success") return redirect( url_for("users.show", username=current_user.username, user_id=current_user.id)) # then redirect to profile page else: flash(new_course.errors, "danger") return redirect(url_for("users.show"))
def get_thread_messages(slug_or_id): sort = request.args.get('sort') since = request.args.get('since') limit = request.args.get('limit') desc = request.args.get('desc') thread = Thread.get_by_slug_or_id(slug_or_id) posts = [] if not thread: return json_response({'message': 'Thread not found'}, 404) if sort == "flat" or sort is None: posts = Thread.get_posts_flat_sorted(thread['id'], since, limit, desc) elif sort == "tree": posts = Thread.get_posts_tree_sorted(thread['id'], since, limit, desc) elif sort == "parent_tree": posts = Thread.get_posts_parent_tree_sorter(thread['id'], since, limit, desc) for post in posts: post['created'] = format_time(post['created']) return json_response(posts, 200)
def show(id): thread = Thread.get_or_none(Thread.id == id) if thread: return jsonify({ 'id': thread.id, 'template': thread.template, 'content': thread.content }), 200 else: return jsonify({'message': 'thread not found'}), 418
def __init__(self, data): self.frecuency = data cpu_data = \ list(filter(lambda element: element['ImageURL'] in 'images_icon/cpu.png', data['Children'][0]['Children']))[0]['Children'] self.threads = Thread(cpu_data) self.load = self.get_values(cpu_data, 'Load', 'CPU Total') self.temp_package = self.get_values(cpu_data, 'Temperatures', 'CPU Package')
def generate_threads(user_list): return [ Thread(users=[user_list[0], user_list[1]], messages=[ Message(content=f'Hi {user_list[1].first_name}', user_id=user_list[0].id), Message(content=f'Hi {user_list[0].first_name}', user_id=user_list[1].id), Message(content='Can I borrow your ladder please?', user_id=user_list[0].id) ]), Thread(users=[user_list[0], user_list[2]], messages=[ Message(content=f'Hi {user_list[0].first_name}', user_id=user_list[2].id), Message(content=f'Hi {user_list[2].first_name}', user_id=user_list[0].id), Message(content='Can I borrow your speakers please?', user_id=user_list[2].id) ]) ]
def destroy(id): thread = Thread.get_by_id(id) if thread.delete_instance(recursive=True): return jsonify({ 'message': "thread deleted" }), 200 else: er_msg = [] for error in thread.errors: er_msg.append(error) return jsonify({'message': er_msg}), 418
async def handle_posts_create(request): data = await request.json() thread_slug_or_id = request.match_info['slug'] connection_pool = request.app['pool'] connection = connection_pool.getconn() cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cursor.execute(Thread.query_get_thread_forum(thread_slug_or_id)) result = cursor.fetchone() if not result: connection_pool.putconn(connection) return web.json_response( status=404, data={"message": "Can't find user with id #42\n"}) thread_id = result['id'] forum = result['forum'] if len(data) == 0: connection_pool.putconn(connection) return web.json_response(status=201, data=[]) result = None try: cursor.execute(Post.query_create_post(thread_id, data)) result = cursor.fetchall() connection.commit() except psycopg2.Error as e: connection.rollback() error = psycopg2.errorcodes.lookup(e.pgcode) connection_pool.putconn(connection) if error == 'NOT_NULL_VIOLATION': return web.json_response( status=409, data={"message": "Can't find user with id #42\n"}) else: return web.json_response( status=404, data={"message": "Can't find user with id #42\n"}) else: connection_pool.putconn(connection) for i in range(len(result)): data[i]['created'] = result[i]['created'].astimezone().isoformat() data[i]['id'] = result[i]['id'] data[i]['forum'] = forum data[i]['thread'] = int(thread_id) return web.json_response(status=201, data=data)
async def handle_get_details(request): thread_slug_or_id = request.match_info['slug_or_id'] connection_pool = request.app['pool'] connection = connection_pool.getconn() cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cursor.execute(Thread.query_get_thread(thread_slug_or_id)) result = cursor.fetchone() if not result: connection_pool.putconn(connection) return web.json_response( status=404, data={"message": "Can't find user with id #42\n"}) data = result data['created'] = data['created'].astimezone().isoformat() connection_pool.putconn(connection) return web.json_response(status=200, data=data)
def upload(user_id, course_title, post_id): user = User.get_or_none(User.id == user_id) course = Course.get_or_none(Course.title == course_title) thread = Thread.get_or_none(Thread.course_id == course.id) post = Post.get_or_none(Post.file_path != 'NULL', Post.thread_id == thread.id) params = request.form title = params.get("title") info = StudentCourse.get_or_none(StudentCourse.student_id == user_id, StudentCourse.course_name_id == course.id) if info: if current_user.id == user.id: # We check the request.files object for a user_file key. (user_file is the name of the file input on our form). If it's not there, we return an error message. if "assignment" not in request.files: flash("No file provided!", "danger") return redirect(url_for('posts.show', course_name=course_title, user_id=current_user.id, post_id = post.id)) # If the key is in the object, we save it in a variable called file. file = request.files["assignment"] # we sanitize the filename using the secure_filename helper function provided by the werkzeurg.security module. # file.filename = secure_filename(file.filename) # get path to image on S3 bucket using function in helper.py file_path = upload_file_to_s3(file, user.username) new_assignment = Assignment(title=title, info_id=info.id, file_path=file_path, post_id=post.id) if new_assignment.save(): flash("Successfully uploaded!","success") return redirect(url_for('posts.show', course_name=course_title, user_id=current_user.id, post_id = post.id)) # then redirect to profile page else: flash("Upload failed. Please try again!", "danger") return redirect(url_for('posts.show', course_name=course_title, user_id=current_user.id, post_id = post.id)) else: flash("Cannot upload assignments for other users", "danger") return redirect(url_for('posts.show', course_name=course_title, user_id=current_user.id, post_id = post.id)) else: flash("Failed to upload!", "danger") return redirect(url_for('posts.show', course_name=course_title, user_id=current_user.id, post_id = post.id))
def get_threads_list(slug): limit = request.args.get('limit') since = request.args.get('since') desc = request.args.get('desc') threads = Thread.get_threads_list(slug, limit, since, desc) forum = Forum().get_by_slug(slug) for thread in threads: thread['created'] = format_time(thread['created']) if forum: return Response( response=json.dumps(threads), status=200, mimetype="application/json" ) else: return json_response( {'message': 'not found'}, 404 )
def upload(thread_id): # if not 'image' in request.files: # return jsonify({'msg': 'no image given'}), 400 file = request.files.get('image') file.filename = secure_filename(file.filename) if not upload_file_to_s3(file): return jsonify({'msg': 'upload to s3 failed'}), 400 thread = Thread.get_or_none(Thread.id == thread_id) thread.template = file.filename # thread = Thread(template=file.filname) thread.save() # os.remove(temp_storage) return jsonify({'msg': 'upload to s3 success'}), 200
def get_info(cls, post_id, related): sql = """ SELECT m.nickname as author, p.created as created, f.slug as forum, p.id as id, p.message as message, p.thread_id as thread, p.parent_id as parent, p.is_edited as isEdited FROM {tbl_name} AS p JOIN {u_tbl_name} AS m ON m.id = p.user_id JOIN {t_tbl_name} AS t ON t.id = p.thread_id JOIN {f_tbl_name} AS f ON f.id = t.forum_id WHERE p.id = %(post_id)s """.format_map({ 'tbl_name': cls.tbl_name, 'u_tbl_name': User.tbl_name, 't_tbl_name': Thread.tbl_name, 'f_tbl_name': Forum.tbl_name, }) post = DbConnector.execute_get(sql, {'post_id': post_id}) if post: post[0]['isEdited'] = post[0]['isedited'] post[0]['created'] = format_time(post[0]['created']) data = {'post': post[0] if post else None} if related and post: related = related.split(',') if 'user' in related: data['author'] = User().get_by_nickname(post[0]['author']) if 'thread' in related: data[ 'thread'] = Thread.get_serialised_with_forum_user_by_id_or_slug( id=post[0]['thread']) data['thread']['created'] = format_time( data['thread']['created']) if 'forum' in related: data['forum'] = Forum().get_by_slug(post[0]['forum']) return data
def show(course_name, user_id, post_id): user = User.get_or_none(User.id == user_id) current_course = Course.get_or_none(Course.title == course_name) thread = Thread.get_or_none(Thread.course_id == current_course.id) if user.role.role == 'Teacher': submitted_assignments = [] for assignment in Assignment.select().where(Assignment.post_id == post_id): submitted_assignments.append(assignment) if user.role.role == 'Student': info = StudentCourse.get_or_none(StudentCourse.student_id == user.id, StudentCourse.course_name_id == current_course.id) submitted_assignments = Assignment.get_or_none(Assignment.info_id == info.id) assignment_post = [] week_num = [] i = 1 for post in Post.select().where(Post.thread_id == thread.id): if post.file_path: assignment_post.append(post) week_num.append(i) i += 1 grades = [] for grade in Grade.select(): grades.append(grade) assignment_week = dict(zip(week_num, assignment_post)) print(str(assignment_week)) # for assignment in Assignment.select().where() return render_template('posts/show.html', course_title=course_name, user_id=user_id, post_id=post_id, assignment_week=assignment_week, submitted_assignments=submitted_assignments, grades=grades) # is_student= user.role == "student"
def update(id): thread = Thread.get_by_id(id) new_thread = request.get_json() thread.template = new_thread['template'] thread.content = new_thread['content'] if thread.save(): return jsonify({ 'message': 'successfully updated thread', 'status': 'success', 'updated_thread': { 'id': thread.id, 'template': thread.template, 'content': thread.content, }, }), 200 else: er_msg = [] for error in thread.errors: er_msg.append(error) return jsonify({'message': er_msg}), 418
async def handle_forum_create(request): data = await request.json() forum = request.match_info['slug'] forum_slug = data.get('forum', False) if not forum_slug: thread = Thread(**data, forum=forum) else: thread = Thread(**data) connection_pool = request.app['pool'] connection = connection_pool.getconn() cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) thread_id = None try: cursor.execute(thread.query_create_thread()) thread_id = cursor.fetchone()['id'] connection.commit() except psycopg2.Error as e: connection.rollback() cursor.execute(Thread.query_get_thread_by_slug(data['slug'])) result = cursor.fetchone() connection_pool.putconn(connection) if result: result['created'] = result['created'].astimezone().isoformat() return web.json_response(status=409, data=result) else: return web.json_response(status=404, data={}) else: cursor.execute(Thread.query_get_thread_by_id(thread_id)) result = cursor.fetchone() result['created'] = result['created'].astimezone().isoformat() if result['slug'] == 'NULL': result.pop('slug') connection_pool.putconn(connection) return web.json_response(status=201, data=result)
def get_thread_details(slug_or_id): thread = Thread.get_by_slug_or_id(slug_or_id) if thread: thread['created'] = format_time(thread['created']) return json_response(thread, 200) return json_response({'message': 'thread not found'}, 404)