def all_shell(): type = request.args.get("type") song_name = request.args.get("song_name") tag = request.args.get("tag") session = db_session() songs = session.query(Song).filter(song_name == None or Song.name == song_name).all() # tags = [session.queiry(ShellTag).filter(ShellTag.tag_id == tag_id) for tag_id in # session.query(Tag).filter(tag==None or Tag.content==tag).all()] shells_result = [] if song_name is not None: for song in songs: shells_tmp = session.query(Shell).filter(Shell.song_id == song.id).all() for shell in shells_tmp: shells_result.append(shell) if tag is not None: tag_id = session.query(Tag.id).filter(Tag.content==tag).order_by(func.random()).limit(1).scalar() print tag_id if tag_id is not None: shell_tags = session.query(ShellTag).filter(ShellTag.tag_id == tag_id).order_by(func.random()).limit( 5).all() for shell_tag in shell_tags: shells_result.append(session.query(Shell).filter(Shell.id == shell_tag.shell_id).first()) shells = [] if type == "all": shells = [shell.to_json() for shell in shells_result] elif type == "random": shells = choice(shells_result).to_json() if len(shells_result) > 0 else [] session.close() return jsonify(shells)
def changeReader(): rdID = request.form.get('rdID', False) rdName = request.form.get('rdName', False) rdSex = request.form.get('rdSex', False) rdType = request.form.get('rdType', False) rdDept = request.form.get('rdDept', False) rdPhone = request.form.get('rdPhone', False) rdEmail = request.form.get('rdEmail', False) if not (rdID and rdName and rdSex and rdType and rdDept and rdPhone and rdEmail): return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() r: TBReader = session.query(TBReader).filter( TBReader.rdID == rdID).one() r.rdName = rdName r.rdSex = rdSex r.rdType = rdType r.rdDept = rdDept r.rdPhone = rdPhone r.rdEmail = rdEmail session.commit() session.close() except NoResultFound: return {'status': 0, 'message': '未找到指定的借书证'} except MultipleResultsFound: return {'status': 0, 'message': '借书证数据异常'} except OperationalError: return {'status': 0, 'message': '输入的数据可能有误'} else: return {'status': 1, 'message': '指定的借书证修改成功'}
def continue_status(): bkID = request.form.get('bkID', False) if bkID is False: return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() bk: TBBook = session.query(TBBook).filter(TBBook.bkID == bkID).one() if bk.bkStatus != '借出': return {'status': 0, 'message': '图书不是借出状态, 不能办理续借'} bo: TBBorrow = session.query(TBBorrow).filter( TBBorrow.bkID == bkID, TBBorrow.IsHasReturn == 0).one() r: TBReader = session.query(TBReader).filter( TBReader.rdID == bo.rdID).one() if r.rdStatus in ('挂失', '注销'): return {'status': 0, 'message': '借书证状态为挂失或注销, 不能办理续借'} rt: TBReaderType = TBReaderType.query.filter( TBReaderType.rdType == r.rdType).one() if bo.IdContinueTimes >= rt.CanContinueTimes: return {'status': 0, 'message': '续借次数已用完, 不能办理续借'} session.close() return { 'status': 1, 'message': '该书可以办理续借, 借书证为: ' + str(r.rdID) + ', 请借阅管理员检查读者出示的借书证是否一致' } except NoResultFound: return {'status': 0, 'message': '没有查询到相应的借阅记录'} except MultipleResultsFound: return {'status': 0, 'message': '借阅数据异常'} except OperationalError: return {'status': 0, 'message': '输入的数据可能有误'}
def continueBorrow(): bkID = request.form.get('bkID', False) if bkID is False: return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() bo: TBBorrow = session.query(TBBorrow).filter( TBBorrow.bkID == bkID, TBBorrow.IsHasReturn == 0).one() r: TBReader = session.query(TBReader).filter( TBReader.rdID == bo.rdID).one() rt: TBReaderType = TBReaderType.query.filter( TBReaderType.rdType == r.rdType).one() bo.IdContinueTimes += 1 bo.IdDateRetPlan += datetime.timedelta(days=rt.CanLendDay) session.commit() session.close() except NoResultFound: return {'status': 0, 'message': '没有查询到相应的借阅记录'} except MultipleResultsFound: return {'status': 0, 'message': '借阅数据异常'} except OperationalError: return {'status': 0, 'message': '输入的数据可能有误'} else: return {'status': 1, 'message': '续借办理成功'}
def get_itemInfo(cls, item_name): item_info = {} #get item_info session = db_session() item_info = session.query(SystemModule).filter_by(item_name = item_name).first() and session.query(SystemModule).filter_by(item_name = item_name).first().item_info or None session.close() return item_info
def changeBook(): bkID = request.form.get('bkID', False) bkName = request.form.get('bkName', False) bkAuthor = request.form.get('bkAuthor', False) bkPress = request.form.get('bkPress', False) if not (bkName and bkAuthor and bkPress and bkID): return {'status': 0, 'message': '传入数据不全'} try: session = db_session() b: TBBook = session.query(TBBook).filter(TBBook.bkID == bkID).one() b.bkName = bkName b.bkAuthor = bkAuthor b.bkPress = bkPress session.commit() session.close() except NoResultFound: return {'status': 0, 'message': '没有查询到相应的图书'} except MultipleResultsFound: return {'status': 0, 'message': '图书数据异常'} except OperationalError: return {'status': 0, 'message': '输入的数据可能有误'} else: return {'status': 1, 'message': '修改成功'}
def extract_messages(extractor, messages): """ Extract the given messages into the db. Args: extractor: object - the extractor to use to extract the messages messages: list - a list of messages to store in the db """ session = models.db_session() ids = [message['id'] for message in messages] existing = session.query(models.Email.external_id) \ .filter(models.Email.external_id.in_(ids)) \ .all() existing_ids = [item[0] for item in existing] for message in messages: # if we already have this message in the db # we don't need to recreate it if message['id'] in existing_ids: continue email = extractor.generate_email(message['id'], message['threadId']) if not email: continue session.add(email) # commit the records session.commit()
def new_user(): username = request.json.get('name') pwd = request.json.get('password') email = request.json.get('email') code = 1 message = "注册成功" user = None if username is None or pwd is None or email is None: code=0 message = "用户名/密码不能为空" elif User.query.filter_by(email=email).first() is not None: code=0 message = "用户已存在!" else: common.send_mail(email, "您已成功注册海螺!") user = User(name=username, password=pwd, email=email) session = db_session() session.add(user) session.commit() session.close() user = session.merge(user) user = user.to_json() return jsonify({ "user":user, "info":generate_return_info(code,message) })
def deleteReaderType(): rdType = request.form.get('rdType', False) rdTypeName = request.form.get('rdTypeName', False) if rdType is False and rdTypeName is False: return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() if rdType and rdTypeName: rt: TBReaderType = session.query(TBReaderType).filter( TBReaderType.rdType == rdType, TBReaderType.rdTypeName == rdTypeName).one() if rdType and rdTypeName is False: rt: TBReaderType = session.query(TBReaderType).filter( TBReaderType.rdType == rdType).one() if rdType is False and rdTypeName: rt: TBReaderType = session.query(TBReaderType).filter( TBReaderType.rdTypeName == rdTypeName).one() session.delete(rt) session.commit() session.close() except NoResultFound: return {'status': 0, 'message': '未找到指定的读者类型'} except MultipleResultsFound: return {'status': 0, 'message': '读者类型数据异常'} except OperationalError: return {'status': 0, 'message': '输入的数据类型可能有误'} else: return {'status': 1, 'message': '指定的读者类型删除成功'}
def changeReaderType(): rdType = request.form.get('rdType', False) rdTypeName = request.form.get('rdTypeName', False) CanLendQty = request.form.get('CanLendQty', False) CanLendDay = request.form.get('CanLendDay', False) CanContinueTimes = request.form.get('CanContinueTimes', False) PunishRate = request.form.get('PunishRate', False) DateValid = request.form.get('DateValid', False) if not (rdType and rdTypeName and CanLendQty and CanLendDay and CanContinueTimes and PunishRate and DateValid): return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() rt: TBReaderType = session.query(TBReaderType).filter( TBReaderType.rdType == rdType).one() rt.rdTypeName = rdTypeName rt.CanLendQty = CanLendQty rt.CanLendDay = CanLendDay rt.CanContinueTimes = CanContinueTimes rt.PunishRate = PunishRate rt.DateValid = DateValid session.commit() session.close() except NoResultFound: return {'status': 0, 'message': '未找到指定的读者类型'} except MultipleResultsFound: return {'status': 0, 'message': '读者类型数据异常'} except OperationalError: return {'status': 0, 'message': '输入的数据类型可能有误'} else: return {'status': 1, 'message': '指定的读者类型修改成功'}
def add_task(list_id): '''Add task for the current user''' ws = existing_web_session() dbs = db_session(close=True) form = forms.AddTask() post = request.POST.decode() if not dbs.query(Todo).filter(Todo.id==list_id).all(): return { 'message':'This is not the list you are looking for.', 'ws':ws } task_name = cgi.escape(post['task']) task = Task(name=task_name,description='',todo_list_id=list_id, creator=ws['user_id'],reviewer=ws['user_id']) dbs.add(task) try: dbs.commit() except: dbs.rollback() return "-1" #tasks = dbs.query(Task).filter(Task.user_created_id == ws['user_id']).all() return json.dumps(task.get_details())
def addTask(list_id): '''Show a specific list''' ws = existing_web_session() dbs = db_session(close=True) attrs = {} if not dbs.query(Todo).filter(Todo.id==list_id).all(): return { 'message':'This is not the list you are looking for.', 'ws':ws } tasks = dbs.query(Task).filter(Task.user_created_id == ws['user_id'], Task.todo_list_id == list_id).all() if tasks: for count,task in enumerate(tasks): attrs[count] = {'task_id':task.id} task.date_created = task.date_created.strftime("%Y-%m-%d %H:%M:%S") form = forms.AddTask() return { 'list_id':list_id, 'tasks':tasks, 'attrs':attrs, 'form':form, 'ws':ws }
def addBorrow(): rdID = request.form.get('rdID', False) bkID = request.form.get('bkID', False) op = request.cookies.get('uid', False) if rdID is False and bkID is False: return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() b = TBBorrow(rdID=rdID, bkID=bkID, OperatorLend=op, IdContinueTimes=0) r: TBReader = session.query(TBReader).filter( TBReader.rdID == rdID).one() rt: TBReaderType = session.query(TBReaderType).filter( TBReaderType.rdType == r.rdType).one() b.IdDateOut = datetime.datetime.now() b.IdDateRetPlan = datetime.datetime.now() + datetime.timedelta( days=rt.CanLendDay) session.add(b) r.rdBorrowQty += 1 bk: TBBook = session.query(TBBook).filter(TBBook.bkID == bkID).one() bk.bkStatus = '借出' session.commit() session.close() except OperationalError: return {'status': 0, 'message': '输入的数据可能有误'} except (NoResultFound, MultipleResultsFound): return {'status': 0, 'message': '后台数据异常'} else: return {'status': 1, 'message': '借书办理成功'}
def addReaderType(): rdType = request.form.get('rdType', False) rdTypeName = request.form.get('rdTypeName', False) CanLendQty = request.form.get('CanLendQty', False) CanLendDay = request.form.get('CanLendDay', False) CanContinueTimes = request.form.get('CanContinueTimes', False) PunishRate = request.form.get('PunishRate', False) DateValid = request.form.get('DateValid', False) if not (rdType and rdTypeName and CanLendQty and CanLendDay and CanContinueTimes and PunishRate and DateValid): return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() rt = TBReaderType(rdType=rdType, rdTypeName=rdTypeName, CanLendQty=CanLendQty, CanLendDay=CanLendDay, CanContinueTimes=CanContinueTimes, PunishRate=PunishRate, DateValid=DateValid) session.add(rt) session.commit() session.close() except OperationalError: return {'status': 0, 'message': '输入的数据类型可能有误'} except IntegrityError: return {'status': 0, 'message': '读者类型编号或读者类型名重复'} else: return {'status': 1, 'message': '新的读者类型添加成功'}
def addReader(): rdID = request.form.get('rdID', False) rdName = request.form.get('rdName', False) rdSex = request.form.get('rdSex', False) rdType = request.form.get('rdType', False) rdDept = request.form.get('rdDept', False) rdPhone = request.form.get('rdPhone', False) rdEmail = request.form.get('rdEmail', False) if not (rdID and rdName and rdSex and rdType and rdDept and rdPhone and rdEmail): return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() r = TBReader(rdID=rdID, rdName=rdName, rdSex=rdSex, rdType=rdType, rdDept=rdDept, rdPhone=rdPhone, rdEmail=rdEmail) session.add(r) session.commit() session.close() except IntegrityError: return {'status': 0, 'message': '已存在相同的借书证编号, 无法重新创建'} except OperationalError: return {'status': 0, 'message': '输入的数据可能有误'} else: return {'status': 1, 'message': '新借书证创建成功'}
def check_user_exists(cls, username): session = db_session() try: user = session.query(Users).filter_by(username=username).first() return user except Exception, e: return '{0}:{1}'.format(type(e), e)
def view_perks(): ws = existing_web_session() dbs = db_session(close=True) return { 'ws':ws }
def remove_article(): uid = request.values.get('id') article = BotArticle.query.filter_by(uid=uid).first() if article: session = db_session() article.status = -1 session.commit() return jsonify(code=0)
def follower(): user_id = g.user.id session = db_session() follower_ids = session.query(Follow.follower_id).filter(Follow.follow_id == user_id).all() followers = [] for follower_id in follower_ids: followers.append(session.query(User).filter(User.id == follower_id[0]).first().to_json()) session.close() return jsonify(followers)
def insert_menu(cls, menu_info): session = db_session() if menu_info is not None: menu = Menu(menu_code= menu_info.menu_code, menu_name= menu_info.menu_name, parent_code= menu_info.parent_code, cid= menu_info.cid, url= menu_info.url, status= 1, orderby= menu_info.orderby, remark= menu_info.remark, icon= menu_info.icon ) session.add(menu) session.commit() session.close() return True
def my_collection(): user_id = g.user.id type = request.args.get("type") session = db_session() usrs = session.query(UserShellRelationship).filter(UserShellRelationship.user_id == user_id, UserShellRelationship.type == ("like_collection" or type) ) shells = [] for usr in usrs: shells.append(session.query(Shell).filter(Shell.id == usr.shell_id).first().to_json()) return jsonify(shells)
def send_to_cutt(): name = request.values.get('name') bot = bots.running_bots.get(name) app_id = '324160' if not bot else bot.app_id uid = request.values.get('id') if uid: article = BotArticle.query.filter_by(uid=uid).first() if article: cutt.post_article(app_id, article.title, article.content) # resp = requests.get(settings.QINIU_ROOT + article.key + ".gz") # if resp.ok: # content = zlib.decompress(resp.content).decode('utf-8') # # cutt.post_draft(article.title, content, article.cover) # article.status = 1 # db_session().commit() article.status = 1 db_session().commit() return jsonify(code=0)
def get_notice(): user_id = g.user.id session = db_session() notice_results = [notice.to_json() for notice in session.query(Notice).filter(Notice.receiver_id == user_id).all()] notices = [] for notice in notice_results: notices.append(notice) session.query(Notice).filter(Notice.receiver_id == user_id).delete(synchronize_session=False) try: session.commit() finally: session.close() return jsonify(notices)
def test(id): session = db_session() # tags = [tag.content for tag in [session.query(Tag).filter(Tag.id == tag_id).all() for tag_id in # session.query(ShellTag).filter(ShellTag.shell_id == id).all()]] # tag_ids = session.query(ShellTag.tag_id).filter(ShellTag.shell_id == id).all() tags_result = [session.query(Tag.content).filter(Tag.id == tag_id[0]).first() for tag_id in session.query(ShellTag.tag_id).filter(ShellTag.shell_id == id).all()] session.close() tags = [] for tag in tags_result: tags.append(tag[0]) print tags return jsonify({"tags": tags})
def login(username, password): dbs = db_session(close=True) user = dbs.query(User).filter(User.username == username).first() if user and user.password == password: ws = web_session() ws['username'] = username ws['user_id'] = user.id return "success" return "fail"
def finish_task(task_id): '''Finish task for the current user''' dbs = db_session(close=True) post = request.POST.decode() dbs.query(Task).filter_by(id = post['task_id']).update({"date_completed": datetime.datetime.now()}) try: dbs.commit() except: dbs.rollback() return "-1" return 'success'
def new_song(): name = request.json.get('name') singer = request.json.get('singer_name') url = request.json.get('url') print name, singer, url song = Song(name=name, singer=singer, url=url) session = db_session() session.add(song) try: session.commit() finally: session.close() song = session.merge(song) return jsonify(song.to_json())
def view_shell(id): session = db_session() shell = session.query(Shell).filter(Shell.id == id).first() code = 1 message = u"操作成功" if shell is None: shell = None code = 0 message = u"不存在的海螺!" else: shell = shell.to_json() return jsonify({ "shell": shell, "info": generate_return_info(code, message) })
def profile(): ws = existing_web_session() dbs = db_session(close=True) num_lists = len(dbs.query(Todo).filter( Todo.owner_id == ws['user_id']).all()) num_tasks = len(dbs.query(Task).filter( Task.user_created_id == ws['user_id']).all()) return { 'ws':ws, 'num_lists':num_lists, 'num_tasks': num_tasks, 'num_perks': 2}
def add_tag(): shell_id = request.json.get("shell_id") tag_ids = request.json.get("tag_id") session = db_session() session.query(ShellTag).filter(ShellTag.shell_id == shell_id).delete(synchronize_session=False) for tag_id in tag_ids: session.add(ShellTag(shell_id=shell_id, tag_id=tag_id)) shell = session.query(Shell).filter(Shell.id == shell_id).first() try: session.commit() finally: session.close() info = generate_return_info(1, "操作成功") return jsonify({ "shell": shell.to_json(), "info": info})
def edit_profile(): name = request.json.get("name") password = request.json.get("password") user = g.user user.name = name user.password = password session = db_session() session.add(user) try: session.commit() finally: session.close() common.send_mail(g.user.email, "您已成功修改个人信息:)") return jsonify({ "user": user.to_json(), "info": generate_return_info(1, "操作成功") })
def others_page(id): session = db_session() user_name = session.query(User.name).filter(User.id == id).scalar() shell_num = session.query(func.count(Shell.id)).filter(Shell.user_id == id, Shell.type == 1).scalar() shells = [shell.to_json() for shell in session.query(Shell).filter(Shell.user_id == id, Shell.type == 1)] follower_num = session.query(func.count(Follow.id)).filter(Follow.follow_id == id).scalar() follow_num = session.query(func.count(Follow.id)).filter(Follow.follower_id == id).scalar() session.close() return jsonify({ "user": { "name": user_name, "shell_num": shell_num, "follow_num": follow_num, "fan_num": follower_num }, "shell": shells })
def get_menu(cls): menu = [] session = db_session() #get pnode menu_code pnodes = sorted(session.query(Menu).filter_by(parent_code = 'system', status = 1).all(), key = lambda menu: menu.orderby) #get node menu_code for pnode in pnodes: nodes = sorted(session.query(Menu).filter_by(parent_code = pnode.menu_code, status = 1).all(), key = lambda menu: menu.orderby) if nodes is not None: nodeInfo = cls.to_json(pnode) nodeInfo['cnode'] = [] for node in nodes: if nodes is not None: nodeInfo['cnode'].append(cls.to_json(node)) menu.append(nodeInfo) session.close() return menu
def replaceReader(): rdID = request.form.get('rdID', False) if rdID is False: return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() r: TBReader = session.query(TBReader).filter( TBReader.rdID == rdID).one() if r.rdStatus == '挂失': r.rdStatus = '注销' rdID_n = rdID + str(randint(0, 10)) rn = TBReader(rdID=rdID_n, rdName=r.rdName, rdSex=r.rdSex, rdType=r.rdType, rdDept=r.rdDept, rdPhone=r.rdPhone, rdEmail=r.rdEmail, rdDateReg=r.rdDateReg, rdPhoto=r.rdPhoto, rdBorrowQty=r.rdBorrowQty, rdPwd=r.rdPwd, rdAdminRoles=r.rdAdminRoles) session.add(rn) session.commit() bl = session.query(TBBorrow).filter(TBBorrow.rdID == rdID).all() for i in bl: i.rdID = rdID_n session.commit() session.close() return {'status': 1, 'message': '补办成功', 'new_rdID': rdID_n} else: session.close() return {'status': 0, 'message': '该借书证状态不是挂失, 无法办理补办'} except NoResultFound: return {'status': 0, 'message': '未找到指定的借书证'} except MultipleResultsFound: return {'status': 0, 'message': '借书证数据异常'} except OperationalError: return {'status': 0, 'message': '输入的数据可能有误'} except IntegrityError: return {'status': 0, 'message': '随机产生的新编号与数据库现有的借书证号出现重复, 请再次点击办理按钮'}
def register_post(): post = request.POST.decode() form = forms.RegisterForm(post) dbs = db_session(close=True) #Check if username exists username = post['username'].strip() user = dbs.query(User).filter(User.username == username).first() if user: return { 'error':'Username already in use', 'form':form } fd = form_filter(form.data, [ 'username', 'password' ]) user = User(**fd) dbs.add(user) try: dbs.commit() except: return { 'form':form, 'error':'You broke me :(' } else: if login(post['username'].strip(), post['password']) == 'success': return "success" else: return "fail"
def deleteBook(): bkID = request.form.get('bkID', False) if bkID is False: return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() b: TBBook = session.query(TBBook).filter(TBBook.bkID == bkID).one() session.delete(b) session.commit() session.close() except NoResultFound: return {'status': 0, 'message': '没有查询到相应的图书'} except MultipleResultsFound: return {'status': 0, 'message': '图书数据异常'} except OperationalError: return {'status': 0, 'message': '输入的数据可能有误'} else: return {'status': 1, 'message': '指定的图书删除成功'}
def todolists_post(): '''Process add new list request''' ws = existing_web_session() dbs = db_session(close=True) post = request.POST.decode() form = forms.AddTodo() todo_name = cgi.escape(post['todo_list']) todo = Todo(owner_id=ws['user_id'], name=todo_name) dbs.add(todo) try: dbs.commit() except: dbs.rollback() return "-1" return json.dumps(todo.get_details())
def changePwd(): uid = request.form.get('uid', False) old_pwd = request.form.get('old_pwd', False) new_pwd = request.form.get('new_pwd', False) if not (uid and old_pwd and new_pwd): return {'status': 0, 'message': '传入数据不完整'} try: session = db_session() r: TBReader = session.query(TBReader).filter( TBReader.rdID == uid, TBReader.rdPwd == old_pwd).one() r.rdPwd = new_pwd session.commit() session.close() except NoResultFound: return {'status': 0, 'message': '旧密码错误'} except MultipleResultsFound: return {'status': 0, 'message': '用户数据异常'} else: return {'status': 1, 'message': '密码修改成功, 请重新登录'}
def todolists(): '''Show all todo lists''' dbs = db_session(close=True) ws = existing_web_session() form = forms.AddTodo() todo_lists = dbs.query(Todo).filter(Todo.owner_id == ws['user_id']).all() if not todo_lists: return { 'form':form, 'ws':ws, 'message':'You don\'t have any lists yet :(' } return { 'form':form, 'todo_lists':todo_lists, 'ws':ws }
def doLogin(): '''Login''' post = request.POST.decode() form = forms.LoginForm(post) dbs = db_session(close=True) username = post['username'].strip() password = post['password'] user = dbs.query(User).filter(User.username == username).first() if user and user.password == password: ws = web_session() ws['username'] = username ws['user_id'] = user.id return "success" #return json.dumps({"output" : "success"}) return "fail"
from flask import Flask, session, render_template, request, redirect from models import db_session, Club, Member, FamilyMember, MemberClubJoin s = db_session() app = Flask(__name__) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() @app.route("/") def hello(): clubs = s.query(Club).order_by(Club.name).all() return render_template("index.html", clubs=clubs) @app.route("/member/<int:member_id>") def member(member_id): clubs = s.query(Club).order_by(Club.name).all() member = s.query(Member).filter(Member.id == member_id).first() return render_template("members_display.html", clubs=clubs, member=member)
def upload_video(): post = request.POST.decode() ws = existing_web_session() form = forms.UploadForm() dbs = db_session(close=True) vid_types = ('.mp4','.wmv','.mov','.m4v') img_types = ('.jpg','.png','.gif') new_file = post['uploaded_file'] #Check for upload pressed with no file selected. if not new_file: return { "message":"No file was selected. Please try again.", "ws":ws, 'form':form } name,ext = os.path.splitext(new_file.filename) name = str(uuid.uuid4()) if ext in vid_types: OUTPUT_PATH = config.VIDEO_PATH elif ext in img_types: OUTPUT_PATH = config.IMAGE_PATH if not os.path.exists(OUTPUT_PATH): os.makedirs(OUTPUT_PATH) chunk_size = 68000 raw = '' if new_file.file: while True: chunk = new_file.file.read(chunk_size) if not chunk: break raw+=chunk with open(OUTPUT_PATH+'/'+name+ext, 'w') as f: f.write(raw) #Check extension and decide on tpye of reward to create if ext in vid_types: encode = encode_video(name+ext) reward = VideoReward(name='New Video Reward!', owner_id=ws['user_id']) reward.set_reward_values(media_url=name) elif ext in img_types: reward = ImageReward(name='New Image Reward!', owner_id=ws['user_id']) reward.set_reward_values(media_url=name+ext) else: return { 'message':'Invalid format :(', 'ws':ws } dbs.add(reward) try: dbs.commit() except: return { 'ws':ws, 'message':'Something went wrong :(' } return { 'message':'File saved successfully', 'ws':ws, 'form':form }