def info_reminder(): """ 进入消息提醒页面 :return: """ uid = current_user.id # 获取发送给该用户的所有信息 mongo_operator = MongoOperator(**MongoDB_CONFIG) collection = mongo_operator.get_collection('message') messages = collection.find({"to_id": uid}).sort([('date', -1)]) unchecked_message = [] checked_message = [] # 把信息分为已读和未读 for message in messages: if message['state'] == Message.CHECKED: checked_message.append(message) else: unchecked_message.append(message) # 标记未读的为已读 collection = mongo_operator.get_collection("message") collection.update_many({"to_id": uid}, {"$set": {"state": Message.CHECKED}}) return render_template("info_reminder.html", checked_message=checked_message, unchecked_message=unchecked_message)
def new_visit_record(): """ 插入新的拜访记录 :return: """ # 获取用户的uid uid = current_user.id record = { 'institution': request.form.get('institution'), 'school': request.form.get('school'), 'content': request.form.get('content'), 'date': request.form.get('date'), 'teacher': request.form.get('teacher'), 'title': request.form.get('title'), "user_id": uid, "user_name": current_user.name, "status": 1, } mongo_operator = MongoOperator(**MongoDB_CONFIG) try: # back => dict or None teacher_info = mongo_operator.get_collection("basic_info").find_one( {"name": record['teacher'], "school": record['school'], "institution": record['institution']}, {"id": 1}) if teacher_info is None: return json.dumps({'success': False, "message": "教师不存在,请检查输入的信息"}) record['teacher_id'] = teacher_info['id'] # 插入拜访记录 result = mongo_operator.get_collection('visit_record').insert_one(record) # 是否存在完善的信息 external_info = {'type': 'modify', 'status': 1, 'username': current_user.name, 'timestamp': datetime.datetime.utcnow()} modifying = False external_keys = [ ('position', 'position'), ('teacher-title', 'title'), ('telephone', 'phone_number') , ('email', 'email'), ('office-phone', 'office_number'), ('department', 'department')] for key in external_keys: whole_key = 'basic_info[%s]' % key[0] if whole_key in request.form: modifying = True external_info[key[1]] = request.form[whole_key] # 更新老师信息 并写入到反馈中 if modifying: teacher_info.update(external_info) teacher_info['teacher_id'] = teacher_info.pop('id') # 写入数据库 mongo_operator.db['agent_feedback'].insert_one(teacher_info) # 多线程执行插入用户与教师的关系 threading.Thread(target=upsert_relation_of_visited, args=(uid, record['teacher_id'], teacher_info['name'])).start() # upsert_relation_of_visited(uid, teacher_info['id'], teacher_info['name']) return json.dumps({'success': True, 'record_id': str(result.inserted_id)}) except Exception as e: print("插入新拜访记录出错,原因:%s" % e) return json.dumps({'success': False, "message": "插入失败, 请确认数据是否正确"})
def get_edit_institution(school, mongo=None): """ 获取mongo数据库中所有的学校学院 :return: """ if mongo is None: mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection("institution") institution_list = collection.find({ "school": school, "relation_data": 1 }, { "_id": 0, "select": 1, "institution": 1, "dfc_num": 1, "nkd_num": 1, "skl_num": 1 }) institution = {} institution['main_institution'] = [] institution['dis_main_institution'] = [] institution['no_relation_data'] = [] for i in institution_list: if (i['dfc_num'] > 0 and i['nkd_num'] > 0) or i['skl_num'] > 0: institution['main_institution'].append( [i['institution'], i['select']]) else: institution['dis_main_institution'].append( [i['institution'], i['select']]) return institution
def get_school_info(school_name, mongo=None): """ 根据学校名获取学校的简介信息 :param school_name: 学校名 :param mongo: MongoOperator对象 :return ((院士,数目)...) """ if mongo is None: mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection("school") school_info = collection.find_one({"name": school_name}, { "_id": 0, "institutions": 1, "dfc_num": 1, "nkd_num": 1, "skl_num": 1, "academician_num": 1, "outstanding_num": 1, "cjsp_num": 1 }) if school_info is None: return None keys = [('academician_num', '院士'), ('cjsp_num', '长江学者'), ('dfc_num', '一流学科'), ('nkd_num', '重点学科'), ('outstanding_num', '杰出青年'), ('skl_num', '重点实验室')] objects = [] for key, value in keys: objects.append((value, school_info[key])) return objects
def _get_details(teacher_ids): """ 根据老师的id数组获取老师的相关信息 :param teacher_ids: :return: """ mongo = MongoOperator(**MongoDB_CONFIG) # 获取学校 collection = mongo.get_collection('basic_info') condition = {'id': {'$in': teacher_ids}} teachers = collection.find(condition, { '_id': 0, 'id': 1, 'title': 1, 'honor_title': 1 }) teacher_map = {} for teacher in teachers: if len(teacher['honor_title']) > 0: teacher['category'] = teacher['honor_title'][0]['type'] elif len(teacher['title'].strip()) == 0: teacher['category'] = '未知' else: teacher['category'] = teacher['title'] teacher_map[teacher['id']] = teacher return teacher_map
def validate_relationship(self, field): """ 自定义验证器,会验证relationship字段的值与数据库的值是否匹配 :param field: relationship字段 当id未找到或者名称等不匹配时都会验证失败 当验证不通过会抛出ValidateError错误 """ self.results = json.loads(field.data) ids = [result['teacherID'] for result in self.results] mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection('basic_info') # 验证id是否和名字 学校 学院匹配 teachers = collection.find({'id': { '$in': ids }}, { '_id': 0, 'id': 1, 'name': 1, 'school': 1, 'institution': 1 }) # 验证通过的个数 nums = 0 for teacher in teachers: for result in self.results: if teacher['id'] == result['teacherID']: if teacher['school'] != result['school'] or teacher['name'] != result['name'] or\ teacher['institution'] != result['institution']: raise ValidationError('合作关系验证失败,请确定老师后重试') else: nums += 1 if nums != len(ids): raise ValidationError('合作关系验证失败,请确定老师后重试')
def save_basic_info(): """ 保存用户修改的基本信息 :return:修改成功: {"success": True}, 修改失败: {"success": False} """ user_id = request.form.get("user_id") user_id = int(user_id) user_name = request.form.get("user_name") user_email = request.form.get("user_email") user_tel = request.form.get("user_tel") mongo = MongoOperator(**MongoDB_CONFIG) user_col = mongo.get_collection("user") try: update_res = user_col.update({'id': user_id}, {"$set": { "name": user_name, "email": user_email, "tel_number": user_tel, }}) if update_res['nModified'] != 0: current_user.name = user_name current_user.email = user_email current_user.tel_number = user_tel return json.dumps({"success": True}) except: return json.dumps({"success": False})
def deprecated_index(): # 获取当前商务负责的学校 / 学院及其建立的关系 mongo_operator = MongoOperator(**MongoDB_CONFIG) # 获取用户的uid uid = current_user.id user_info = {} if "charge_school" in current_user: user_info = { 'charge_school': current_user['charge_school'], "related_teacher": current_user['related_teacher'] } else: # 获取该商务的信息 user_info = mongo_operator.get_collection("user").find_one({"id": uid}) if not ("related_teacher" in user_info): user_info["related_teacher"] = None if not ("charge_school" in user_info): user_info["charge_school"] = None current_user["charge_school"] = user_info['charge_school'] current_user["related_teacher"] = user_info["related_teacher"] schools = user_info['charge_school'] if schools: # 仅仅获取第一个学校的学院数组 institutions = agent_service.get_institutions_list(schools[0]) return render_template('personal.html', schools=schools, institutions=institutions) else: return render_template('personal.html', schools=[], institutions=[])
def get_teachers(teacher_name): """ 根据老师的名字进行数据库的搜索 :param teacher_name: 老师名字 :return: 如果request.args存在is_json且为True,则返回json格式的字符串,否则直接返回python数组 """ # 是否把结果转换成json格式的字符串,默认为False result = None is_json = request.args.get('is_json', type=bool, default=False) # 是否进行模糊查询 is_like = request.args.get('is_like', type=bool, default=False) try: # 查询数据库 mongo_operator = MongoOperator(**MongoDB_CONFIG) # 模糊查询 if is_like: condition = {'name': {'$regex': teacher_name + '.*?'}} else: condition = {'name': teacher_name} scope = {'title': 1, 'school': 1, 'institution': 1, 'name': 1, '_id': 0, 'id': 1} generator = mongo_operator.get_collection('basic_info').find(condition, scope) teachers = list(generator) result = json.dumps(teachers) if is_json else teachers except Exception as e: print('error raised when get teacher: %s' % e) return result
def scholar_info(teacher_id): """ 获取专家个人信息 :param teacher_id: :return: """ # 返回json 序列化后的数据 teacher = basic_info_service.get_info(teacher_id) team_list = basic_info_service.get_teacher_central_network(teacher_id) team_id_list = [] for i in team_list: team_id_list.append(i['id']) team_info = basic_info_service.get_team_info(team_id_list) # 当老师id不存在时,直接报404 if teacher is None: return abort(404) # 获取拜访记录 visit_list = None try: mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection("visit_record") user_id = current_user.id # 找到对应的拜访记录信息, 按时间排序, 最多5个 visit_info = collection.find({"user_id": user_id, "status": 1, "teacher_id": teacher_id}, {"_id": 0, "date": 1, "title": 1, "content": 1, "user_name": 1}).sort("date", -1).limit(5) # 转成列表 visit_list = list(visit_info) except Exception as e: print('get_visit_info error:%s' % e) return render_template('scholar/detail.html', teacher=teacher, visit_list=visit_list,team_info=team_info)
def feedback_get(teacher_id): """ 老师信息的反馈页面的GET方法 显示页面 :return: """ cur_school = None cur_institution = None form = ScholarForm() try: mongo = MongoOperator(**MongoDB_CONFIG) # 填充数据 if teacher_id: result = mongo.get_collection('basic_info').find_one({'id': teacher_id}, {'_id': 0}) cur_school, cur_institution = result['school'], result['institution'] form.set_data(result) # 获取所有的学校 cur_school, schools, institutions = school_service.get_schools_institutions(mongo=mongo, cur_school=cur_school) form.set_schools(schools, cur_school) form.set_institutions(institutions, cur_institution) title = '添加老师' if teacher_id is None else '修改老师信息' return render_template('scholar/teacher_feedback.html', form=form, title=title) except Exception as e: print('when feedback: %s' % e) abort(404)
def check_user(username, password): """ 根据账户名密码 :param username:用户名(str) :param password: 原始密码(str) :return: 字典对象{'ID': 1, 'NAME': '测试账号', 'TYPE': '1'} or None """ tel = re.compile(r"^\d{11}$") email = re.compile(r"^[\w\d]+@[\w\d]+\.com$") u_id = re.compile(r"^\d{6,8}$") # 加密密码 password = encrypt.encryption(password) # 查询条件 condition = {'password': password, "status": "1"} # 以电话登陆 if tel.match(username): condition['tel_number'] = username # 以邮件登陆 elif email.match(username): condition['email'] = username # 以 id 登陆 elif u_id.match(username): condition['id'] = int(username) else: return None # 连接服务器 mongo = MongoOperator(**MongoDB_CONFIG) # 除_id 外全部获取 result = mongo.get_collection('user').find_one(condition, {"_id": 0}) if result: return User(**result) return None
def get_institution_info(school, institution): """ 获取学校中该学院的相关信息 :param school: 学校名称 :param institution: 学院名称 :return: 学科、荣誉头衔和个数tuple数组,如果不存在学校.学院则返回None """ mongo = MongoOperator(**MongoDB_CONFIG) # 获取学校 collection = mongo.get_collection('institution') result = collection.find_one({ 'school': school, 'institution': institution }, { '_id': 0, 'school': 0, 'institution': 0 }) # 学校或院系不存在 if result is None: return None keys = [('academician_num', '院士'), ('cjsp_num', '长江学者'), ('dfc_num', '一流学科'), ('nkd_num', '重点学科'), ('outstanding_num', '杰出青年'), ('skl_num', '重点实验室')] objects = [] for key, value in keys: objects.append((value, result[key])) return objects
def get_team_info(teacher_id_list): """ 根据教师团队的id收集 :param teacher_id_list:教师团队中所有老师的ID :return:team_info:教师团队的项目、专利和论文数据 """ team_info = {} team_info["patents"] = [] team_info["projects"] = [] team_info["papers"] = [] for i in teacher_id_list: try: mongo = MongoOperator(**MongoDB_CONFIG) # 获取老师基本信息 basic_info = mongo.get_collection('basic_info').find_one( {'id': i}, {'_id': 0}) # 获取项目集合 if 'project_id' in basic_info and len( basic_info["project_id"]) > 0: team_info["projects"].extend( getProjectsInfo(mongo, basic_info["project_id"])) # 获取专利集合 if 'patent_id' in basic_info and len(basic_info["patent_id"]) > 0: team_info["patents"].extend( getPatentInfo(mongo, basic_info["patent_id"])) # 获取论文数据集合 if 'paper_id' in basic_info and len(basic_info["paper_id"]) > 0: team_info["papers"].extend( getPaperInfo(mongo, basic_info["paper_id"])) except: pass #排除重复项 run_function = lambda x, y: x if y in x else x + [y] team_info['papers'] = reduce(run_function, [ [], ] + team_info['papers']) team_info['patents'] = reduce(run_function, [ [], ] + team_info['patents']) team_info['projects'] = reduce(run_function, [ [], ] + team_info['projects']) # #按时间排序 team_info['papers'] = sorted(team_info['papers'], key=lambda x: x['year'], reverse=True)[0:30] # True 是倒叙 默认是False team_info['patents'] = sorted(team_info['patents'], key=lambda x: x['date'], reverse=True)[0:30] team_info['projects'] = sorted(team_info['projects'], key=lambda x: x['start_time'], reverse=True)[0:30] return team_info
def get_agents(): """ 获取所有的用户,并返回一个字典数组{name,id} :return: """ mongo_operator = MongoOperator(**MongoDB_CONFIG) collection = mongo_operator.get_collection("user") # 仅仅需要id和name results = collection.find({}, {"name": 1, "id": 1, "_id": 0}) users = list(results) return json.dumps(users, ensure_ascii=False)
def get_user_by_email(email): """ 根据email获取对应的用户,如果邮箱不存在则返回None :param email: :return: """ # 数据库查询 mongo_operator = MongoOperator(**MongoDB_CONFIG) collection = mongo_operator.get_collection("user") user = collection.find_one({'email': email}) return user
def get_institutions(school): """ 根据学校的名称获取学院列表 :param school: :return: """ mongo_operator = MongoOperator(**MongoDB_CONFIG) # 获取当前学校的所有院系 condition = {'name': school} school = mongo_operator.get_collection('school').find_one(condition, {'_id': 0, 'institutions': 1}) return json.dumps(school['institutions'])
def get_info(teacher_id): """ 根据教师的id从MongoDB中获取教师的基本信息 :param teacher_id: :return: """ basic_info = None try: mongo = MongoOperator(**MongoDB_CONFIG) # 是否存在该老师 basic_info = mongo.get_collection('basic_info').find_one( {'id': teacher_id}, {'_id': 0}) if basic_info is None: return basic_info # 荣誉头衔排序,按时间,倒序 if 'honor_title' in basic_info and len(basic_info['honor_title']) > 0: basic_info['honor_title'].sort(key=lambda k: (k.get('year', 0)), reverse=True) # 获取项目集合 if 'project_id' in basic_info and len(basic_info["project_id"]) > 0: basic_info["projects"] = getProjectsInfo(mongo, basic_info["project_id"]) # 获取专利集合 if 'patent_id' in basic_info and len(basic_info["patent_id"]) > 0: basic_info["patents"] = getPatentInfo(mongo, basic_info["patent_id"]) # 获取论文数据集合 if 'paper_id' in basic_info and len(basic_info["paper_id"]) > 0: basic_info["papers"] = getPaperInfo(mongo, basic_info["paper_id"]) # 获取获奖情况 if 'award_id' in basic_info and len(basic_info["award_id"]) > 0: basic_info["awards"] = getAwardInfo(mongo, basic_info["award_id"]) # 计算教师年龄 birth_year = basic_info["birth_year"] # 如果存在birth_year字段且为空,则不计算age if birth_year: basic_info['age'] = datetime.datetime.now().year - int(birth_year) # print(basic_info) return basic_info except Exception as e: print("------exception------ ", e) return basic_info
def get_total_institutions(school_name, mongo=None): """ 根据学校名获取学校中的重点学院和非重点学院,将有一流学科并且有重点学科或者拥有国家重点实验室的学院定位重点学院 :param school_name:学校名 :param mongo:为空则自己创建一个mongo :return: """ if mongo is None: mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection("institution") institution = collection.find( { "school": school_name, "relation_data": 1, "select": 1 }, { "_id": 0, "institution": 1, "dfc_num": 1, "nkd_num": 1, "skl_num": 1 }) # 重点学院 main_institution = [] # 非重点学院 dis_main_institution = [] for i in institution: # 筛选同时拥有一流学科和重点学科的学院或者拥有国家重点实验室的学院为重点学院 if (i['dfc_num'] > 0 and i['nkd_num'] > 0) or i['skl_num'] > 0: main_institution.append(i['institution']) else: dis_main_institution.append(i['institution']) data = {} data['name'] = school_name data['children'] = [] main_institution_dict = {} main_institution_dict['name'] = "重点学院" main_institution_children = [] for i in main_institution: main_institution_children.append({"name": i}) main_institution_dict['children'] = main_institution_children dis_main_institution_dict = {} dis_main_institution_dict['name'] = "非重点学院" dis_main_institution_children = [] for i in dis_main_institution: dis_main_institution_children.append({"name": i}) dis_main_institution_dict['children'] = dis_main_institution_children data['children'].append(main_institution_dict) data['children'].append(dis_main_institution_dict) return data
def get_user_by_id(user_id): """ 根据user_id 获取对应的用户,如果不存在返回None :param user_id: :return: User对象或者None """ mongo_operator = MongoOperator(**MongoDB_CONFIG) collection = mongo_operator.get_collection("user") datum = collection.find_one({'id': int(user_id)}) # 转化成对象 user = None if datum: user = User(**datum) return user
def set_password(user, new_password): """ 为某个用户赋予新的密码 :param user: 用户字典 :param new_password: 新的密码 :return: 操作成功则返回True """ mongo_operator = MongoOperator(**MongoDB_CONFIG) collection = mongo_operator.get_collection("user") # 为密码加密 password_hash = encrypt.encryption(new_password) # 更新数据库 condition = {'id': user['id']} user['password'] = password_hash result = collection.update_one(condition, {'$set': user}) return result.matched_count == 1
def change_pwd_in_db(new_pwd): """ 根据输入的新密码对用户数据库中的密码进行修改 :param new_pwd:新密码 :return:密码修改失败: {"success": False}, 修改成功: {"success": True} """ user_id = current_user.id pwd_md5 = encryption(new_pwd) try: mongo = MongoOperator(**MongoDB_CONFIG) user_col = mongo.get_collection("user") user_col.update({"id": user_id}, {"$set": {"password": pwd_md5}}) return json.dumps({"success": True}) except: return json.dumps({"success": False})
def get_all_institution(school, mongo=None): """ 获取mongo数据库中此学校的所有学院 :return: """ if mongo is None: mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection("institution") institution_list = collection.find({"school": school}, { "_id": 0, "institution": 1 }) institution = [] for i in institution_list: institution.append(i['institution']) return institution
def get_schools(): """ by zhang 获取所有学校的名称组成的列表 :return: """ mongo = MongoOperator(**MongoDB_CONFIG) try: school_col = mongo.get_collection("school") schools = list(school_col.find({}, {"_id": 0, "name": 1})) # 转成学校列表 school_list = [school["name"] for school in schools] return json.dumps({"success": True, "school_list": school_list}) except Exception as e: print(e) return json.dumps({"success": False, "school_list": []})
def get_institution(school, mongo=None): """ 获取mongo数据库中没有关系网络的学校学院 :return: """ if mongo is None: mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection("institution") institution = collection.find({ "school": school, "relation_data": 0 }, { "_id": 0, "school": 1, "institution": 1 }) return institution
def update_institution_select(school, institution_select, mongo=None): """ 更新institution中select字段 :param school: 学校名 :param institution_select: 选择的学院信息 :param mongo: 数据库 :return: """ if mongo is None: mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection("institution") for i in institution_select: collection.update_one({ "school": school, "institution": i[0] }, {"$set": { "select": i[1] }})
def detail(objectId): """ 根据objectId获取对应的拜访记录的所有内容 :param objectId: mongoDb的主键 objectId :return: """ record = None try: mongo_operator = MongoOperator(**MongoDB_CONFIG) condition = {"_id": ObjectId(objectId)} record = mongo_operator.get_collection('visit_record').find_one(condition, {'_id': 0}) # 拜访记录的内容 进行安全转义 if 'content' in record: record['content'] = Markup(record['content']) except Exception as e: print('error raised when viewing the detail of visit record %s' % e) if record is None: abort(404) return render_template('visit_record/detail.html', record=record)
def update_institution_relation_data(school, institution, mongo=None): """ 有此学校学院的关系数据网络则在此学院的字段添加字段relation_data为1,否则为0 :return: """ if mongo is None: mongo = MongoOperator(**MongoDB_CONFIG) collection = mongo.get_collection("institution") if (is_exist_data(school, institution)): collection.update_one({ "school": school, "institution": institution }, {"$set": { "relation_data": 1 }}) else: collection.update_one({ "school": school, "institution": institution }, {"$set": { "relation_data": 0 }})
def get_schools_institutions(cur_school=None, mongo=None): """ 获取目前的所有的学校和cur_school对应的所有学院 :param cur_school: 当前选中的学校,如为None则默认获取第一个 :param mongo: 为空则自己创建一个mongo :return: (学校数组,学院列表) """ pass if mongo is None: mongo = MongoOperator(**MongoDB_CONFIG) # 获取学校 collection = mongo.get_collection('school') generator = collection.find({}, {'_id': 0, 'name': 1}) schools = [school['name'] for school in generator] # 确定当前选择的学校 cur_school = schools[0] if cur_school is None else cur_school # 获取当前学校的所有院系 school = collection.find_one({'name': cur_school}, { '_id': 0, 'institutions': 1 }) institutions = [result['name'] for result in school['institutions']] return cur_school, schools, institutions
def schedule(): """ 显示日程安排页面 :return: """ # 获取用户的id user_id = current_user.id mongo_operator = MongoOperator(**MongoDB_CONFIG) # 选定集合 schedule_col = mongo_operator.get_collection("schedule") # 找到对应的user ,根据提醒日期对日程进行降序排序 schedule_list = schedule_col.find({ "user_id": user_id, "status": 1 }).sort([("remind_date", 1)]) schedule_list = list(schedule_list) now = datetime.datetime.now() for item in schedule_list: remind_date = datetime.datetime.strptime(item["remind_date"], "%Y-%m-%d") # 计算该日程距离今天还有几天,计算结果向下取整 # 由于 now 有 时分秒存在,计算结果会比正常理解小1, 例如提醒日期就是今天,结果为 -1 diff = remind_date - now # 距离设定的提醒日期多余1天 if diff.days < -1: item["bg"] = "bg-danger" elif diff.days == -1: item['bg'] = "bg-warning" else: item['bg'] = "" return render_template("schedule.html", schedule_list=schedule_list)