def resp_personal_info(): response = {} if request.method == 'POST': data = eval(str(request.data, encoding="utf-8")) resp = db_operate(db_server, "personal_info", "create", data=data) response['resp'] = resp return response elif request.method == 'DELETE': data = eval(str(request.data, encoding="utf-8")) id = data['_id'] resp = db_operate(db_server, "personal_info", "delete", id=id) response['resp'] = resp return response elif request.method == 'PUT': data = eval(str(request.data, encoding="utf-8")) resp = db_operate(db_server, "personal_info", "update", data=data) response['resp'] = resp return response elif request.method == 'GET': id = request.args.get('id') resp, list_info = db_operate(db_server, "personal_info", "get", id=id) response['resp'] = resp response['list_info'] = list_info return response
def db_online_info(db_server, operation, id ='', status =''): # Validate the database. try: db = db_server['online_info'] except ResourceNotFound: print('There is no database named online_info!') return 405 # Validate the data. try: assert type(status) == str except AssertionError: print('The online status should be in str form!') return 408 # Update status. if operation.lower() == 'update': try: doc = db[id] db.purge([doc]) db.compact() except ResourceNotFound: pass new_content = {'_id': id, 'status': status} db.save(new_content) return 200 # Get status. elif operation.lower() == 'get': if type(id) != list: id = [id] list_info = {} for i in range(len(id)): try: doc = dict(db[id[i]]) list_info[doc['_id']] = doc['status'] except ResourceNotFound: print('There is no such a file!') return 200, list_info # Update status. elif operation.lower() == 'delete': resp = db_op.db_operate(db_server, 'online_info', 'delete', id = id) return resp
def verify_step1(db_server, user_name): accounts_db = db_server['accounts'] record_list = accounts_db.view('auth/auth', start_key=[user_name], end_key=[user_name + 'CHANGE']) if len(record_list) == 0: return 404 record_list = list(record_list) account_id = record_list[0].value resp, verify_code = send_verify_code(user_name) if resp != 200: return resp data = { '_id': account_id, 'user_name': user_name, 'verify_code': verify_code, 'verify_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") } resp = db_op.db_operate(db_server, 'verify', 'update', data=data) return resp
def resp_account_forgetpwd(): response = {} if request.method == 'GET': user_name = request.args.get('user_name') resp = forget_pwd.verify_step1(db_server, user_name) response['resp'] = resp return response elif request.method == 'POST': data = eval(str(request.data, encoding="utf-8")) user_name = data['user_name'] verify_code = data['verify_code'] resp, id = forget_pwd.verify_step2(db_server, user_name, verify_code) response['resp'] = resp response['gen_id'] = id return response elif request.method == 'DELETE': id = request.args.get('id') print(id) resp = db_op.db_operate(db_server, 'verify', 'delete', id=id) response['resp'] = resp return response
def db_distance(db_server, operation, id=[], data={}, ranking_type='daily'): from datetime import timedelta db = db_server['distance'] # Create distance record. if operation.lower() == 'create': try: if type(data['distance']) == str: data['distance'] = float(data['distance']) new_data = {} new_data['_id'] = data['_id'] record_time = datetime.datetime.strptime(data['start_time'], "%Y-%m-%d %H:%M:%S") new_data['this_day'] = record_time.date().strftime("%Y-%m-%d") new_data['daily_distance'] = data['distance'] new_data['this_week'] = ( record_time - timedelta(days=record_time.weekday())).strftime("%Y-%m-%d") new_data['week_distance'] = data['distance'] new_data['this_month'] = datetime.datetime(record_time.year, record_time.month, 1).strftime("%Y-%m-%d") new_data['month_distance'] = data['distance'] new_data['this_year'] = datetime.datetime(record_time.year, 1, 1).strftime("%Y-%m-%d") new_data['year_distance'] = data['distance'] new_data['total_distance'] = data['distance'] new_data['record_time'] = data['start_time'] new_data['latest_ave_speed'] = data['ave_speed'] new_data['total_sessions'] = 1 if data['status'] == 'completed': new_data['completed_sessions'] = 1 else: new_data['completed_sessions'] = 0 print(new_data) db.save(new_data) return 200 except ResourceConflict: print("Info already existed!") return 406 # Update distance record. elif operation.lower() == 'update': id = data['_id'] try: if type(data['distance']) == str: data['distance'] = float(data['distance']) doc = db[id] current_record = dict(doc) # Check data uniqueness. if (current_record['record_time'] == data['start_time']): print('Duplicate data!') return 406 del current_record['_rev'] db_record_time = datetime.datetime.strptime( current_record['record_time'], "%Y-%m-%d %H:%M:%S") record_time = datetime.datetime.strptime(data['start_time'], "%Y-%m-%d %H:%M:%S") current_record['total_distance'] += data['distance'] current_record['total_sessions'] += 1 if data['status'] == 'completed': current_record['completed_sessions'] += 1 db_day = current_record['this_day'] db_week = current_record['this_week'] db_month = current_record['this_month'] db_year = current_record['this_year'] record_day = record_time.date().strftime("%Y-%m-%d") record_week = ( record_time - timedelta(days=record_time.weekday())).strftime("%Y-%m-%d") record_month = datetime.datetime(record_time.year, record_time.month, 1).strftime("%Y-%m-%d") record_year = datetime.datetime(record_time.year, 1, 1).strftime("%Y-%m-%d") # New data if record_time > db_record_time: current_record['latest_ave_speed'] = data['ave_speed'] current_record['record_time'] = data['start_time'] if db_day != record_day: current_record['daily_distance'] = data['distance'] current_record['this_day'] = record_day else: current_record['daily_distance'] += data['distance'] if db_week != record_week: current_record['week_distance'] = data['distance'] current_record['this_week'] = record_week else: current_record['week_distance'] += data['distance'] if db_month != record_month: current_record['month_distance'] = data['distance'] current_record['this_month'] = record_month else: current_record['month_distance'] += data['distance'] if db_year != record_year: current_record['year_distance'] = data['distance'] current_record['this_year'] = record_year else: current_record['year_distance'] += data['distance'] # Old data. else: if db_day == record_day: current_record['daily_distance'] += data['distance'] if db_week == record_week: current_record['week_distance'] += data['distance'] if db_month == record_month: current_record['month_distance'] += data['distance'] if db_year == record_year: current_record['year_distance'] += data['distance'] db.purge([doc]) db.compact() db.save(current_record) except ResourceNotFound: db_distance(db_server, 'create', data=data) return 200 # Get distance record. elif operation.lower() == 'get': if type(id) != list: id = [id] record_detail = [] for i in range(len(id)): current_id = id[i] try: doc = dict(db[current_id]) del doc['_rev'] record_detail.append(doc) except ResourceNotFound: pass return 200, record_detail # Get ranking. elif operation.lower() == 'get_ranking': personal_info_db = db_server['personal_info'] if type(id) != list: id = [id] now = datetime.datetime.now() if ranking_type == 'daily': this_item = now.date().strftime("%Y-%m-%d") record_keyword = 'daily_distance' date_keyword = 'this_day' distance_keyword = 'daily_distance' elif ranking_type == 'weekly': this_item = (now - timedelta(days=now.weekday())).strftime("%Y-%m-%d") date_keyword = 'this_week' distance_keyword = 'week_distance' elif ranking_type == 'monthly': this_item = datetime.datetime(now.year, now.month, 1).strftime("%Y-%m-%d") date_keyword = 'this_month' distance_keyword = 'month_distance' elif ranking_type == 'yearly': this_item = datetime.datetime(now.year, 1, 1).strftime("%Y-%m-%d") date_keyword = 'this_year' distance_keyword = 'year_distance' record_detail = {} for i in range(len(id)): current_id = id[i] info_list = {} try: doc = dict(db[current_id]) distance = doc[distance_keyword] if 'latest_ave_speed' in doc.keys(): ave_speed = doc['latest_ave_speed'] else: ave_speed = 0 if doc[date_keyword] == this_item: info_list['distance'] = distance info_list['ave_speed'] = ave_speed else: info_list['distance'] = 0 info_list['ave_speed'] = 0 except ResourceNotFound: info_list['distance'] = 0 info_list['ave_speed'] = 0 # Add user's name into it. try: doc1 = dict(personal_info_db[current_id]) info_list['first_name'] = doc1['first_name'] info_list['last_name'] = doc1['last_name'] except ResourceNotFound: info_list['first_name'] = '' info_list['last_name'] = '' except: return 404, [] record_detail[current_id] = info_list rank = sorted(record_detail.items(), key=lambda kv: (kv[1]['distance'], kv[0]), reverse=True) return 200, rank # Delete distance record. elif operation.lower() == 'delete': resp = db_op.db_operate(db_server, 'distance', operation, id=id) return resp
def db_moments(db_server, operation, id='', query_key=[], data={}): db = db_server['moments'] # Insert new moments if operation.lower() == 'create': # Check uniqueness of the record. cond = [data['user_id'], data['time']] record_list = db.view('moments_info/moments_info', start_key=cond, end_key=cond) if len(record_list) != 0: print("Moment is already existed!") return 406, '' data['like_num'] = 0 data['like_list'] = [] doc = db.save(data) return 200, doc[0] # Make comments. elif operation.lower() == 'comment': id = data["_id"] try: doc = db[id] new_content = dict(doc) del data['_id'] new_content['comments'].append(data) del new_content['_rev'] db.purge([doc]) db.compact() db.save(new_content) return 200 except ResourceNotFound: print("There is no such a moment.") return 404 # Query moments. elif operation.lower() == 'get_by_query': record_list = db.view('moments_info/moments_info', start_key=query_key[0], end_key=query_key[1]) if len(record_list) == 0: return 404, [] record_detail = [] for row in record_list: doc = db[row.value] record_detail.append(dict(doc)) print(record_detail) return 200, record_detail # Get moments by id. elif operation.lower() == 'get_by_id': resp, record_detail = db_op.db_operate(db_server, 'moments', operation='get', id=id) return resp, record_detail # Delete moments. elif operation.lower() == 'delete_by_id': resp = db_op.db_operate(db_server, 'moments', operation='delete', id=id) return resp elif operation.lower() == 'delete_by_query': record_list = db.view('moments_info/moments_info', start_key=query_key[0], end_key=query_key[1]) if len(record_list) == 0: return 404 for row in record_list: doc = db[row.value] db.purge([doc]) db.compact() return 200 elif operation.lower() == 'friends_moments': import datetime personal_info_db = db_server['personal_info'] if type(id) != list: id = [id] moment_list = [] for id_item in id: record_list = db.view('moments_info/moments_info', start_key=[id_item], end_key=[id_item + 'CHANGE']) if len(record_list) == 0: continue else: for row in record_list: moment_id = row.value try: doc = dict(db[moment_id]) # Get user_name user_id = doc['user_id'] try: doc1 = dict(personal_info_db[user_id]) doc['first_name'] = doc1['first_name'] doc['last_name'] = doc1['last_name'] except ResourceConflict: doc['first_name'] = '' doc['last_name'] = '' # Get comment user name if len(doc['comments']) > 0: for i in range(len(doc['comments'])): user_id = doc['comments'][i]['user_id'] try: doc1 = dict(personal_info_db[user_id]) doc['comments'][i]['first_name'] = doc1[ 'first_name'] doc['comments'][i]['last_name'] = doc1[ 'last_name'] except ResourceConflict: doc['comments'][i]['first_name'] = '' doc['comments'][i]['last_name'] = '' moment_list.append(doc) except ResourceConflict: continue sorted_moments = sorted(moment_list, key=lambda kv: datetime.datetime.strptime( kv['time'], "%Y-%m-%d %H:%M:%S"), reverse=True) return 200, sorted_moments elif operation.lower() == 'like': try: doc = dict(db[id]) new_data = doc.copy() del new_data['_rev'] like_list = new_data['like_list'] if data['user_id'] in like_list: return 406 else: new_data['like_num'] += 1 new_data['like_list'].append(data['user_id']) db.purge([doc]) db.compact() db.save(new_data) return 200 except ResourceConflict: return 404 elif operation.lower() == 'dislike': try: doc = dict(db[id]) new_data = doc.copy() del new_data['_rev'] like_list = new_data['like_list'] if data['user_id'] in like_list: new_data['like_num'] -= 1 new_data['like_list'].remove(data['user_id']) db.purge([doc]) db.compact() db.save(new_data) return 200 else: return 404 except ResourceConflict: return 404
def db_running_record(db_server, operation, id='', query_key=[], data={}): db = db_server['running_record'] # Insert new running record. if operation.lower() == 'create': # Check uniqueness of the record. cond = [data['user_id'], data['start_time']] record_list = db.view('running_info/running_info', start_key=cond, end_key=cond) if len(record_list) != 0: print("Record is already existed!") return 406, '' if type(data['distance']) == str: data['distance'] = float(data['distance']) doc = db.save(data) id = data['user_id'] data['_id'] = id distance.db_distance(db_server, 'update', data=data) return 200, doc[0] # Query running record. elif operation.lower() == 'get_by_query': record_list = db.view('running_info/running_info', start_key=query_key[0], end_key=query_key[1]) if len(record_list) == 0: return 404, [] import datetime record_detail = [] for row in record_list: doc = db[row.value] record_detail.append(dict(doc)) sorted_records = sorted(record_detail, key=lambda kv: datetime.datetime.strptime( kv['start_time'], "%Y-%m-%d %H:%M:%S"), reverse=True) return 200, sorted_records # Get running record by id. elif operation.lower() == 'get_by_id': resp, record_detail = db_op.db_operate(db_server, 'running_record', operation='get', id=id) return resp, record_detail # Delete running record. elif operation.lower() == 'delete_by_id': resp = db_op.db_operate(db_server, 'running_record', operation='delete', id=id) return resp elif operation.lower() == 'delete_by_query': record_list = db.view('running_info/running_info', start_key=query_key[0], end_key=query_key[1]) if len(record_list) == 0: return 404 for row in record_list: try: doc = db[row.value] db.purge([doc]) db.compact() except ResourceNotFound: pass return 200
def db_accounts(db_server, operation, id='', data={}): if operation.lower() == 'create': # Check unique user_name db = db_server['accounts'] user_name = data['user_name'] record_list = db.view('auth/auth', start_key=[user_name], end_key=[user_name + 'CHANGE']) if len(record_list) != 0: return 406, '' res = send_welcome_email(user_name) if res == 200: resp, gen_id = db_op.db_operate(db_server, 'accounts', operation, data=data) else: resp = res gen_id = '' return resp, gen_id elif operation.lower() == 'get': if id == '': return 404, [] resp, account_info = db_op.db_operate(db_server, 'accounts', operation, id=id) return resp, account_info elif operation.lower() == 'auth': db = db_server['accounts'] query_key = [data['user_name'], data['pwd']] record_list = db.view('auth/auth', start_key=query_key, end_key=query_key) if len(record_list) == 0: print('User_name of password wrong!') return 404, '' id_list = [] for row in record_list: id_list.append(row.value) return 200, id_list[0] # Change password. elif operation.lower() == 'update': db = db_server['accounts'] try: doc = db[data['_id']] resp = db_op.db_operate(db_server, 'accounts', operation, data=data) except ResourceNotFound: resp = 404 return resp elif operation.lower() == 'delete': if id == '': return 404 resp = db_op.db_operate(db_server, 'accounts', operation, id=id) return resp elif operation.lower() == 'exist': db = db_server['accounts'] user_name = data['user_name'] record_list = db.view('auth/auth', start_key=[user_name], end_key=[user_name + 'CHANGE']) if len(record_list) != 0: gen_id = '' for row in record_list: gen_id = row.value return 200, gen_id else: return 404, ''