def sendMessage(): form = MessageForm() if not current_user.is_administrator(): to_users = [(u.lower.id, u.lower.name) for u in current_user.lower.all()] to_users.extend([(u.upper.id, u.upper.name) for u in current_user.upper.all()]) else: to_users = [ (u.id, u.name) for u in User.query.filter(User.id != current_user.id).all() ] form.to_user.choices = to_users if form.validate_on_submit(): mesg = Message(subject=form.subject.data, content=form.content.data, sender_id=current_user.id, receiver_id=form.to_user.data) mesg.root = mesg if current_user.is_administrator(): mesg.type = MesgType.SYSTEM else: mesg.type = MesgType.USER db.session.add(mesg) db.session.commit() flash(u'发送成功') return redirect(url_for('main.listMessage')) return render_template('main/send_mesg.html', pagetitle=u'发送消息', mesgManage='active', form=form)
def edit_profile(id): employee = Employee.query.get_or_404(id) if current_user == employee or current_user.is_administrator(): form = EditEmployeeFrom(employee) if form.validate_on_submit(): employee.login_name = form.login_name.data employee.employee_name = form.employee_name.data employee.role = Role.query.get(form.role_name.data) employee.dept = Department.query.get(form.dept_name.data) db.session.add(employee) flash('员工信息修改成功!') if current_user.is_administrator(): return redirect(url_for('main.employee_list')) else: return redirect( url_for('main.employee', employee_name=current_user.employee_name)) form.login_name.data = employee.login_name form.employee_name.data = employee.employee_name form.role_name.data = employee.role_id form.dept_name.data = employee.dept_id return render_template('edit_profile.html', form=form, employee=employee) else: abort(403)
def design(): if request.method == 'POST': a = request.get_json(force=True) title = a["title"] if (current_user.is_administrator()): tag = a["tag"] timestamp = datetime.datetime.now() user_id = current_user.get_id() items = a["items"] q = Questionnaire() if (title != ""): q.title = title if (current_user.is_administrator()): q.tag = tag q.user_id = user_id q.timestamp = timestamp q.save() for item in items: i = Item() question = item["question"] no = item["no"] kind = item["kind"] need = item["need"] i.question = question i.no = no i.kind = kind i.need = need choice = item["choice"] for c in choice: i.choice.append(c) i.questionnaire = q i.save() return jsonify(result=str(q.id)) return render_template('design.html', id="")
def event_details(id): """Render a page that allows the user to enter more details about the event. """ details_form = EventDetailsForm() upload_image_form = UploadImageForm() remove_image_form = RemoveImageForm() details_form.submit.label.text = "Submit" event = Event.query.get_or_404(id) if not current_user.is_organizer( event) and not current_user.is_administrator(): return redirect(url_for("main.index")) if details_form.validate_on_submit(): event.description = details_form.description.data event.pitch = details_form.pitch.data db.session.commit() flash("Update successful.", "success") return redirect(url_for("events.event_details", id=event.id)) # pre-fill fields details_form.description.data = event.description details_form.pitch.data = event.pitch return render_template( "events/event_details.html", details_form=details_form, upload_image_form=upload_image_form, remove_image_form=remove_image_form, main_image_path=event.main_image(), event=event, )
def media(id): """Return a page that allows the user do at various forms of media to their event page.""" event = Event.query.get_or_404(id) if not current_user.is_organizer( event) and not current_user.is_administrator(): return redirect(url_for("main.index")) # Instantiate forms upload_video_form = UploadVideoForm() remove_video_form = RemoveVideoForm() image_form = MultipleImageForm() remove_image_form = RemoveImageForm() # Get data from user session upload_video_form.video_url.errors = session.pop( "upload_video_form_errors", []) upload_video_form.video_url.data = session.pop("video_url", "") image_form.images.errors = session.pop("image_form_errors", []) return render_template( "events/media.html", upload_video_form=upload_video_form, remove_video_form=remove_video_form, image_form=image_form, remove_image_form=remove_image_form, video=event.video, misc_image_paths=event.misc_images(), event=event, )
def edit_package(event_id, package_id): """View function to add a package to an event in the database.""" form = EventPackagesForm() event = Event.query.get_or_404(event_id) package = event.packages.filter(Package.id == package_id).first_or_404() if not current_user.is_organizer( event) and not current_user.is_administrator(): return redirect(url_for("main.index")) if form.validate_on_submit(): form_data = form.data form_data["audience"] = EventPackagesForm.convert_choice_to_value( form.audience.data, "PEOPLE_RANGES") form_data["package_type"] = EventPackagesForm.convert_choice_to_value( form.package_type.data, "PACKAGE_TYPES") package.update(**form_data) db.session.commit() flash("Package details were successfully updated.", "success") return redirect(url_for("events.packages", id=event_id)) packages = event.packages.all() package_data = package.to_dict() package_data["audience"] = EventPackagesForm.convert_choice_to_id( package.audience, "PEOPLE_RANGES") package_data["package_type"] = EventPackagesForm.convert_choice_to_id( package.package_type, "PACKAGE_TYPES") form.populate(**package_data) return render_template("events/packages.html", form=form, event=event, packages=packages)
def demographics(id): """Return a page that allows the user to give details about who is attending the event. """ form = DemographicsForm() event = Event.query.get_or_404(id) if not current_user.is_organizer( event) and not current_user.is_administrator(): return redirect(url_for("main.index")) if form.validate_on_submit(): event.attendees = DemographicsForm.convert_choice_to_value( form.attendees.data, "PEOPLE_RANGES") event.male_to_female = str(form.males.data) + "-" + str( form.females.data) db.session.commit() flash("Your information has been successfilly uploaded.", "success") return redirect(url_for("events.demographics", id=id)) if event.attendees: form.attendees.data = DemographicsForm.convert_choice_to_id( event.attendees, "PEOPLE_RANGES") else: form.attendees.data = 1 if event.male_to_female: distribution = event.male_to_female.split("-") form.males.data = distribution[0] form.females.data = distribution[1] else: form.males.data = 0 form.females.data = 0 return render_template("events/demographics.html", form=form, event=event)
def admin(): current_term = current_app.config['CURRENT_TERM'] if current_user.is_administrator() is False: return redirect(url_for('main.index')) query_term = request.args.get('query_term', current_term, type=str) add_course_form = AddCourseForm() add_courses_form = AddCoursesForm() if add_course_form.validate_on_submit(): flash(add_course_form.course_name.data + '已添加') addCourseName(add_course_form.course_name.data) course_names = getCourseNames() if len(course_names) > 0: add_course_form.form_body = '已有科目:' + "、".join(course_names) add_courses_form.course.choices = [(i, i) for i in course_names] else: add_course_form.form_body = '暂无科目' if add_courses_form.validate_on_submit(): flash(add_courses_form.course.data + '新班级已添加') addCourseNames(add_courses_form.course.data) forms = [add_course_form, add_courses_form] currentCourseInfos = CourseInfo.query.filter_by( course_period=query_term, disabled=False).order_by(CourseInfo.course_names).all() statusLabels = ['课程名称', '班级', '班级人数', '正在收的作业'] statusContent = [CourseInfo.showStatus(i) for i in currentCourseInfos] return render_template('auth/admin.html', statuslabels=statusLabels, statusContent=statusContent, query_term=query_term, query_term_str=courseInfoIDToStr(query_term), forms=forms)
def made_post(): id = request.args.get('id', 0, type=int) user_id = request.args.get('user_id', 0, type=int) user = User.query.get(user_id) form = PostForm() title = '变更公告:' if id: post = Post.query.get_or_404(id) if current_user != post.author and not current_user.is_administrator(): abort(403) if form.validate_on_submit(): post.body = form.body.data db.session.add(post) flash('公告已更改!') return redirect(url_for('.post', id=post.id)) form.body.data = post.body else: title = '新公告' 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) flash('新公告已发布!') return redirect(url_for('.index')) return render_template('made_post.html', form=form, title=title, user=user)
def edit_profile_admin(id): if not current_user.is_administrator(): print 'jjj' return redirect(url_for('.index')) user = User.query.get_or_404(id) form = EditAdmin(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash(u'用户资料已变更') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit-profile-admin.html', form=form)
def unlock_user(id): if not current_user.is_administrator(): return redirect(url_for('.index')) user = User.query.get_or_404(id) user.username = user.username.strip('#ban#') db.session.add(user) return redirect(url_for('.user_manage'))
def update_user_information(username): form = UpdateUserInformationForm() user = User.query.filter_by(username=username).first() if form.validate_on_submit(): if current_user.is_administrator(): user.role_id = form.role.data user.nickname = form.nickname.data user.province = form.province.data user.city = form.city.data user.area = form.area.data user.about_me = form.about_me.data if form.avatar.data is not None and form.avatar.data.filename != '': file = form.avatar.data file.filename = datetime.now().strftime( "%Y%m%d%H%M%S") + os.path.splitext(file.filename)[-1] name = avatar.save(file) if user.avatar_name is not None: old_avatar_name = user.avatar_name user.avatar_name = name db.session.commit() os.remove(current_app.config['UPLOADED_AVATAR_DEST'] + old_avatar_name) else: user.avatar_name = name db.session.commit() flash('资料修改成功!') return redirect(url_for('main.index')) return render_template('updateUserInformation.html', form=form, user=user)
def delete_file(username, filename): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) current_app.logger.info("User {} requested deletion of file {}".format(username, filename)) file_path = os.path.join(current_app.config['MEDIA_ROOT'], 'users', username, filename) os.remove(file_path) return redirect(url_for('profile.manage_files', username=username))
def detail(alcohol_id): the_alcohol = Alcohol.query.get_or_404(alcohol_id) if the_alcohol.hidden and (not current_user.is_authenticated or not current_user.is_administrator()): abort(404) show = request.args.get('show', 0, type=int) page = request.args.get('page', 1, type=int) form = CommentForm() if show in (1, 2): pagination = the_alcohol.logs.filter_by(returned=show - 1) \ .order_by(Log.buy_timestamp.desc()).paginate(page, per_page=5) else: pagination = the_alcohol.comments.filter_by(deleted=0) \ .order_by(Comment.edit_timestamp.desc()).paginate(page, per_page=5) data = pagination.items return render_template("alcohol_detail.html", alcohol=the_alcohol, data=data, pagination=pagination, form=form, title=the_alcohol.title)
def list_one(name, date): participations = StudentService.search_by_competition_participation( competition_name=name, competition_date=date) results = CompetitionService.read_all_results(name=name, date=date) res_count = len(results) if res_count > 0: has_results = True else: has_results = False comp = CompetitionService.read(name, date) if current_user.is_administrator(): form = CreateCompetitionForm() form.initialize_fields() else: form = CompetitionFormBase() form.put_competition(comp) form.set_read_only_mode() return render_template('competition/single_view.html', form=form, showParticipations=0, participations=participations, name=comp.name, date=comp.date, has_results=has_results)
def user_upload(username): if current_user.username != username and not current_user.is_administrator( ): return redirect(url_for('front_page.home_page')) user = User.query.filter_by(username=username).first() file_path = os.path.join(current_app.config['MEDIA_ROOT'], 'users', username) form = Upload() if form.validate_on_submit(): file_data = form.file.data import pdb pdb.set_trace() filename = secure_filename(file_data.filename) print(filename) if filename.rsplit('.')[1].lower() in ALLOWED_EXTENSIONS: try: file_data.save(os.path.join(file_path, filename)) except IOError: flash('Image appears corrupted or failed verification') return redirect( url_for('profile.manage_files', username=username)) else: flash("Unacceptable file type submitted for upload") return redirect(url_for('profile.manage_files', username=username)) flash("Filed uploaded successfully") return form.redirect() return render_template('profile/upload.html', username=username, form=form, user=user)
def listArchives(user_id): page = request.args.get('page', 1, type=int) target = User.query.filter_by(id=user_id).first_or_404() if current_user.role.name == 'psycho': pagination = Archive.query\ .filter_by(author_id=current_user.id)\ .filter_by(target_id=user_id)\ .order_by(Archive.ctime.desc())\ .paginate(page, per_page=current_app.config['ENTRIES_PER_PAGE'], \ error_out=False) elif current_user.role.name == 'supervisor' \ or current_user.is_administrator(): pagination = Archive.query\ .filter((Archive.author_id==target.id) | \ (Archive.target_id==target.id)) \ .order_by(Archive.ctime.desc())\ .paginate(page, per_page=current_app.config['ENTRIES_PER_PAGE'], \ error_out=False) else: flash(u'权限不足') return redirect(url_for('manage.listArchives', user_id=user_id)) archives = pagination.items return render_template('manage/list_archives.html', archives=archives, pagination=pagination, user_id=user_id, pagetitle=u'{}的记录一览'.format(target.name), userManage='active')
def select(type): page = request.args.get('page', 1, type=int) # 无参数则默认为1,type作用:参数无法转为int时则默认为1 form = PostForm() if form.is_submitted() and current_user.can(Permission.WRITE_ARTICLES): post = Post(body=form.body.data, author_id=current_user.id, title=form.title.data, type=form.post_type.data) db.session.add(post) db.session.commit() return redirect('http://127.0.0.1:5000/') # 分页 if current_user.is_administrator(): pagination = Post.query.filter_by(type=type).order_by( Post.id.desc()).paginate(page, per_page=10, error_out=False) else: pagination = Post.query.filter_by(type=type).filter( Post.visible == 1).order_by(Post.id.desc()).paginate( page, per_page=10, error_out=False) # 拿到一页内容 posts = pagination.items types = get_types() return render_template('blog.html', form=form, posts=posts, pagination=pagination, types=types)
def downloadSurveyResult(survey_id): survey = Survey.query.filter_by(id=survey_id).first_or_404() if not current_user.is_administrator() and \ current_user.own_surveys.filter(Survey.id == survey_id).all(): #survey.author != current_user: flash(u'权限不足') return redirect(url_for('manage.listSurvey')) # 取得问卷条目的ID origin_keys = [] dimen_keys = (yaml.load(survey.dimension)).keys() for page in loadYAML(survey.content_origin): for item in page['items']: origin_keys.append(item['id']) keys = origin_keys+dimen_keys survey_results = SurveyResult.query\ .filter_by(survey=survey)\ .order_by(SurveyResult.id.asc())\ .all() results = (json.loads(r.result) for r in survey_results) r_list = [] for row in results: o = [str(row['origin'][k]) for k in origin_keys] d = [str(row['dimen'][k]) for k in dimen_keys] r_list.append(','.join(o+d)) resp = Response(stream_template('manage/survey_results.csv', results=r_list, keys='","'.join(keys) ), mimetype='text/csv') resp.headers['Content-Disposition']='attachment; filename={}.csv'.format(survey.slug) return resp
def user_upload(username): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) user = User.query.filter_by(username=username).first() file_path = os.path.join(current_app.config['MEDIA_ROOT'], 'users', username) form = Upload() if form.validate_on_submit(): file_data = form.file.data import pdb; pdb.set_trace() filename = secure_filename(file_data.filename) print(filename) if filename.rsplit('.')[1].lower() in ALLOWED_EXTENSIONS: try: file_data.save(os.path.join(file_path, filename)) except IOError: flash('Image appears corrupted or failed verification') return redirect(url_for('profile.manage_files', username=username)) else: flash("Unacceptable file type submitted for upload") return redirect(url_for('profile.manage_files', username=username)) flash("Filed uploaded successfully") return form.redirect() return render_template('profile/upload.html', username=username, form=form, user=user)
def user_transload(username): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) user = User.query.filter_by(username=username).first() file_path = os.path.join(current_app.config['MEDIA_ROOT'], 'users', username) form = Transload() if form.validate_on_submit(): url = form.url.data response = transload(url) if int(response.headers['Content-Length']) > int(current_app.config['MAX_CONTENT_LENGTH']): return abort(413) img = Image.open(BytesIO(response.content)) if img.format.lower() in ALLOWED_EXTENSIONS: secured_name = secure_filename(response.url.split('/')[-1]) outfile = os.path.join(file_path, secured_name) try: img.save(outfile, img.format) except IOError: flash('Image appears corrupted or failed verification') return redirect(url_for('profile.manage_files', username=username)) else: flash("Unacceptable file type submitted for upload") return redirect(url_for('profile.manage_files', username=username)) return render_template('profile/transload.html', username=username, form=form, user=user)
def manage_files(username): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) filedata = [] user = User.query.filter_by(username=username).first() file_list, file_path = get_file_list(user) if file_list: for userfile in file_list: data = { 'name': userfile['name'], 'size': userfile['size'], 'URL': url_for('media', filename='users/{}/{}'.format(user.username, userfile)) } if user.avatar_url and user.avatar_url.endswith(userfile['name']): data['avatar'] = True if user.picture_url and user.picture_url.endswith(userfile['name']): data['picture'] = True im = Image.open(os.path.join(file_path, userfile['name'])) data['w'] = im.size[0] data['h'] = im.size[1] if data['w'] > 300 and data['h'] > 300: data['resize'] = True if not os.path.isfile(os.path.join(file_path, 'tn/tn_{}'.format(userfile['name']))): dest_path = os.path.join(file_path, 'tn') generate_thumbnail(userfile['name'], source_path=file_path, dest_path=dest_path, width=300) filedata.append(data) return render_template('profile/manage_files.html', user=user, filedata=filedata)
def index(): if current_user.is_administrator(): return redirect(url_for('admin.index')) if (request.method == 'POST'): teamName = request.form.get('teamName') phone = request.form.get('phone') password = request.form.get('password') description = request.form.get('description') team = current_user team.teamName = teamName team.phone = phone if (password): team.password = password team.description = description avatar = request.files['avatar'] if avatar and allowed_file(avatar.filename): filename = secure_filename(avatar.filename) if (filename.find('.') != -1): filename = 'teamavatar_' + str(team.id) + '_' + filename else: filename = 'teamavatar_' + str(team.id) + '_.' + filename avatar.save( os.path.join(current_app.config['UPLOAD_FOLDER'], filename).replace('\\', '/')) file = '/static/img/' + filename team.avatar = file db.session.commit() return render_template('profile.html', team=current_user)
def article(title_slug, **kwargs): article = Article.query.filter_by(title_slug=title_slug).first_or_404() if not article.published and not current_user.is_administrator( ) and not current_user.can( Permission.EDIT) and not current_user == article.author: abort(404) return render_template('main/article.html.j2', article=article)
def listMessage(path): if current_user.is_administrator(): return redirect(url_for('manage.listMessage')) page = request.args.get('page', 1, type=int) if path == 'in': pagination = Message.query\ .filter(Message.receiver_id==current_user.id, Message.receiver_deled==0)\ .order_by(Message.ctime.desc())\ .paginate(page, per_page=current_app.config['ENTRIES_PER_PAGE'], \ error_out=False) template = 'main/list_message_inbox.html' elif path == 'out': pagination = Message.query\ .filter(Message.sender_id==current_user.id, Message.sender_deled==0)\ .order_by(Message.ctime.desc())\ .paginate(page, per_page=current_app.config['ENTRIES_PER_PAGE'], \ error_out=False) template = 'main/list_message_outbox.html' elif path == 'del': pagination = Message.query\ .filter(and_(Message.sender_id==current_user.id, Message.sender_deled!=0) |\ and_(Message.receiver_id==current_user.id, Message.receiver_deled!=0))\ .filter(Message.ctime > getDayBeforeN())\ .order_by(Message.ctime.desc())\ .paginate(page, per_page=current_app.config['ENTRIES_PER_PAGE'], \ error_out=False) template = 'main/list_message_delbox.html' messages = pagination.items return render_template(template, messages=messages, pagination=pagination, pagetitle=u'查看消息', path=path, mesgManage='active')
def post(id): post = Post.query.get_or_404(id) post.view_count += 1 db.session.add(post) db.session.commit() if post.disabled is True and not current_user.is_administrator() \ and not current_user.is_moderate(post.board): return render_template('404.html', deleted_post=True) form = ResponseForm() if current_user.can(Permission.COMMENT) and form.validate_on_submit(): refloor = 0 Post.new_comment(form.body.data, current_user._get_current_object(),post, refloor) flash('评论提交成功') return redirect(url_for('.post', id=post.id, page=-1)) form.re.data = 'Re 标题: ' + post.title page = request.args.get('page', 1, type=int) if page == -1: page = (post.comments.count() - 1) // \ current_app.config['BBS_COMMENTS_PER_PAGE'] + 1 pagination = post.comments.order_by(Comment.floor.asc()).paginate( page, per_page=current_app.config['BBS_COMMENTS_PER_PAGE'], error_out=False) comments = pagination.items return render_template('post.html', post=post, form=form, board=post.board, page=page, comments=comments, pagination=pagination)
def index(): if current_user.is_authenticated and (not current_user.validated): # if the user is not validated they will be routed back to change password form current_app.logger.info("{} visited index but is not validated. Redirecting to /auth/change_password".format(current_user.email)) return redirect(url_for("auth.change_password")) else: flash("Logged in successfully") current_app.logger.info("user {} logged in".format(current_user.email)) # If the user is an admin they should be able to see all the appointments for all the departments if current_user.is_administrator(): appointments = Appointment.query.all() else: appointments = Appointment.query.filter_by(department=current_user.department).all() # if user has logged in load all the appointments that are for today and then add the to the appointments_list, those ont approvedf are put in unapproved_appointments_list, # I didn't remove from the original list that was queried because removing somehow always left an extra element in there appointments_list = [] unapproved_appointments_list = [] # This page also needs to contain a list of the unaproved appointmetns so that they can be approved for appointment in appointments: # if appointment if apprved and today put it in appointment list if appointment.datetime.date() == datetime.today().date() and appointment.check_in_state<3 and appointment.approved == True: appointments_list.append(appointment) # if apointment is not approved and is today or greater than today then put it in this list if appointment.datetime.date() >= datetime.today().date() and appointment.check_in_state<3 and appointment.approved == False: unapproved_appointments_list.append(appointment) return render_template("auth/index.html", appointments=appointments_list ,unapproved_appointments=unapproved_appointments_list, today=datetime.today().date())
def delete_post(id): post = Post.query.get_or_404(id) if post.author_id != current_user.id and not current_user.is_administrator( ): abort(403) if post.comments.count() > 0: for comment in post.comments.all(): db.session.delete(comment) remove_tags = [] for tag in post.tags: post.tags.remove(tag) remove_tags.append(tag) for tag in remove_tags: if tag.posts.count() == 0: print 'delete tag: %s because there is not any post use this tag' % tag.name db.session.delete(tag) #old_tags = post.tags.all() old_category = post.category db.session.delete(post) # for old_tag in old_tags: # if old_tag.posts.count() == 0: # print 'delete tag: %s because there is not any post use this tag' % old_tag.name # db.session.delete(old_tag) if old_category.posts.count() == 0: print 'delete category: %s because there is not any post in this category' % old_category.name db.session.delete(old_category) return redirect(url_for('.user', username=current_user.username))
def user_stats(): from rq import Queue from ..jobs import game_stats s3_bucket = current_app.config['S3_BUCKET'] aws_region = current_app.config['AWS_REGION'] q = Queue(connection=redis_store) user_role = '' if current_user.is_student(): user_role = 'student' if current_user.is_teacher(): user_role = 'teacher' if current_user.is_administrator(): user_role = 'administrator' result = q.enqueue(game_stats.game_stats, aws_region, s3_bucket, current_user.id, user_role, timeout=59 * 30) job_url = 'https://s3.amazonaws.com/{}/jobs/{}.csv'.format( s3_bucket, result.id) return render_template('game_stats.html', job_url=job_url)
def made_post(): id = request.args.get('id', 0, type=int) user_id = request.args.get('user_id', 0, type=int) user = User.query.get(user_id) form = PostForm() title = '变更公告:' if id: post = Post.query.get_or_404(id) if current_user != post.author and not current_user.is_administrator(): abort(403) if form.validate_on_submit(): post.body = form.body.data db.session.add(post) complete_quest_1(post.body, user) flash('公告已更改!') return redirect(url_for('.post', id=post.id)) form.body.data = post.body else: title = '新公告' 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) complete_quest_1(form.body.data, current_user) flash('新公告已发布!') resp = make_response(redirect(url_for('.posts'))) resp.set_cookie('show_which', 'all', max_age=30 * 24 * 60 * 60) return resp return render_template('made_post.html', form=form, title=title, user=user)
def subforum(id): subforum = Forum.query.get_or_404(id) form1=PostForm() form2=SetModeratorForm() if current_user.can(Permission.WRITE_ARTICLES) and form1.validate_on_submit(): post=Post(body=form1.body.data, author=current_user._get_current_object(), subforum=subforum) db.session.add(post) return redirect(url_for('note.subforum', id=subforum.id)) # Enter the forum and set the moderator if current_user.is_administrator() and form2.validate_on_submit(): if form2.setmoderator.data != 0: user=User.query.get(form2.setmoderator.data) user.subforum=subforum user.role=Role.query.filter_by(name='Moderator').first() db.session.add(user) elif subforum.users != None: user=subforum.users user.role=Role.query.filter_by(name='User').first() user.subforum=None db.session.add(user) return redirect(url_for('note.subforum', id=subforum.id)) page = request.args.get('page', 1, type=int) query = Post.query.filter_by(subforum=subforum).order_by(Post.timestamp.desc()) show_followed=False if current_user.is_authenticated: show_followed=bool(request.cookies.get('show_followed', '')) if show_followed: # query=current_user.followed_posts query=query.join(Follow, Follow.followed_id==Post.author_id).filter(Follow.follower_id==current_user.id) pagination = query.paginate(page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False) posts = pagination.items return render_template('note/subforum.html', id=id, form1=form1, form2=form2, subforum=subforum, posts=posts, pagination=pagination, show_followed=show_followed)
def addSurvey(): form = addSurveyForm() if form.validate_on_submit(): survey = Survey( title=form.title.data, description=form.describe.data, content_origin=form.content.data, dimension=form.dimension.data, uptime=datetime.now(), author=current_user ) if current_user.is_administrator(): survey.status = SurveyStatus.PUB survey_origin = SurveyMeta( meta_key='survey_origin', meta_value=form.content.data, author_id=current_user.id, survey=survey ) db.session.add(survey) db.session.add(survey_origin) db.session.add(Distribute(owner=current_user, survey=survey, type=OwnerType.OWNER)) db.session.commit() flash(u'操作成功') return redirect(url_for('manage.listSurvey')) return render_template('manage/add_survey.html', form=form, pagetitle=u'添加问卷', surveyManage='active' )
def hello_world(): page = request.args.get('page', 1, type=int) # 无参数则默认为1,type作用:参数无法转为int时则默认为1 form = PostForm() if form.is_submitted() and current_user.can(Permission.WRITE_ARTICLES): post = Post(body=form.body.data, author_id=current_user.id, title=form.title.data, type=form.post_type.data, timestamp=datetime.datetime.now()) db.session.add(post) db.session.commit() return redirect(url_for('main.hello_world')) # 分页 if current_user.is_administrator(): pagination = Post.query.order_by(Post.id.desc()).paginate( page, per_page=10, error_out=False) else: pagination = Post.query.filter(Post.visible == 1).order_by( Post.id.desc()).paginate(page, per_page=10, error_out=False) # 拿到一页内容 todo = TodoList.query.order_by(TodoList.id.asc()).all() posts = pagination.items types = get_types() return render_template('blog.html', form=form, posts=posts, pagination=pagination, todo=todo, types=types)
def set_picture(username, filename): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) user = User.query.filter_by(username=username).first() new_picture = url_for('media', filename='users/{}/{}'.format(user.username, filename)) user.set_picture(new_picture) return redirect(url_for('profile.manage_files', username=username))
def user_transload(username): if current_user.username != username and not current_user.is_administrator( ): return redirect(url_for('front_page.home_page')) user = User.query.filter_by(username=username).first() file_path = os.path.join(current_app.config['MEDIA_ROOT'], 'users', username) form = Transload() if form.validate_on_submit(): url = form.url.data response = transload(url) if int(response.headers['Content-Length']) > int( current_app.config['MAX_CONTENT_LENGTH']): return abort(413) img = Image.open(BytesIO(response.content)) if img.format.lower() in ALLOWED_EXTENSIONS: secured_name = secure_filename(response.url.split('/')[-1]) outfile = os.path.join(file_path, secured_name) try: img.save(outfile, img.format) except IOError: flash('Image appears corrupted or failed verification') return redirect( url_for('profile.manage_files', username=username)) else: flash("Unacceptable file type submitted for upload") return redirect(url_for('profile.manage_files', username=username)) return render_template('profile/transload.html', username=username, form=form, user=user)
def book_borrow(): book_id = request.args.get('book_id') the_book = Book.query.get_or_404(book_id) if the_book.hidden and not current_user.is_administrator(): abort(404) result, message = current_user.borrow_book(the_book) flash(message, 'success' if result else 'danger') db.session.commit() return redirect(request.args.get('next') or url_for('book.detail', book_id=book_id))
def rename_file(username, filename): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) form = Rename() if form.validate_on_submit(): file_path = os.path.join(current_app.config['MEDIA_ROOT'], 'users', username) os.rename(os.path.join(file_path, filename), os.path.join(file_path, form.filename.data)) return redirect(url_for('profile.manage_files', username=username)) form.filename.data = filename return render_template('profile/rename.html', form=form)
def add(book_id): form = CommentForm() the_book = Book.query.get_or_404(book_id) if the_book.hidden and not current_user.is_administrator(): abort(404) if form.validate_on_submit(): the_comment = Comment(user=current_user, book=the_book, comment=form.comment.data) db.session.add(the_comment) db.session.commit() flash(u'书评已成功发布', 'success') return redirect(request.args.get('next') or url_for('book.detail', book_id=book_id))
def edit_signature(username): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) user = User.query.filter_by(username=username).first() form = Signature() form.signature.data = user.signature_text if form.validate_on_submit(): user.signature_text = form.signature.data db.session.add(user) db.session.commit() return render_template('profile/signature.html', user=user, form=form)
def edit(tid): topic = Topic.query.filter_by(id=tid).first() if current_user.id != topic.user().id and (not current_user.is_administrator()): return redirect(url_for('voice.view'), tid=topic.id) if request.method == 'GET': return render_template('voice/edit.html', topic=topic) elif request.method == 'POST': topic.content = request.form['content'] if not topic.content: message = gettext('content cannot be empty') return render_template('voice/edit.html', topic=topic, message=message) topic.content_rendered = markdown.markdown(topic.content, ['codehilite'], safe_mode='escape') db.session.commit() return redirect(url_for('voice.view', tid=topic.id))
def decorator_function(*args, **kw): c = Contest.cache_get(contest_id) if c is None: abort(404) if c.type == ContestType.PUBLIC or current_user.is_administrator(): return f(*args, **kw) if current_user in c.players.all(): return f(*args, **kw) else: abort(404) if c.type == ContestType.PASSWORD: pass return f(*args, **kw)
def problem_details(problem_id): problem = Problem.query.get(problem_id) if problem.hidden and not current_user.is_administrator(): abort(404) form = SubmitSolution() if form.validate_on_submit(): if not current_user.is_authenticated: flash("You Need Login First!") return redirect((url_for('auth.login'))) sol = Solution(code = form.code.data, lang = form.lang.data, user_id = current_user.id, problem_id = problem_id) db.session.add(sol) db.session.commit() flash("submit success!") return redirect(url_for('main.judge_status', problem_id = problem_id)) return render_template('problem/details.html', problem = problem, form = form, current_page = "main.problem")
def problem(contest_id, problem_relative_id): c = before_request(contest_id) contest_problems = c.contest_problems.filter_by(problem_relative_id = problem_relative_id).first() if contest_problems is None: abort(404) #if not start if c.begin_time > datetime.datetime.utcnow() and not current_user.is_administrator(): flash("plese wait for contest start") return redirect(url_for('contest.contest', contest_id = contest_id)) form = SubmitSolution() if form.validate_on_submit(): if not current_user.is_authenticated: flash("You Need Login First!") return redirect((url_for('auth.login'))) if c.begin_time > datetime.datetime.utcnow() or c.end_time < datetime.datetime.utcnow(): flash("out of contest time") return redirect(url_for('contest.contest', contest_id = contest_id)) sol = Solution() sol.code = form.code.data sol.contest_id = contest_id sol.lang = form.lang.data sol.problem_id = contest_problems.problem_id sol.user_id = current_user.id sol.problem_relative_id = contest_problems.problem_relative_id try: db.session.add(sol) db.session.commit() flash("Submit Solution Success") return redirect(url_for('contest.status', contest_id = contest_id)) except IntegrityError: db.session.rollback() flash("system error, try again later", "error") return render_template('contest/problem.html', current_page = 'main.contest', contest = c, cp = contest_problems, form = form)
def detail(book_id): the_book = Book.query.get_or_404(book_id) if the_book.hidden and (not current_user.is_authenticated or not current_user.is_administrator()): abort(404) show = request.args.get('show', 0, type=int) page = request.args.get('page', 1, type=int) form = CommentForm() if show in (1, 2): pagination = the_book.logs.filter_by(returned=show - 1) \ .order_by(Log.borrow_timestamp.desc()).paginate(page, per_page=5) else: pagination = the_book.comments.filter_by(deleted=0) \ .order_by(Comment.edit_timestamp.desc()).paginate(page, per_page=5) data = pagination.items return render_template("book_detail.html", book=the_book, data=data, pagination=pagination, form=form, title=the_book.title)
def edit_profile(username): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) user = User.query.filter_by(username=username).first() file_path = os.path.join(current_app.config['MEDIA_ROOT'], 'users', user.username) form = Profile() form.time_zone.choices = build_timezone_list() form.redirect_target.choices = [(url_for('front_page.home_page'), 'Front Page'), (url_for('forum.forum_index'), 'Forum Home')] # Check if the user is using 2FA, and needs to auth. if user.otp: tfa_state = True else: tfa_state = False if form.validate_on_submit(): user.fullname = form.fullname.data user.location = form.location.data user.avatar_text = form.avatar_text.data user.avatar_url = form.avatar_url.data user.timezone = form.time_zone.data user.landing_page = form.redirect_target.data db.session.add(user) db.session.commit() form.fullname.data = user.fullname or None form.location.data = user.location or None form.avatar_url.data = user.avatar_url or None form.avatar_text.data = user.avatar_text or None form.time_zone.data = user.timezone # print(user.landing_page) form.redirect_target.data = user.landing_page try: file_list = [f.stat().st_size for f in scandir(file_path)] disk_use = sum(file_list) except OSError: disk_use = 0 return render_template('profile/edit.html', user=user, form=form, tfa=tfa_state, disk_use=disk_use)
def individual_homepage(id): user = User.query.filter_by(id=id).first_or_404() if current_user.id != user.id and not current_user.is_administrator(): abort(403) posts = user.posts.order_by(Post.timestamp.desc()).all() return render_template('individual-homepage.html', user=user, posts=posts)
def decorated(*args, **kwargs): if not current_user.is_administrator(): abort(403) return f(*args, **kwargs)
def download_file(username, filename): if current_user.username != username and not current_user.is_administrator(): return redirect(url_for('front_page.home_page')) file_path = os.path.join(current_app.config['MEDIA_ROOT'], 'users', username, filename) img_type = filename.rsplit('.')[1] return send_file(file_path, mimetype='image/{}'.format(img_type), as_attachment=True)
def solution(solution_id): sol = Solution.query.get(solution_id) if current_user.is_administrator() or (not current_user.is_anonymous and current_user.id == sol.user_id): return render_template('solution_code.html', sol = sol) else: abort(404)
def is_accessible(self): return current_user.is_administrator()
def decorated(*args, **kwargs): if not current_user.is_administrator(): return redirect(url_for('auth.login')) return f(*args, **kwargs)