def post(cls): """Create an activity.""" payload = request.get_json(silent=True) if payload: result, errors = activity_schema.load(payload) if errors: status_code = activity_schema.context.get('status_code') activity_schema.context = {} validation_status_code = status_code or 400 return response_builder(errors, validation_status_code) else: activity = Activity( name=result['name'], description=result['description'], activity_type_id=result['activity_type_id'], activity_date=result['activity_date'], added_by_id=g.current_user.uuid) activity.save() return response_builder( dict(message='Activity created' ' successfully.', data=result), 201) return response_builder( dict(message="Data for creation must be provided."), 400)
def generate_activities(): import json from faker import Faker import random fake = Faker() activities=[] activity_list = ['running', 'biking', 'walking', 'double dutch', 'cook a meal', 'have a snack', 'walk the dog', 'watch a movie', 'bake a cake', 'order pizza'] for x in range(100): # activity = {'fields':{'title':random.choice(activity_list), # 'timestamp':str(fake.date_time_this_year())[:10], # 'user': random.choice(User.objects.all()) # }, # 'model':'api.Activity',} # activities.append(activity) # print(activity) # with open('activities.json', 'w') as f: # f.write(json.dumps(activities)) activity = Activity(title=random.choice(activity_list), timestamp=str(fake.date_time_this_year())[:10], user= random.choice(User.objects.all())) activity.save() print(activity)
def generate_activities(): import json from faker import Faker import random fake = Faker() activities = [] activity_list = [ 'running', 'biking', 'walking', 'double dutch', 'cook a meal', 'have a snack', 'walk the dog', 'watch a movie', 'bake a cake', 'order pizza' ] for x in range(100): # activity = {'fields':{'title':random.choice(activity_list), # 'timestamp':str(fake.date_time_this_year())[:10], # 'user': random.choice(User.objects.all()) # }, # 'model':'api.Activity',} # activities.append(activity) # print(activity) # with open('activities.json', 'w') as f: # f.write(json.dumps(activities)) activity = Activity(title=random.choice(activity_list), timestamp=str(fake.date_time_this_year())[:10], user=random.choice(User.objects.all())) activity.save() print(activity)
def test_dev_activities_seed_data(args): (president, member, success_ops, hackathon, interview, open_saturdays, phoenix, sparks, invictus) = args # test activities python_hackathon = Activity(name="Hacktober Fest", activity_type=hackathon, activity_date=datetime.date.today() + datetime.timedelta(days=7), added_by=president) interview_2017 = Activity(name="2017-feb-bootcamp-17", activity_type=interview, activity_date=datetime.date.today() + datetime.timedelta(days=14), added_by=president) open_saturdays_2018 = Activity(name="2018-feb-meetup", activity_type=open_saturdays, activity_date=datetime.date.today() + datetime.timedelta(days=21), added_by=president) member.activities.extend( [python_hackathon, interview_2017, open_saturdays_2018]) # Logged Activities hackathon_points = LoggedActivity( value=hackathon.value, activity=python_hackathon, user=member, society=phoenix, activity_type=hackathon, status='approved', approver_id=success_ops.uuid, reviewer_id=president.uuid, activity_date=python_hackathon.activity_date) phoenix._total_points = hackathon_points.value interview_points = LoggedActivity( value=interview.value * 5, activity=interview_2017, user=member, society=sparks, activity_type=interview, status='rejected', approver_id=success_ops.uuid, reviewer_id=president.uuid, activity_date=interview_2017.activity_date) open_saturday_points = LoggedActivity( value=open_saturdays.value, activity=open_saturdays_2018, user=member, society=invictus, activity_type=open_saturdays, activity_date=open_saturdays_2018.activity_date) return (hackathon_points, interview_points, open_saturday_points)
def watch(self, request, pk=None): user = self.get_object() if user is None: return error('user not exists') profile = request.user.profile profile.watchedUser.add(user) profile.watchCount += 1 profile.save() user.profile.beWatchCount += 1 user.profile.save() if request.user.is_authenticated: Activity.watchUser(request.user.profile, user.profile) return success()
def watch(self, request, pk=None): if request.user.is_authenticated is False: return error('please login') question = self.get_object() if question is None: return error('question not exists') profile = request.user.profile Activity.watchQuestion(request.user.profile, question) profile.watchedQuestion.add(question) profile.save() return success()
def agree(self, request, pk=None): profile = request.user.profile answer = self.get_object() if answer is None: return error('没有找到你想赞的回答') if profile.agreed.filter(id=answer.id).exists(): return error('你已经赞过了') answer.approve += 1 answer.save() profile.agreed.add(answer) profile.save() if request.user.is_authenticated: Activity.agreeAnswer(request.user.profile, answer) return success()
def handle(self, *args, **options): filename = "inputs.csv" Activity.objects.all().delete() Category.objects.all().delete() Link.objects.all().delete() with open("inputs.csv", newline="") as csvfile: csvreader = csv.DictReader(csvfile) for row in csvreader: if row["is_published"].lower() == "false": continue print(row["name"]) activity = Activity( name=row["name"], description=row["description"], date_created=datetime.datetime.strptime( row["date_created"], "%m/%d/%Y").date(), min_cost=row["min_cost"], max_cost=row["max_cost"], min_participants=row["min_participants"], max_participants=row["max_participants"], requirements=row["requirements"], ) activity.save() links = [link for link in row["links"].split("\n")] for link in links: if len(link): name, url = link.split(",") link = Link(name=name.strip(), url=url.strip(), activity=activity) link.save() categories_names = [ category.strip().lower() for category in row["categories"].split(",") if len(category) ] for category_name in categories_names: try: category = Category.objects.get(name=category_name) except Category.DoesNotExist: category = Category.objects.create(name=category_name) category.save() activity.categories.add(category)
def get(self): # 给用户增加一个活动记录,接口 user = self.user f = Activity.find_by_uid(user.uid) if f is None: # 调用接口成功在添加 req = req_user_join_activity(user.uid) if req is None: return True d = dict(uid=user.uid, activity_id=2443) result = Activity.add(**d) return True return False # tets
def show_activity(): current_user_id = get_jwt_identity() user = User.get(current_user_id) activities = Activity.get_by_user(current_user_id) activities_serialized = [] for activity in activities: activities_serialized.append(activity.serialize()) return jsonify(activities_serialized), 200
def post_activity(): request_json = request.get_json() current_user_id = get_jwt_identity() current_user = User.get(current_user_id) new_activity = Activity.create(current_user_id, request_json["name"], request_json["route"], request_json["dificulty"], request_json["description"]) return jsonify(current_user.serialize()), 201
def create_activity(): body = request.get_json() new_activity = Activity(exercise=body["exercise"], distance=body["distance"], date=body["date"], lapse=body["lapse"], user_id=body["user_id"], deleteNumber=body["deleteNumber"]) db.session.add(new_activity) db.session.commit() return jsonify(body), 200
def setUp(self): """Setup function to configure test enviroment.""" self.app = create_app("Testing") self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() # test client self.client = self.app.test_client() self.header = {"Authorization": self.generate_token(self.test_payload)} # mock user self.member = User(email="someonecool.andela.com", name="thecoolest", uuid="-Ksomeid", role="member", country="ke/ug/niger/ny/sa/tz/rw") self.admin = User(email="coolAdmin.andela.com", name="thecoolestAdmin", uuid="-KsomeidAdmin", role="admin", country="ke/ug/niger/ny/sa/tz/rw") # mock societies self.istelle = Society(name="istelle", photo="url/imgae", logo="url/image", color_scheme="#00ff4567") self.sparks = Society(name="sparks", photo="url/imgae", logo="url/image", color_scheme="#00ff4567") self.phenix = Society(name="phenix", photo="url/imgae", logo="url/image", color_scheme="#00ff4567") self.phenix.save() # mock points self.point = Point(value=2500, name="interview-2017-sep-23rd") # mock interview self.activity = Activity( name="Interview", value=50, description="members earn 50 points per activity", photo="cool/icon/url")
def get_or_init_activity(data): try: # Find the existing activity entry activity = Activity.objects.get( guild_id=Guild(guild_id=data["guild_id"]), user_id=User(user_id=data.get("user_id", data.get("giver_id"))), period=date.today()) except ObjectDoesNotExist: # Entry not found - create one! activity = Activity( guild_id=Guild(guild_id=data["guild_id"]), user_id=User(user_id=data.get("user_id", data.get("giver_id"))), period=date.today()) return activity
def setUp(self): """Configure test enviroment.""" os.environ['APP_SETTINGS'] = 'Testing' self.patcher = mock.patch( 'api.services.auth.helpers.add_extra_user_info', return_value=(None, None, None)) self.patcher.start() self.app = create_app("Testing") self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() # test client self.client = self.app.test_client() token_payloads_list = [ self.incomplete_payload, self.expired_payload, self.test_cio_role_payload, self.test_society_president_role_payload, self.test_auth_role_payload, self.test_finance_payload, self.test_successops_payload ] for token_payload in token_payloads_list: token_payload.update({ 'iss': self.app.config['API_ISSUER'], 'aud': self.app.config['API_AUDIENCE'] }) self.header = { "Authorization": self.generate_token(self.test_user_payload), "Content-Type": "application/json" } self.success_ops = { "Authorization": self.generate_token(self.test_successops_payload), "Content-Type": "application/json" } self.society_president = { "Authorization": self.generate_token(self.test_society_president_role_payload), "Content-Type": "application/json" } self.sparks_society_president = { "Authorization": self.generate_token(self.test_sparks_society_president_payload), "Content-Type": "application/json" } self.society_secretary = { "Authorization": self.generate_token(self.test_society_secretary_payload), "Content-Type": "application/json" } self.cio = { "Authorization": self.generate_token(self.test_cio_role_payload), "Content-Type": "application/json" } self.finance = { "Authorization": self.generate_token(self.test_finance_payload), "Content-Type": "application/json" } self.bad_token_header = { "Authorization": self.generate_token({"I don't know": "what to put here"}), "Content-Type": "application/json" } # test centers self.nairobi = Center(name='Nairobi') self.kampala = Center(name='Kampala') self.lagos = Center(name='Lagos') # test societies self.phoenix = Society(name="Phoenix", color_scheme="#00001", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.istelle = Society(name="iStelle", color_scheme="#00002", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.sparks = Society(name="Sparks", color_scheme="#00003", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.invictus = Society(name="Invictus", color_scheme="#00004", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") # test roles self.successops_role = Role(uuid="-KkLwgbeJUO0dQKsEk1i", name="success ops") self.fellow_role = Role(uuid="-KXGy1EB1oimjQgFim6C", name="Fellow") self.success_role = Role(uuid="-KXGy1EB1oimjQgFim6F", name="success ops") self.finance_role = Role(uuid="-KXGy1EB1oimjQgFim6L", name="finance") self.lf_role = Role(uuid="d47ec8a7-3f09-44a5-8188-ff1d40ef35b6", name="Learning Facilitator") self.president_role = Role(uuid="-KXGyd2udi2", name="society president") self.v_president_role = Role(uuid="-KXGy32odnd", name="vice president") self.secretary_role = Role(uuid="-KXGy12odfn2idn", name="society secretary") self.cio_role = Role(uuid="-KXGionceu24i2y", name="cio") # test cohorts self.cohort_12_Ke = Cohort(name="cohort-12", center=self.nairobi) self.cohort_14_Ke = Cohort(name="cohort-14", center=self.nairobi) self.cohort_12_Ug = Cohort(name="cohort-12", center=self.kampala) self.cohort_1_Nig = Cohort(name="cohort-1", center=self.lagos) # test users self.test_user = User(uuid="-KdQsMt2U0ixIy_-yWTSZ", name="Test User", photo="https://www.link.com", email="*****@*****.**", center=self.lagos, cohort=self.cohort_1_Nig, society=self.phoenix) self.test_user_2 = User(uuid="-KdQsawesome_usedk2cckjfbi", name="Test User2", photo="https://www.link.com", email="*****@*****.**", center=self.kampala, cohort=self.cohort_12_Ug, society=self.sparks) self.test_user_3 = User(uuid="-KdQsawesomb2dunkdnw", name="Test User3", photo="https://www.link.com", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_12_Ke, society=self.invictus) self.test_cio = User( uuid="-KdQdsdadqwdqomb2dunkdnw", name="Test CIO", photo="https://www.link.com", email="*****@*****.**", center=self.nairobi, ) self.test_cio.roles.append(self.cio_role) self.president = User( uuid="-KdQsMtixG4U0y_-yJEH", name="Test President", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.lagos, cohort=self.cohort_1_Nig, society=self.phoenix) self.president.roles.append(self.president_role) self.vice_president = User( uuid="-KdQsMtixGc2nuekwnd", name="Test Vice-President", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_12_Ke, society=self.sparks) self.vice_president.roles.append(self.v_president_role) self.secretary = User( uuid="-Kuty7hryt8cbkc", name="Test Secretary", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_14_Ke, society=self.invictus) self.secretary.roles.append(self.secretary_role) # test ActivityType self.hackathon = ActivityType(name="Hackathon", description="A Hackathon", value=100) self.tech_event = ActivityType(name="Tech Event", description="Organize a tech event", value=2500) self.interview = ActivityType( name="Bootcamp Interviews", description="Interviewing candidate for a fellow" " recruiting event", value=20, supports_multiple_participants=True) # test Activity self.alibaba_ai_challenge = Activity( name='Fashion challenge', activity_type=self.hackathon, activity_date=datetime.date.today() + datetime.timedelta(days=21), added_by=self.president) self.js_meet_up = Activity(name='Nairobi Js meetup', activity_type=self.tech_event, activity_date=datetime.date.today() + datetime.timedelta(days=14), added_by=self.president) self.bootcamp_xiv = Activity(name='Bootcamp XIV Interviews - Nairobi', activity_type=self.interview, activity_date=datetime.date.today() + datetime.timedelta(days=14), added_by=self.president) # test LoggedActivity self.log_alibaba_challenge = LoggedActivity( name="my logged activity", description="Participated in this event", value=2500, user=self.test_user, activity=self.alibaba_ai_challenge, society=self.invictus, activity_type=self.hackathon) self.log_alibaba_challenge2 = LoggedActivity( name="my second logged activity", description="Participated in this event", value=2500, user=self.test_user, activity=self.alibaba_ai_challenge, society=self.sparks, activity_type=self.hackathon) self.redemp_req = RedemptionRequest(name="T-shirt Funds Request", value=2500, user=self.test_user, center=self.test_user.center, society=self.test_user.society) # save common items to db self.tech_event.save() self.interview.save() self.hackathon.save() self.test_user.save()
def test_fields_exist_as_expected(self): a = Activity(user=UserFactory.create()) a.save() assert a.modified is not None assert a.created is not None
def find_family_by_id(cls, _id, _uid): from api.models import User from api.models import Activity from api.models import Achievement # 先查询出这个家庭信息,在查询出加入这个家庭的其他用户信息 family = cls.query.filter(cls.id == _id).first() if not family: return None other_members = User.find_by_family_id(family.id) uid_l = list() member_l = list() for member in other_members: uid = member.uid if isinstance(uid, str): if uid.isdigit(): uid = int(uid) elif isinstance(uid, int): uid = uid uid_l.append(uid) # 拿到成员id,查询名字 nick, url = req_get_uid_info(uid) if str(family.uid) == str(uid): nick = family.member_name d = dict(nick=nick, head_url=url) member_l.append(d) # 孩子dict _d = dict(nick=family.get_child_name(), head_url=Family.get_child_head()) member_l.append(_d) # 查询这个家庭累计里程,同时排名, yp_run 表user_run_0-user_run_127 按用户uid%128 # 1560405600 2019-06-13 14:00:00 开始时间取用户参加本活动的时间 # 1561305600 2019-06-23 24:00:00 activity = Activity.find_by_uid(_uid) if activity is None: start_time = 1560391200 else: start_time = activity.created_at meter_total = 0 testdb.ping() cursor = testdb.cursor() for uid in uid_l: table_name = 'user_run_{}'.format(uid % 128) sql = '''select sum(meter) / 1000 from {} where uid = {} and status in (1, 4) and start_time > {} and end_time < 1561305600 '''.format( table_name, uid, start_time) # print(sql) cursor.execute(sql) meter = cursor.fetchone() meter = int(meter[0]) if meter[0] else 0 meter_total += meter cursor.close() # 比较一下这个家庭薪的总里程是否和之前相等 if family.run_total != meter_total and meter_total > 0: family.update(run_total=meter_total) if family.run_total >= 1: # TODO 调用java接口给这个用户增加成就 f = req_user_gain_achievement(_uid) if f: family.update(task_stage=1) # 接口调用成功 Achievement.verify_add(uid=_uid) current_run_total = family.run_total if family.run_total else 0 sql = 'select count(*) from family where run_total > {}'.format( current_run_total) rank = db.session.execute(sql).fetchone() rank = rank[0] if rank[0] else 1 # 累计爱心值 系数13 if rank > 120: rank = rank * 13 sql = 'select sum(run_total) from family' love_total = db.session.execute(sql).fetchone() love_total = int(love_total[0]) if love_total[0] else 0 # love_total 爱心值 这里要*一个系数,暂定为13 love_total = int(love_total * 27.1) - 639000 # print(love_total) d = dict(family_name=family.family_name, member=member_l, family_meter=meter_total, rank=rank, love_total=love_total, invitation_code=family.invitation_code, member_name=family.member_name, child_name=family.get_child_name()) # print(d) return d