def follow(username): user = MongoClient().blog.User.find_one({'username': username}) if user is None: flash('此用户不存在.') return redirect(url_for('.index')) very = False temp = MongoClient().blog.User.find_one({ 'username': current_user.username }).get('following') for i in range(temp.__len__()): if temp[i][0] == username: very = True break if very: flash('您已经关注过了他,不能重复关注.') return redirect(url_for('.user', username=username)) followers = user.get('followers') time = datetime.utcnow() follow = [current_user.username, time] followers.append(follow) MongoClient().blog.User.update({'username': username}, {'$set': { 'followers': followers }}) post2 = MongoClient().blog.User.find_one( {'username': current_user.username}) following = post2.get('following') follow = [user.get('username'), time] following.append(follow) MongoClient().blog.User.update({'username': current_user.username}, {'$set': { 'following': following }}) flash('您成功关注了 %s.' % username) return redirect(url_for('.user', username=username))
def to_json(self): json_post = { 'url': url_for('api.get_post', id=self.id, _external=True), 'body': self.body, 'body_html': self.body_html, 'timestamp': self.timestamp, 'author': url_for('api.get_user', id=self.author_id, _external=True), # 'comments': url_for('api.get_post_comments', id=self.author_id, _external=True), # 'comment_count': self.comments.count() } return json_post
def to_json(self): json_user = { 'url': url_for('api.get_user', id=self.id, _external=True), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts': url_for('api.get_user_posts', id=self.id, _external=True), 'followed_posts': url_for('api.get_user_followed_posts', id=self.id, _external=True), 'post_count': self.posts.count() } return json_user
def unauthorized(): if request.method == 'GET': flash(_('Please login to access this page.')) # return redirect(login_url('sso.login', request.url, 'url')) return redirect(url_for('sso.login', **make_referrer_query(request.url)[2])) else: return dict(error=True, message=_("Please login for access.")), 403
def post(id): post = MongoClient().blog.Aritical.find({'_id': ObjectId(id)}) form = CommentForm() if form.validate_on_submit(): comments = post[0].get('comments') body = form.body.data comments.append([body, current_user.username, datetime.utcnow()]) MongoClient().blog.Aritical.update({'_id': ObjectId(id)}, {'$set': { 'comments': comments }}) flash('评论发布成功.') return redirect(url_for('.post', id=id, page=-1)) page = request.args.get('page', 1, type=int) pagination = PaginateComments(page, id) comments = pagination.items comment = (post[0].get('username') != current_user.username) return render_template('post.html', posts=post, form=form, i=0, comments=comments, pagination=pagination, author=comment, id=id)
def register(): print ("in register_page") try: form = RegistrationForm(request.form) # allows us to render the form if request.method == "POST" and form.validate(): # if user hit register button and form is complete # logout any logged in user logout_user() username = form.username.data # refers to username from RegistrationForm class email = form.email.data pass_hash = generate_password_hash(form.password.data, method='pbkdf2:sha256') # hash the user's pw # prepare User user = User(username,email,pass_hash) if user.save(): if login_user(user, remember="no"): flash("Thank you for registering! Logged in!") return redirect(url_for('questions')) else: flash("unable to log you in") else: flash("Username already taken. Please choose another.") return render_template('register.html', form=form) return render_template('register.html', form=form) except Exception as e: return(str(e))
def edit_profile_admin(id): user = MongoClient().blog.User.find_one({'_id': ObjectId(id)}) if user is None: return abort(404) user_temp = Temp(id=user.get('_id'), username=user.get('username'), email=user.get('email'), password=user.get('password'), activate=user.get('activate'), role=user.get('role'), name=user.get('name'), location=user.get('location'), about_me=user.get('about_me'), last_since=user.get('last_since'), member_since=user.get('member_since')) form = EditProfileAdminForm(user=user_temp) if form.validate_on_submit(): MongoClient().blog.User.update({'email': user_temp.email}, {'$set': { 'name': form.name.data }}) MongoClient().blog.User.update( {'email': user_temp.email}, {'$set': { 'username': form.username.data }}) MongoClient().blog.User.update({'email': user_temp.email}, {'$set': { 'email': form.email.data }}) MongoClient().blog.User.update( {'email': user_temp.email}, {'$set': { 'activate': form.activate.data }}) MongoClient().blog.User.update({'email': user_temp.email}, {'$set': { 'role': form.role.data }}) MongoClient().blog.User.update( {'email': user_temp.email}, {'$set': { 'location': form.location.data }}) MongoClient().blog.User.update( {'email': user_temp.email}, {'$set': { 'about_me': form.about_me.data }}) flash('The profile has been updated.') return redirect(url_for('.user', username=user_temp.username)) form.email.data = user_temp.email form.username.data = user_temp.username form.activate.data = user_temp.activate form.role.data = user_temp.role.name form.name.data = user_temp.name form.location.data = user_temp.location form.about_me.data = user_temp.about_me return render_template('edit_profile.html', form=form, user=user_temp)
def to_json(self): json_user ={ 'url': url_for('api_1.user_detail', id=self.id), 'username': self.username, 'location': self.location, 'about_me': self.about_me, 'member_since': self.member_since, 'last_seen': self.last_seen } return json_user
def account_createtable(): form = CreateTableForm(request.form) if form.validate(): tableid = DB.add_table(form.tablenumber.data, current_user.get_id()) new_url = BH.shorten_url(config.base_url + "newrequest/" + tableid) DB.update_table(tableid, new_url) return redirect(url_for('account')) return render_template("account.html", createtableform=form, tables=DB.get_tables(current_user.get_id()))
def process_email_batch(service_id): form = CreateEmailBatchForm() service = admin_api_client.get_service_by_user_id_and_service_id( int(session['user_id']), service_id) file = request.files['email-bulk-upload'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) data = transform(StringIO(file.stream.read().decode("UTF8")), 'email') if 'errors' in data: return render_template("send_sms_batch.html", form=form, errors=data['errors'], service=service['service'], **get_template_data()), 400 job = admin_api_client.create_job(form.description.data, filename, service_id) for notification in data['notifications']: try: admin_api_client.send_email( notification['to'], notification["message"], notification["from"], notification["subject"], job_id=job["job"]["id"], token=service["service"]["token"]["token"]) except APIError as ex: message = "Upload with errors" print(ex.response.json()) flash(message, 'error') return redirect( url_for('.view_all_jobs', service_id=service_id)) message = "Uploaded email batch of {} notifications".format( len(data["notifications"])) flash(message, 'success') return redirect(url_for('.view_all_jobs', service_id=service_id)) else: return render_template("send_email_batch.html", form=form, service=service['service'], **get_template_data()), 400
def process_email_batch(service_id): form = CreateEmailBatchForm() service = admin_api_client.get_service_by_user_id_and_service_id(int(session['user_id']), service_id) file = request.files['email-bulk-upload'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) data = transform(StringIO(file.stream.read().decode("UTF8")), 'email') if 'errors' in data: return render_template("send_sms_batch.html", form=form, errors=data['errors'], service=service['service'], **get_template_data() ), 400 job = admin_api_client.create_job(form.description.data, filename, service_id) for notification in data['notifications']: try: admin_api_client.send_email( notification['to'], notification["message"], notification["from"], notification["subject"], job_id=job["job"]["id"], token=service["service"]["token"]["token"]) except APIError as ex: message = "Upload with errors" print(ex.response.json()) flash(message, 'error') return redirect(url_for('.view_all_jobs', service_id=service_id)) message = "Uploaded email batch of {} notifications".format(len(data["notifications"])) flash(message, 'success') return redirect(url_for('.view_all_jobs', service_id=service_id)) else: return render_template( "send_email_batch.html", form=form, service=service['service'], **get_template_data()), 400
def unfollow(username): user = MongoClient().blog.User.find_one({'username': username}) if user is None: flash('此用户不存在.') return redirect(url_for('.index')) very = False temp = MongoClient().blog.User.find_one({ 'username': current_user.username }).get('following') for i in range(temp.__len__()): if temp[i][0] == username: very = True break if not very: flash('您没有关注这个用户.') return redirect(url_for('.user', username=username)) followers = user.get('followers') for i in range(followers.__len__()): if followers[i][0] == current_user.username: followers.remove(followers[i]) break MongoClient().blog.User.update({'username': username}, {'$set': { 'followers': followers }}) post2 = MongoClient().blog.User.find_one( {'username': current_user.username}) following = post2.get('following') for i in range(following.__len__()): if following[i][0] == username: following.remove(following[i]) break MongoClient().blog.User.update({'username': current_user.username}, {'$set': { 'following': following }}) flash('您取消关注了 %s.' % username) return redirect(url_for('.user', username=username))
def login(): form = LoginForm(request.form) if form.validate(): stored_user = DB.get_user(form.loginemail.data) if stored_user and PH.validate_password(form.loginpassword.data, stored_user['salt'], stored_user['hashed']): user = User(form.loginemail.data) login_user(user, remember=True) return redirect(url_for('account')) form.loginemail.errors.append("Email or password invalid") return render_template("home.html", loginform=form, registrationform=RegistrationForm())
def login(): form = LoginForm() if request.method == 'POST' and form.validate_on_submit(): #user = app.config['USERS_COLLECTION'].find_one({"_id": form.username.data}) user = User() curr_user = user.get(form.username.data) if curr_user and User.validate_login(curr_user.password, form.password.data): # ensure that user exists # user_obj = User(user['_id']) login_user(curr_user) flash("Logged in successfully!", category='success') return redirect(url_for("search")) else: flash("Wrong username or password!", category='error') # could not find in database return render_template('login.html', title='login', form=form)
def following(username): user = MongoClient().blog.User.find_one({'username': username}) if user is None: flash('此用户不存在.') return redirect(url_for('.index')) page = request.args.get('page', 1, type=int) pagination = PaginateFollowing(page=page, username=username) follows = pagination.item return render_template('followers.html', user=user, title='关注的人', title1='', title2='关注的人', endpoint='.following', pagination=pagination, follows=follows)
def delete(id): user = MongoClient().blog.Aritical.find({'_id': ObjectId(id)}) if not current_user.username == user[0].get( 'username') and not current_user.is_administrator(): abort(304) timedata = request.args.get('data') comments = user[0].get('comments') for i in range(comments.__len__()): time = str(comments[i][2]) if time == timedata: del comments[i] break MongoClient().blog.Aritical.update({'_id': ObjectId(id)}, {'$set': { 'comments': comments }}) return redirect(url_for('.post', id=id))
def edit(id): post = MongoClient().blog.Aritical.find_one({'_id': ObjectId(id)}) if current_user.id != post.get('user_id') and \ not current_user.can(Permission.ADMINISTER): abort(403) form = EditPostForm() if form.validate_on_submit(): MongoClient().blog.Aritical.update({'_id': ObjectId(id)}, { '$set': { 'body': form.body.data, 'body_html': body_html(form.body.data) } }) flash('修改成功') return redirect(url_for('.post', id=post.get('_id'))) form.body.data = post.get('body') return render_template('edit_post.html', form=form)
def main_project(self, data): user_id = data["user_id"] project_name = data["project_name"] user_manage_id = data["user_manage_id"] user_obj = load_user(user_id) # noinspection PyTypeChecker self.show_um_status_message("creating main container", user_manage_id, None) main_id = create_container("tactic_main_image", network_mode="bridge", owner=user_id) caddress = get_address(main_id, "bridge") send_request_to_container(self.megaplex_address, "register_container", {"container_id": main_id}) global_tile_manager.add_user(user_obj.username) list_names = self.get_list_names({"user_id": user_obj.get_id()})["list_names"] class_names = self.get_class_names({"user_id": user_obj.get_id()})["class_names"] function_names = self.get_function_tags_dict({"user_id": user_obj.get_id()})["function_names"] with self.app.test_request_context(): bf_url = url_for("figure_source", tile_id="tile_id", figure_name="X")[:-1] data_dict = { "project_name": project_name, "project_collection_name": user_obj.project_collection_name, "main_id": main_id, "user_id": user_obj.get_id(), "megaplex_address": self.megaplex_address, "main_address": caddress, "loaded_user_modules": global_tile_manager.loaded_user_modules, "mongo_uri": mongo_uri, "list_names": list_names, "class_names": class_names, "function_names": function_names, "user_manage_id": user_manage_id, "base_figure_url": bf_url, "use_ssl": use_ssl, } # noinspection PyTypeChecker self.show_um_status_message("start initialize project", user_manage_id, None) result = send_request_to_container(caddress, "initialize_project_mainwindow", data_dict).json() if not result["success"]: destroy_container(main_id) raise Exception(result["message_string"]) return None
def index(): form = PostForm() if current_user.can(Permission.WRITE_ARTICLES) and \ form.validate_on_submit(): Post(body=form.body.data).new_article() return redirect(url_for('.index')) page = request.args.get('page', 1, type=int) show_followed = False if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) if show_followed: pagination = Paginate(page, 1) else: pagination = Paginate(page, 0) posts = pagination.item return render_template('index.html', form=form, posts=posts, pagination=pagination, show_followed=show_followed)
def get_rooms(user): from models.models import ActivatedUsers, session q = ActivatedUsers.query.filter_by(user_id=user).first() if q is None: from flask_login import redirect, url_for del session['user_active'] return redirect(url_for('main.index_page')) if q.rooms is not None: arr = q.rooms.split('/') s = [] for x in arr: if x: s.append(x) session['rooms'] = s
def questions(): try: form = QuestionsForm(request.form) # allows us to render the form if request.method == "POST" and form.validate(): # if user hit submit button and form is complete restrictions = form.restrictions.data allergies = form.allergies.data zipcode = form.zipcode.data time = form.time.data meal = form.meal.data try: current_user.update({"restrictions": restrictions, "allergies": allergies, "zipcode": zipcode, "time": time, "meal": meal}) flash("Thank you!") return redirect(url_for('search')) # if registration was successful, except Exception as e: return(str(e)) return render_template('questions.html', form=form) except Exception as e: return(str(e))
def logout(): logout_user() return redirect(url_for('search')) # go back to login page
def show_followed(): resp = make_response(redirect(url_for('.index'))) resp.set_cookie('show_followed', '1', max_age=30 * 24 * 60 * 60) return resp
def unauthorized(): return redirect(url_for('login', next=request.path))
def dashboard_resolve(): request_id = request.args.get("request_id") DB.delete_request(request_id) return redirect(url_for('dashboard'))
def logout(): logout_user() return redirect(url_for("home"))
def account_deletetable(): tableid = request.args.get("tableid") DB.delete_table(tableid) return redirect(url_for('account'))