def user_get_patch_delete_by_id(id): if current_user is None: db.session.close() abort(404, description="This user does not exist") #Returns the specific User if request.method == 'GET': returnValue = jsonify(current_user.to_dict()) db.session.close() return returnValue, 200 #Updates the user password elif request.method == 'PATCH': obj = request.get_json() if not v.validate(obj): abort(400, description=v.errors) # Note that this update function is specified in models.py if "password" in obj: myPassword = obj.pop('password', None) current_user.set_password(myPassword) current_user.update(obj) db.session.commit() returnValue = jsonify(current_user.to_dict()) db.session.close() return returnValue, 200 #Removes the user and its devices from the database elif request.method == 'DELETE': user = User.query.filter_by(id = current_user.get_id()) for o in user: db.session.delete(o) db.session.flush() db.session.delete(current_user) db.session.commit() db.session.close() return '', 204
def authenticate(): """ Authenticates a user. """ if current_user.is_authenticated: # return {'user': current_user.to_json()} print('CURRENT USER------->', current_user.to_dict()) return current_user.to_dict() return {'errors': ['Unauthorized']}, 401
def post(): get = request.json.get user = User() user.first_name = get("first_name") user.last_name = get("last_name") user.bio = get("bio") db.session.add(user) db.session.commit() user.set_active_email_address(get("email")) user.set_active_password(get("password")) db.session.commit() return jsonify({ "data": { **current_user.to_dict(), "password": None, "confirm_password": None, }, "notification": { "body": f"Welcome, {user.first_name}!", "type": "card_notifications", "action_label": "Take me to Surprise Me", "action": "/#/home", }, }), 201
def index(): if request.method == "GET": date_list = list() today = date.today() # dates = Date.query.filter(Date.date >= date.today()) dates = Date.query.all() for one_date in dates: reservations = Reservation.query.filter( Reservation.date_id == one_date.id).order_by( Reservation.updated_at.desc()) one_date = one_date.to_dict() yes_list = list() no_list = list() for reservation in reservations: player = User.query.filter( User.id == reservation.user_id).one_or_none().to_dict() if reservation.will_play_singles: player["will_play_singles"] = True if reservation.wants_to_play: yes_list.insert(0, player) else: no_list.append(player) one_date["yes_list"] = yes_list one_date["no_list"] = no_list date_list.append(one_date) return { "dates": date_list, "today": today, "current_user": current_user.to_dict() }
def user(): if current_user.is_authenticated: return ( jsonify({"msg": "Session still valid", **current_user.to_dict()}), 200, ) raise APIError("Please log in", 401)
def post(self, data): if current_user.check_password(data["old_password"]): current_user.password = data["new_password"] current_user.update_at = time_utcnow() current_user.save() return current_user.to_dict(get_token()) raise APIException("invalid credential", 401)
def authenticate(): """ Authenticates a user. """ if current_user.is_authenticated: return current_user.to_dict() return jsonify(None)
def posts(): """处理文章的首页路由""" form = PostForm() if form.validate_on_submit(): if current_user.is_admin: post = Post(body=form.body.data, teacher=current_user._get_current_object()) else: if len(current_user.sid) == 9: post = Post(body=form.body.data, teacher=current_user._get_current_object()) else: post = Post(body=form.body.data, student=current_user._get_current_object()) db.session.add(post) return redirect(url_for('post.posts')) page = request.args.get('page', 1, type=int) pagination = Post.query.order_by(Post.create_time.desc()).paginate( page, per_page=5, error_out=False) posts = pagination.items data = {'user_info': current_user.to_dict()} return render_template('post/post.html', form=form, posts=posts, data=data, pagination=pagination)
def user_post_detail(id): """在用户资料中心的我的文章里面文章详情页面,post必须以列表的形式传递到模板。因为_my_post里对文章显示时从列表里取""" post = Post.query.get_or_404(id) form = CommentForm() print(form.body.data) if form.validate_on_submit(): if len(current_user.sid) == 9: comment = Comment(body=form.body.data, post=post, teacher=current_user._get_current_object()) else: comment = Comment(body=form.body.data, post=post, student=current_user._get_current_object()) db.session.add(comment) flash('你发布了一条评论!') return redirect(url_for('post.user_post_detail', id=post.id, page=-1)) page = request.args.get("page", 1, type=int) # 用page = -1 来表示要访问最后一页的标志 # 下面的公式来计算一共有几页 if page == -1: page = (post.comments.count() - 1) // 10 + 1 pagination = post.comments.order_by(Comment.create_time.asc()).paginate( page, per_page=10, error_out=False) comments = pagination.items data = { 'user_info': current_user.to_dict(), } return render_template('post/user_post_detail.html', posts=[post], data=data, form=form, comments=comments, pagination=pagination)
def get(self): """Get current (logged in) user""" try: jsonsend = UserResponse.marshall_json(current_user.to_dict()) return jsonsend except Exception as error: return ErrorHandler(error).handle_error()
def authenticate(): """ Authenticates a user. """ if current_user.is_authenticated: return jsonify({'user': current_user.to_dict()}) return jsonify({'user': {'errors': ['Unauthorized']}}), 401
def restore(): id = current_user.id if current_user.is_authenticated else None user = None if not current_user.is_authenticated else current_user.to_dict( ) if current_user: # return {'csrf_token': generate_csrf(), 'current_user_id': id, "current_user": user} return {"current_user_id": id, "current_user": user}
def request_exists(form, field): title = field.data user = current_user.to_dict() request = Request.query.filter(Request.title == form.data["title"], Request.userId == user["id"]).first() if request: raise ValidationError("This request already exist")
def study_progress(): """ 该学生的学习情况,如果该学生选了该门课程,在老师点击结课后应显示已完成, 如果正在学习应该显示学习中。 """ # 找出选课记录里该学生的选课记录 course_records = Course_Record.query.\ filter(Course_Record.student_sid == current_user.sid).all() courses = [] total_credit = 0 # 通过选课记录里的course_sid找出该学生选过的课程 for course_record in course_records: course = Course.query.\ filter(Course.course_sid == course_record.course_sid).first() # 如果课程结课了,那么就可以将学分算到已获得学分里 if course_record.course_state: total_credit += course.credit_hour courses.append({ 'course': course, 'course_state': course_record.course_state, }) # print(courses) # for course in courses: # # print(course) # if not course.course_state: # total_credit += course.credit_hour data = { 'user_info': current_user.to_dict(), 'courses': courses, 'total_credit': total_credit, } return render_template('student/study_progress.html', data=data)
def edit_profile(): """View function that renders the page to allow a user to update their contact information""" admin_route = False upload_image_form = UploadImageForm() upload_image_form.image.errors = session.pop("image_form_errors", []) remove_image_form = RemoveImageForm() profile_form = EditProfileForm(current_user) if profile_form.validate_on_submit(): current_user.update(**profile_form.data) db.session.add(current_user._get_current_object()) db.session.commit() flash("Your profile information has been successfully updated.", "success") return redirect(url_for("users.edit_profile")) profile_form.populate(**current_user.to_dict()) return render_template( "users/edit_profile.html", profile_form=profile_form, upload_image_form=upload_image_form, remove_image_form=remove_image_form, user=current_user, admin_route=admin_route, profile_photo=current_user.profile_photo, )
def authenticate(): """ Authenticates a user. """ if current_user.is_authenticated: return current_user.to_dict() return {'errors': ['no user logged in']}, 401
def index(): if request.method == 'PUT': if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 username_or_email = request.json.get('usernameoremail', None) password = request.json.get('password', None) if not username_or_email or not password: return {"errors": ["Missing required parameters"]}, 400 authenticated1, user1 = User.authenticate1(username_or_email, password) authenticated2, user2 = User.authenticate2(username_or_email, password) if authenticated1: user = user1 authenticated = authenticated1 elif authenticated2: user = user2 authenticated = authenticated2 else: authenticated = False user = None if authenticated: login_user(user) return {"current_user_id": current_user.id, "current_user": current_user.to_dict()} return {"errors": ["Invalid credentials"]}, 401 if request.method == 'DELETE': logout_user() return {'msg': 'You have been logged out'}, 200
def post(self, data): upd_count = 0 if data.get("username"): current_user.username = data["username"] upd_count += 1 if data.get("email"): current_user.email = data["email"] current_user.email_verify = False email_sender( recipients=current_user.email, subject="Email address confirmation", template="mail/activation", token=encode_token({"user_id": str(current_user.id)}, reason="activation", expires_in=172800), username=current_user.username, ) upd_count += 1 if upd_count > 0: current_user.update_at = time_utcnow() current_user.save() return current_user.to_dict(get_token())
def authenticate(): """ Authenticates a user. """ if current_user.is_authenticated: return current_user.to_dict() return {'errors': ['Unauthorized']}
def richiesta_soccorso_intelligente(): user_lat = request.form.get('lat') user_long = request.form.get('long') if not user_lat or not user_long: abort(400) user_d = current_user.to_dict() request_to_ga = { 'user': { 'name': user_d.get('name'), 'surname': user_d.get('surname'), 'location': { 'lat': user_lat, 'long': user_long } } } ga_response = es_ga.nuova_richiesta_soccorso(request_to_ga) r_d = { 'user_id': current_user.get_id(), 'gestione_ambulanze_richiesta_id': ga_response.get('request_id'), 'ambulanza_associata': ga_response.get('ambulanza_associata'), 'data': '06/06/2018', 'stato': 'in corso' } new_request = db.RichiestaSoccorso(r_d) db.save(new_request) return jsonify(status='SUCCESS', request_id=new_request.to_dict().get('id'), message='Richiesta inoltrata con successo')
def sign_up(): if current_user.is_authenticated: return current_user.to_dict() form = SignUpForm(csrf_token=request.headers["x-Csrftoken"]) if form.validate_on_submit(): data = request.json user = User( firstname=data["firstname"], lastname=data["lastname"], username=data["username"], email=data["email"], password=data["password"], ) watchlist = UserList(userId=user.id, listName="Watch List") db.session.add(user) db.session.commit() newUser = User.query.filter( User.email == user.to_dict()["email"]).first() login_user(newUser) watchlist = UserList(userId=newUser.id, listName="Watch List") db.session.add(watchlist) db.session.commit() return user.to_dict() return form.errors, 401
def serialize_query(query, with_stats=False, with_visualizations=False, with_user=True, with_last_modified_by=True): d = { 'id': query.id, 'latest_query_data_id': query.latest_query_data_id, 'name': query.name, 'description': query.description, 'query': query.query_text, 'query_hash': query.query_hash, 'schedule': query.schedule, 'is_archived': query.is_archived, 'is_draft': query.is_draft, 'updated_at': query.updated_at, 'created_at': query.created_at, 'data_source_id': query.data_source_id, 'options': query.options, 'version': query.version, 'tags': query.tags or [], 'is_safe': query.parameterized.is_safe, 'user_id': current_user.id, 'created_by': query.user.to_dict(), 'user': current_user.to_dict(), 'folder_id': query.folder_id } if with_user: d['api_key'] = query.api_key #else: # d['user_id'] = query.user_id d['groups'] = [ g.to_dict(with_permissions_for=True) for g in models.QueryGroup.get_by_query(query) ] if with_last_modified_by: d['last_modified_by'] = query.last_modified_by.to_dict( ) if query.last_modified_by is not None else None else: d['last_modified_by_id'] = query.last_modified_by_id if with_stats: if query.latest_query_data is not None: d['retrieved_at'] = query.retrieved_at d['runtime'] = query.runtime else: d['retrieved_at'] = None d['runtime'] = None if with_visualizations: d['visualizations'] = [] for vis in query.visualizations: if vis.is_archived == False: d['visualizations'].append( serialize_visualization(vis, with_query=False)) return d
def download_own_data(): """Retrieve and download user data""" user_identifier = current_user.hash_identifier() user_results = Result.query.filter_by(identifier=user_identifier).all() user_data = { 'user': current_user.to_dict( include_student_of=True, include_teacher_of=True, include_examiner_of=True, include_groups=True ), 'results': [x.to_dict() for x in user_results], 'schedules': collect_schedule_data(user_identifier), 'questionnaires': [ x.get_questionnaire_for_user(current_user) for x in get_user_questionnaires(user_identifier) ] } print(user_data) file_path = f'{current_app.config["EXPORT_FOLDER"]}{token_urlsafe(6)}' if not os.path.exists(current_app.config["EXPORT_FOLDER"]): os.makedirs(current_app.config["EXPORT_FOLDER"]) with open(file_path, 'w+') as file: json.dump(user_data, file, indent=4) return send_file( file_path, mimetype='application/json', attachment_filename='my-data.json', as_attachment=True, cache_timeout=-1 )
def save_user_info(): values = request.json.get('values') for k, v in values.items(): setattr(current_user, k, v) db.session.add(current_user) db.session.commit() return jsonify(current_user.to_dict(access_token=False))
def base_info(): """修改基本信息""" # 展示基本信息 if request.method == 'GET': return render_template('user/user_base_info.html', user_info=current_user.to_dict()) username = request.json.get("username") age = request.json.get("age") school = request.json.get("school") sex = request.json.get('sex') if not sex in ["男", "女"]: return jsonify(errno=RET.DATAERR, errmsg="性别输入不正确!") # 修改用户数据 if username: current_user.username = username if age: current_user.age = age if school: current_user.school = school if sex: current_user.sex = sex db.session.commit() # 返回响应 return jsonify(errno=RET.OK, errmsg='修改成功!')
def pic_info(): if request.method == 'GET': return render_template('user/user_pic_info.html', user_info=current_user.to_dict()) # 3若果是post请求则获取文件 avatar = request.files.get('avatar') # 为空校验 if not avatar: return jsonify(errno=RET.PARAMERR, errmsg="未选择上传图片!") # 上传图片,判断图片是否上传成功 try: # 读取图片为二进制上传 image_name = image_store(avatar.read()) except: return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常!") if not image_name: return jsonify(errno=RET.NODATA, errmsg='图片上传失败!') # 将图片设置到用户的avatar_url里 current_user.avatar_url = image_name data = {"avatar_url": constants.QINIUYUN_DOMIN_PREFIX + image_name} # 返回响应 return jsonify(errno=RET.OK, errmsg="土拍你上传成功!", data=data)
def get(self, id=None): if id == None: #Если id не был дан, то возвращаем ошибку res = { 'status': 'error', 'message': 'Не найден обязательный параметр: id' } return jsonify(res) else: #Если дан id, то находим юзера с таким id obj = User.query.filter_by(id=id).first() if obj: # Нудно разграничить по провам res = {} if int(current_user.id) != int(id): # скрываем часть данных такие как пароль и т.д. keys = [ 'name', 'sname', 'activity', 'born', 'id', 'mail', 'phone', 'pname', 'rating' ] else: # чужой ползователь может получить только часть данных keys = ['name', 'sname', 'id'] user_data = current_user.to_dict() # res = {"name":"", "sname":"", } for key in keys: res[key] = user_data[key] return jsonify(res) else: #Иначе, возвращаем ошибку res = { 'status': 'error', 'message': 'По вашему запросу ничего не найдено' } return jsonify(res)
def authenticate(): """ Authenticates a user. """ if current_user.is_authenticated: return current_user.to_dict() return {"errors": ["Unauthorized"]}, 401
def login(): """ # 先查询用户是否存在,存在则校验密码。 :return: """ try: if current_user.is_authenticated: return jsonify({ 'status': 0, 'message': 'ok', 'data': { 'displayName': '李成龙', 'name': 'lichenglong', } # 'data': current_user.to_dict() }) if request.method == 'GET': return jsonify({ 'status': 0, 'message': 'ok', 'data': current_user.to_dict() }) if request.method == 'POST': data = request.get_json() user = query_user(data['username']) if not user: return jsonify({ 'status': 400, 'message': '用户名不存在,请输入正确的用户名!', 'data': data }) service = LoginService() login = service.check_password(data['password'], user) if not login: return jsonify({ 'status': 400, 'message': '密码不正确,请输入正确的密码!', 'data': data }) # 通过Flask-Login的login_user方法登录用户 login_user(user) login_user(user, True) session.permanent = True current_app.permanent_session_lifetime = datetime.timedelta( minutes=600) return jsonify({ 'status': 0, 'message': 'ok', 'data': user.to_dict() }) except Exception as error: return jsonify({ 'status': 500, 'message': str(error), 'trace': traceback.format_stack() })
def get_calendar_events(): """Gets dictionary of calendar events for teacher Returns ------- dict The view response """ req_data = request.get_json() if req_data: title = req_data["title"] start = req_data["start"] end = req_data["end"] color = req_data["color"] url = req_data["url"] newEvent = { "title": title, "start": start, "end": end, "color": color, "url": url, } teacherDict = current_user.to_dict() teacher = Teacher.get_by_email(teacherDict["email"]) current_user.add_calendar_event(teacher.id, newEvent) events = current_user.get_calendar() return response(data={"events": events})
def send_sup(username): user = User.query.filter_by(username=username).first() if user is None: return (flask.jsonify(message="Unknown user '{0}'".format(username)), 404) try: lat = float(flask.request.args.get("lng", None)) lng = float(flask.request.args.get("lng", None)) except ValueError: return flask.jsonify(message="Invalid coordinates"), 404 sup = Sup(current_user, user, lat, lng) db.session.add(sup) db.session.commit() return flask.jsonify(current_user.to_dict())
def index(): if current_user.is_authenticated(): return flask.jsonify(current_user.to_dict()) return flask.jsonify(message="s'up")
def get(self): print(current_user) if not current_user.is_authenticated: return {'error' : 'not logged in'} return current_user.to_dict()
def index(): session["logged_in"] = json.dumps(current_user.is_authenticated()) session["user"] = json.dumps(current_user.to_dict()) return render_template('index.html')