def handle(self, *args, **options): Magazine.objects.all().delete() User.objects.all().delete() Subscribe.objects.all().delete() Task.objects.all().delete() Order.objects.all().delete() titles = [ "Reader's Digest USA", 'Harvard Business Review', 'Scientific American', 'Bloomberg Businessweek', 'WSJ', 'Time', 'TE', 'FT', 'TWP', 'The New Yorker' ] for title in titles: if len(Magazine.objects.filter(title=title)) > 0: continue magazine = Magazine(title=title) magazine.save() if len(User.objects.filter(uuid='uuid')) == 0: user = User(email='xxx', uuid='uuid', key='key', invitor='invitor', expire_date=localdate()) user.save()
def test_ogin_auth(self): self.assertEqual(User().login("wanyifu11", "hello"), ERR_BAD_CREDENTIALS) self.assertEqual(User().login("wanyifu11", "felix14"), ERR_BAD_CREDENTIALS) self.assertEqual(User().login("wanyifu15", "felix13"), ERR_BAD_CREDENTIALS)
def updateLocation(user_name, longitude, latitude): try: user = User.objects.get(user_name=user_name) except User.DoesNotExist: user = User(user_name=user_name) user.longitude = longitude user.latitude = latitude user.save() return
def test_build_account(self): a = User().add("wanyifu11", "felix11") b = User().add("wanyifu12", "felix12") c = User().add("wanyifu13", "felix13") d = User().add("wanyifu14", "felix14") self.assertEqual(SUCCESS, a) self.assertEqual(SUCCESS, b) self.assertEqual(SUCCESS, c) self.assertEqual(SUCCESS, d)
def register(request): #회원가입 if request.method == "GET": return render(request, 'uuser/register.html') elif request.method == "POST": username = request.POST.get('username', None) password = request.POST.get('password', None) user = User(username=username, password=make_password(password)) user.save() return redirect('/')
def authenticate(self, request): token = request.META.get('HTTP_TOKEN') try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) user = User() user.no = payload['userid'] user.is_authenticated = True return user, token except InvalidTokenError: raise AuthenticationFailed('请提供有效的身份令牌')
def add(request): if request.method == 'POST': Requestheader = json.loads(request.body) username = Requestheader["user"] password = Requestheader["password"] count_or_code = User.add(username, password) if count_or_code > 0: return HttpResponse(json.dumps({ "errCode": SUCCESS, "count": count_or_code }), content_type="application/json") else: if count_or_code == ERR_USER_EXISTS: return HttpResponse(json.dumps({ "errCode": ERR_USER_EXISTS, "count": count_or_code }), content_type="application/json") if count_or_code == ERR_BAD_USERNAME: return HttpResponse(json.dumps({ "errCode": ERR_BAD_USERNAME, "count": count_or_code }), content_type="application/json") else: return HttpResponse(json.dumps({ "errCode": ERR_BAD_PASSWORD, "count": count_or_code }), content_type="application/json")
def logout(self, user_id: str): user = User.objects(id=user_id).first() if user: user.isAuth = False user.token = '' user.save() return True else: raise UnknownUserError(str(user_id))
def get_industry(self, user_id: str): start = time.time() user = User.objects(id=user_id).first() country = Country.objects(id=user.country.id).first() industry_dict = {} farms_list = [] mines_list = [] factories_list = [] game_service = GameService() farms_modifiers = game_service.get_industry_modifiers(country, 'farms') mines_modifiers = game_service.get_industry_modifiers(country, 'mines') factories_modifiers = game_service.get_industry_modifiers( country, 'factories') for farm in country.farms: industrial_card_view = IndustrialCardView( farm.name, farm.link_img, round(farm.production_speed, 2), round( farm.active_number * farm.production_speed * farms_modifiers, 2), farm.price_build, farm.workers, farm.number, farm.active_number, farm.number * farm.workers, []) farms_list.append(industrial_card_view) industry_dict['farms'] = farms_list for mine in country.mines: industrial_card_view = IndustrialCardView( mine.name, mine.link_img, round(mine.production_speed, 2), round( mine.active_number * mine.production_speed * mines_modifiers, 2), mine.price_build, mine.workers, mine.number, mine.active_number, mine.number * mine.workers, []) mines_list.append(industrial_card_view) industry_dict['mines'] = mines_list for factory in country.factories + country.military_factories: industrial_card_view = IndustrialCardView( factory.name, factory.link_img, round(factory.production_speed, 2), round(factory.active_number * factory.production_speed * factories_modifiers), factory.price_build, factory.workers, factory.number, factory.active_number, factory.number * factory.workers, [ TableRowGoodsView(item.link_img, item.name, item.value) for item in factory.need_goods ]) factories_list.append(industrial_card_view) industry_dict['factories'] = factories_list[:18] industry_dict['military_factories'] = factories_list[18:] finish = time.time() return industry_dict
def test_login_count(self): a = User().add("wanyifu1", "felix1") b = User().add("wanyifu2", "felix2") c = User().add("wanyifu3", "felix3") d = User().add("wanyifu4", "felix4") e = User().login("wanyifu1", "felix1") f = User().login("wanyifu1", "felix1") g = User().login("wanyifu2", "felix2") h = User().login("wanyifu3", "felix3") i = User().login("wanyifu4", "felix4") self.assertEqual(e, 2) self.assertEqual(f, 3) self.assertEqual(g, 2) self.assertEqual(h, 2) self.assertEqual(i, 2)
def login(request): if request.method == 'POST': Requestheader = json.loads(request.body) username = Requestheader["user"] password = Requestheader["password"] count_or_code = User.login(username, password) if count_or_code > 0: return HttpResponse(json.dumps({"errCode" : SUCCESS, "count" : count_or_code}), content_type = "application/json") else: return HttpResponse(json.dumps({"errCode" : ERR_BAD_CREDENTIALS, "count" : count_or_code}), content_type = "application/json")
def get_cache_politics_laws(self, user_id: str): user = User.objects(id=user_id).first() country = Country.objects(id=user.country.id).first() cache = Cache.objects().first() if cache.politics != '': politics_view = json.loads(cache.politics) politics_view['selected_laws'] = country.adopted_laws return politics_view else: return self.get_politics_laws(user_id)
def register(request: HttpRequest) -> HttpResponse: agreement = request.data.get('agreement') if agreement: username = request.data.get('username') password = request.data.get('password') tel = request.data.get('tel') if username and password and tel: try: password = gen_md5_digest(password) user = User(username=username, password=password, tel=tel) user.save() return Response({'code': 30000, 'mesg': '注册成功'}) except DatabaseError: hint = '注册失败,请尝试更换用户名' else: hint = '请输入有效的注册信息' else: hint = '请勾选同意网站用户协议及隐私政策' return Response({'code': 30001, 'mesg': hint})
def delete_user_account(self, user_id: str, password: str): if User.objects(id=user_id).count() == 1 and User.objects( id=user_id).first().password == sha256( password.encode()).hexdigest(): try: user = User.objects(id=user_id).first() user_email = user.email country_pk = user.country.id country = Country.objects(id=country_pk).first() country.delete() user.delete() if GlobalSettings.objects().first().email_notification: SystemService().send_notification([user_email], EmailEvent.DELETE, user.username) return True except Exception as e: print(e) return False return False
def get_view_page(self, user_id: str): user = User.objects(id=user_id).first() country = Country.objects(id=user.country.id).first() economic_place = GameService().get_economic_place(country.name) army_place = GameService().get_army_place(country.name) cache = Cache.objects().first() if cache.top_players != '': top_players = json.loads(cache.top_players) else: global_settings = GlobalSettings.objects().first() top_players = self.get_top_players( global_settings.number_top_players) return TopPlayersPage(economic_place, army_place, top_players)
def get_account(self, user_id: str): user = User.objects(id=user_id).first() country = Country.objects(id=user.country.id).first() game_service = GameService() days_in_game = (datetime.utcnow() - user.date_registration).days date_reg = user.date_registration.strftime('%d.%m.%Y') account_view = AccountView( user_id, country.link_img, country.name, game_service.get_total_profit(country), game_service.get_economic_place(country.name), game_service.get_army_place(country.name), user.username, user.email, date_reg, days_in_game) return account_view
def get_trade(self, user_id: str): start = time.time() user = User.objects(id=user_id).first() goods = Trade.objects target_country = Country.objects(id=user.country.id).first() countries = Country.objects trade_cards_view_list = [] production_data = GameService().get_table_world_place_production() for item in goods: data_top_producer = [] if len(production_data[item.name]) > 2: data_top_producer_buffer = production_data[item.name][:3] else: data_top_producer_buffer = production_data[item.name] for producer in data_top_producer_buffer: producer_view = TableRowProducerView( countries.filter(name=producer[0]).first().link_img, producer[0], producer[1]) data_top_producer.append(producer_view) data_top_producer.sort(key=lambda x: x.number, reverse=True) warehouse = next( filter(lambda x: x.goods.name == item.name, target_country.warehouses), None) price_list = [ round(history.value, 2) for history in item.history_price ] if not price_list: price_list = [round(item.price_now, 2)] chart_price_goods = ChartPriceGoods(price_list, [ history.time.strftime("%H:%M:%S") for history in item.history_price ], item.name, max(price_list) * 1.2, min(price_list) * 0.9) trade_card_view = TradeCardView(item.name, warehouse.goods.link_img, round(item.price_now), round(warehouse.goods.value, 2), warehouse.capacity, data_top_producer, chart_price_goods) trade_cards_view_list.append(trade_card_view) finish = time.time() return trade_cards_view_list
def register(request): """用户注册""" username, tel, hint = '', '', '' if request.method == 'POST': agreement = request.data.get('agreement') if agreement: username = request.data.get('username', '').strip() password = request.data.get('password', '') tel = request.data.get('tel', '').strip() redis_cli = get_redis_connection() code_from_user = request.data.get('mobilecode', '0') code_from_redis = redis_cli.get(f'mobile:valid:{tel}').decode() if code_from_user == code_from_redis: if check_username(username) and check_password( password) and check_tel(tel): password = gen_sha256_digest(password) try: user = User(username=username, password=password, tel=tel) user.last_visit = timezone.now() user.save() # 验证码只能消费一次,注册成功用过的验证码立即失效 redis_cli.delete(f'mobile:valid:{tel}') hint = '注册成功,请登录' # return redirect(f'/login/?hint={hint}') return Response({'code': 30000, 'mesg': hint}) except DatabaseError: hint = '注册失败,用户名或手机号已被使用' else: hint = '请输入有效的注册信息' else: hint = '请输入正确的手机验证码' else: hint = '请勾选同意网站用户协议及隐私政策' # return render(request, 'register.html', {'hint': hint, 'username': username, 'tel': tel}) return Response({'code': 30001, 'mesg': hint})
def add(request): if request.method == 'POST': Requestheader = json.loads(request.body) username = Requestheader["user"] password = Requestheader["password"] count_or_code = User.add(username, password) if count_or_code > 0: return HttpResponse(json.dumps({"errCode" : SUCCESS, "count" : count_or_code}), content_type = "application/json") else: if count_or_code == ERR_USER_EXISTS: return HttpResponse(json.dumps({"errCode" : ERR_USER_EXISTS, "count" : count_or_code}), content_type = "application/json") if count_or_code == ERR_BAD_USERNAME: return HttpResponse(json.dumps({"errCode" : ERR_BAD_USERNAME, "count" : count_or_code}), content_type = "application/json") else: return HttpResponse(json.dumps({"errCode" : ERR_BAD_PASSWORD, "count" : count_or_code }), content_type = "application/json")
def register_new_user(self, username: str, password: str, email: str, country_name: str, link_country_flag: str): country = SystemService().create_default_country( country_name, link_country_flag) try: country.save() except Exception as error: print(error) return False user = User(username=username, password=sha256(password.encode()).hexdigest(), email=email, country=country.pk) try: user.save() except Exception as error: print(error) country.delete() return False if GlobalSettings.objects().first().email_notification: SystemService().send_notification([email], EmailEvent.REGISTRATION, username, country_name, str(user.pk), link_country_flag) return True
def get_cache_trade(self, user_id: str): cache = Cache.objects().first() if cache.trade != '': trade_view = json.loads(cache.trade) user = User.objects(id=user_id).first() target_country = Country.objects(id=user.country.id).first() for trade_card in trade_view: warehouse = next( filter(lambda x: x.goods.name == trade_card['name'], target_country.warehouses), None) trade_card['warehouse_has'] = round(warehouse.goods.value, 2) trade_card['warehouse_capacity'] = warehouse.capacity return trade_view else: return self.get_trade(user_id)
def get_warehouses(self, user_id: str): start = time.time() user = User.objects(id=user_id).first() country = Country.objects(id=user.country.id).first() warehouses_list = [] for warehouse in country.warehouses: warehouse_card_view = WarehouseCardView( warehouse.goods.name, warehouse.goods.link_img, round(warehouse.goods.value, 2), warehouse.capacity, round(warehouse.filling_speed, 2), warehouse.level, warehouse.max_level, warehouse.price_upgrade, warehouse.added_capacity, warehouse.increase_price) warehouses_list.append(warehouse_card_view) finish = time.time() return warehouses_list
def run_check_warehouses(): print('run_check_warehouses') global_settings = GlobalSettings.objects().first() if global_settings.email_notification: while True: try: users = User.objects() for user in users: if user.settings['warehouse overflow or empty']: country = Country.objects(id=user.country).first() for warehouse in country.warehouses: if warehouse.filling_speed != 0 and (datetime.utcnow() - country.date_last_warehouse_notification).total_seconds()/60 >= global_settings.frequency_email_notification and (warehouse.goods.value <= 0 or warehouse.goods.value >= warehouse.capacity): SystemService().send_notification([user.email],EmailEvent.WAREHOUSE) break time.sleep(global_settings.frequency_check_warehouses * 60) except Exception as e: print(e)
def login(request): if request.method == 'POST': Requestheader = json.loads(request.body) username = Requestheader["user"] password = Requestheader["password"] count_or_code = User.login(username, password) if count_or_code > 0: return HttpResponse(json.dumps({ "errCode": SUCCESS, "count": count_or_code }), content_type="application/json") else: return HttpResponse(json.dumps({ "errCode": ERR_BAD_CREDENTIALS, "count": count_or_code }), content_type="application/json")
def get_technologies(self, user_id: str): start = time.time() user = User.objects(id=user_id).first() country = Country.objects(id=user.country.id).first() technologies_view_list = [] for technology in country.technologies: technology_view = TechnologyView( technology.name, technology.price_upgrade, technology.level, technology.max_level, technology.level * technology.modifiers[0].value, [ ModifierView(mod.value, mod.address_to) for mod in technology.modifiers ]) technologies_view_list.append(technology_view) finish = time.time() return technologies_view_list
def change_user_data(self, user_id: str, new_country_name: str = None, new_country_flag: str = None): user = User.objects(id=user_id).first() if user is not None: country = Country.objects(id=user.country.id).first() country.name = new_country_name if new_country_name is not None and Country.objects( name=new_country_name).count() == 0 else country.name country.link_img = new_country_flag if new_country_flag is not None else country.link_img country.save() user.country = country.to_dbref() user.save() if GlobalSettings.objects().first().email_notification: SystemService().send_notification([user.email], EmailEvent.CHANGE_DATA, user.username, country.name, country.link_img) return True return False
def login(self, username: str, password: str): user = User.objects(username=username, password=sha256( password.encode()).hexdigest()).first() if user: token = tokenlib.make_token( { "user_id": str(user.id), 'username': username, 'password': password, 'random_value': random.randint(0, 1000000) }, secret=SECRET_KEY) user.isAuth = True user.token = token user.date_last_login = timezone.now() user.save() return token else: raise UnknownUserError(username)
def get_politics_laws(self, user_id: str): user = User.objects(id=user_id).first() country = Country.objects(id=user.country.id).first() conscription_laws = [] pop_laws = [] for law in Law.objects(): if 'Conscript law:' in law.name: conscription_percent = re.split(' ', law.description)[-1] conscription_laws.append( LawView(law.name, law.description, [ ModifierView(mod.value, mod.address_to) for mod in law.modifiers ], conscription_percent)) else: pop_laws.append( LawView(law.name, f' ({law.description})', [ ModifierView(mod.value, mod.address_to) for mod in law.modifiers ])) return PoliticsView(country.adopted_laws, conscription_laws, pop_laws)
def signup(request): username = request.POST.get('username') psw = request.POST.get('psw') first_name = request.POST.get('firstname') last_name = request.POST.get('lastname') if any(elem is None or len(elem) > 32 for elem in [username, psw, first_name, last_name]): return HttpResponseRedirect(reverse('polls:register')) if len(User.objects.filter(username=username)) > 0: return HttpResponseRedirect(reverse('polls:failure', args=(2, ))) salt = os.urandom(32) key = hashlib.pbkdf2_hmac('sha256', psw.encode('utf-8'), salt, 100000) hashed = binascii.hexlify(salt) + binascii.hexlify(key) User(username=username, psw=hashed.decode('utf-8'), first_name=first_name, last_name=last_name).save() request.session['username'] = username return HttpResponseRedirect(reverse('polls:home'))
def get_player(self, username: str): start = time.time() user = User.objects(username=username).first() if user is not None: country = Country.objects(id=user.country.id).first() player_view = PlayerView( country.link_img, country.name, user.username, GameService().get_economic_place(country.name), GameService().get_army_place(country.name), country.budget.money, country.population.total_population, sum([farm.number for farm in country.farms]), sum([mine.number for mine in country.mines]), sum([ sum([factory.number for factory in country.factories]), sum([ factory.number for factory in country.military_factories ]) ]), country.population.solders, country.army.units) finish = time.time() return player_view
def regUser(request): rsp = RegRsp(200, -1) if smartstring.equals_ingorecase(request.method, "POST"): regmsg = RegMsg() regmsg.parse(request.body) if not hasUser(regmsg.account): u = User() u.account = regmsg.account u.password = regmsg.password u.token = hashlib.sha1(os.urandom(24)).hexdigest() u.save() rsp.Code = 0 rsp.Userid = u.id return HttpResponse(rsp.toJson()) else: rsp.Code = 100 rsp.Userid = -1 return HttpResponse(rsp.toJson()) else: return HttpResponse(rsp.toJson())
def get_population(self, user_id: str): start = time.time() user = User.objects(id=user_id).first() country = Country.objects(id=user.country.id).first() modifiers_view_list = [] population_modifiers = 0 # -> 1(100%) for mod in country.population.modifiers: modifiers_view_list.append( ModifierView(round(mod.value, 2), mod.address_from)) population_modifiers += mod.value modifiers_view_list.append( ModifierView(country.population.basic_percent_growth_rate, 'basic percent')) percent_total_progress = round( (population_modifiers + country.population.basic_percent_growth_rate), 2) pie_chart_labels = [ 'Farmers', 'Miners', 'Workers', 'Solders', 'Free', 'Others' ] pie_chart_data = [ country.population.farmers, country.population.miners, country.population.factory_workers, country.population.solders, country.population.free_people, country.population.total_population * (country.population.min_percent_others / 100) ] population_view = PopulationView( country.population.total_population, country.population.farmers, country.population.miners, country.population.factory_workers, country.population.solders, country.population.free_people, country.population.others, percent_total_progress, modifiers_view_list, pie_chart_data, pie_chart_labels) finish = time.time() return population_view
def run_check_news(): print('run_check_news') global_settings = GlobalSettings.objects().first() number_of_news = len(News.objects()) if global_settings.email_notification: while True: try: news_len_lst = len(News.objects()) if news_len_lst < number_of_news: number_of_news = news_len_lst if news_len_lst > number_of_news: number_of_news = news_len_lst users = User.objects() to_emails_lst = [] for user in users: if user.settings['news']: to_emails_lst.append(user.email) SystemService().send_notification(to_emails_lst, EmailEvent.NEWS) time.sleep(global_settings.frequency_check_news * 60) except Exception as e: print(e)
def update(request, timestamp): print "Hello" json_data = request.read() data = simplejson.loads(json_data) current_date = datetime.datetime.now() current_timestamp = long(time.mktime(current_date.timetuple())) print data["timestamp"] ###Handle Add Operation # Condition: add if only if KTP is not exist for a in data["add"]["user"]: try: temp = User.objects.get(ktp=a["local_ktp"]) except User.DoesNotExist: u = User( ktp=a["local_ktp"], username=a["username"], password=a["password"], name=a["name"], address=a["address"], email=a["email"], phone=a["phone"], description=a["description"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) u.save() print "saving user", u.ktp # Condition: add if only if KTP is not exist for a in data["add"]["patient"]: try: temp = Patient.objects.get(ktp=a["local_ktp"]) except Patient.DoesNotExist: p = Patient( ktp=a["local_ktp"], name=a["name"], address=a["address"], phone=a["phone"], birthdate=a["birthdate"], filename=a["filename"], description=a["description"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) p.save() print "saving patient", p.ktp # Condition: add if only if Patient's KTP+Pregnancy Number is not exist for a in data["add"]["pregnancy"]: try: temp = Pregnancy.objects.get( patient__ktp=a["local_patient_id"], pregnancy_number=a["local_pregnancy_number"] ) except Pregnancy.DoesNotExist: patient_temp = Patient.objects.get(ktp=a["local_patient_id"]) p = Pregnancy( patient=patient_temp, pregnancy_number=a["local_pregnancy_number"], is_finish=a["is_finish"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) p.save() print "saving pregnancy", p.patient.ktp, p.pregnancy_number # Condition: Add if only if no doctor with identical ktp or id for a in data["add"]["doctor"]: temp = Doctor.objects.filter(Q(user__ktp=a["local_ktp"]) | Q(doctor_id=a["doctor_id"])) if len(temp) < 1: u = User.objects.get(ktp=a["local_ktp"]) d = Doctor( user=u, doctor_id=a["doctor_id"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) d.save() print "saving doctor", d.user.ktp, d.doctor_id # Condition: Add if only if no identical clinic id exist for a in data["add"]["clinic"]: try: temp = Clinic.objects.get(clinic_id=a["local_clinic_id"]) except Clinic.DoesNotExist: c = Clinic( clinic_id=a["local_clinic_id"], name=a["name"], address=a["address"], city=a["city"], province=a["province"], phone=a["phone"], description=a["description"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) c.save() print "saving clinic", c.clinic_id # Condition: Add if only if no officer with identical ktp or id for a in data["add"]["officer"]: temp = Officer.objects.filter(Q(user__ktp=a["local_ktp"]) | Q(officer_id=a["officer_id"])) if len(temp) == 0: u = User.objects.get(ktp=a["local_ktp"]) o = Officer( user=u, officer_id=a["officer_id"], clinic_id=a["local_clinic_id"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) o.save() print "saving officer", o.user.ktp, o.officer_id photo_confirmation = [] # Condition: Add as long as KTP + Pregnancy exist. Global photo number may be differ for a in data["add"]["photo"]: try: temp = Pregnancy.objects.get(patient__ktp=a["local_ktp"], pregnancy_number=a["local_pregnancy_number"]) o = Officer.objects.get(user__ktp=a["local_officer_ktp"]) last_objects = Photo.objects.filter(pregnancy__pregnancy_id=temp.pregnancy_id).aggregate( Max("photo_number") ) last_number = last_objects["photo_number__max"] if last_number is None: last_number = 1 p = Photo( pregnancy=temp, officer=o, photo_number=last_number + 1, analyze_timestamp=a["analyze_timestamp"], filename=a["filename"], x=a["x"], y=a["y"], a=a["a"], b=a["b"], tetha=a["tetha"], scale=a["scale"], method=a["method"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) p.save() photo_confirmation.append( { "local_number": a["local_photo_number"], "ktp": a["local_ktp"], "pregnancy_number": a["local_pregnancy_number"], "global_number": p.photo_number, } ) print "saving photo", p.pregnancy.patient.ktp, p.pregnancy.pregnancy_number, p.photo_number except (Pregnancy.DoesNotExist, Officer.DoesNotExist): print "Pregnancy, photo, Officer not exist" # Condition: Add if only if clinic and patient exist, no existing serve, the server_id may vary for a in data["add"]["serve"]: try: temp = Serve.objects.get(clinic__clinic_id=a["local_clinic_id"], patient__ktp=a["local_ktp"]) except Serve.DoesNotExist: try: c = Clinic.objects.get(clinic_id=a["local_clinic_id"]) p = Patient.objects.get(ktp=a["local_ktp"]) s = Serve( clinic=c, patient=p, is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) s.save() print "saving serve", p.ktp, c.clinic_id except (Clinic.DoesNotExist, Patient.DoesNotExist) as e: print "Clinic, Patient not exist" # Condition: Add if only if clinic and doctor exist, no existing works0n print data["add"]["works_on"] for a in data["add"]["works_on"]: try: temp = Works_On.objects.get(clinic__clinic_id=a["local_clinic_id"], doctor__user__ktp=a["local_ktp"]) except Works_On.DoesNotExist: try: c = Clinic.objects.get(clinic_id=a["local_clinic_id"]) d = Doctor.objects.get(user__ktp=a["local_ktp"]) w = Works_On( clinic=c, doctor=d, is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) w.save() print "saving works_on", d.user.ktp, c.clinic_id except (Clinic.DoesNotExist, Doctor.DoesNotExist) as e: print "Clinic, Doctor not exist" # Condition: Add if only if photo and doctor exist, no existing Validation for a in data["add"]["validation"]: try: current_photo_number = a["photo_number"] if current_photo_number == -1: for ii in photo_confirmation: if ( ii["local_number"] == a["local_photo_number"] and ii["ktp"] == a["local_patient_ktp"] and ii["pregnancy_number"] == a["local_pregnancy_number"] ): current_photo_number = ii["global_number"] break if current_photo_number == -1: continue temp = Validation.objects.get( doctor__user__ktp=a["local_doctor_ktp"], photo__photo_number=current_photo_number, photo__pregnancy__pregnancy_number=a["local_pregnancy_number"], photo__pregnancy__patient__ktp=a["local_patient_ktp"], ) except Validation.DoesNotExist: try: if current_photo_number != -1: p = Photo.objects.get( photo_number=current_photo_number, pregnancy__pregnancy_number=a["local_pregnancy_number"], pregnancy__patient__ktp=a["local_patient_ktp"], ) d = Doctor.objects.get(user__ktp=a["local_doctor_ktp"]) v = Validation( doctor=d, photo=p, x=a["x"], y=a["y"], a=a["a"], b=a["b"], tetha=a["tetha"], has_seen=a["has_seen"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) v.save() print "saving validation", d.user.ktp, p.pregnancy.patient.ktp, p.pregnancy.pregnancy_number, p.photo_number except (Photo.DoesNotExist, Doctor.DoesNotExist) as e: print "Photo, Doctor not exist" comment_confirmation = [] # Condition: Add as long as KTP + Pregnancy exist. Global photo number may be differ for a in data["add"]["comment"]: try: d = Doctor.objects.get(user__ktp=a["local_doctor_ktp"]) o = Officer.objects.get(user__ktp=a["local_officer_ktp"]) p = Patient.objects.get(ktp=a["local_patient_ktp"]) last_objects = Comment.objects.filter(patient__ktp=p.ktp).aggregate(Max("comment_number")) last_number = last_objects["comment_number__max"] if last_number is None: last_number = 1 c = Comment( doctor=d, officer=o, patient=p, comment_number=last_number + 1, from_doctor=a["from_doctor"], content=a["content"], has_seen=a["has_seen"], is_active=a["is_active"], modify_timestamp=a["modify_timestamp"], create_timestamp=a["create_timestamp"], server_arrival_timestamp=current_timestamp, server_modify_timestamp=current_timestamp, ) c.save() comment_confirmation.append( { "local_number": a["local_comment_number"], "ktp": a["local_patient_ktp"], "global_number": c.comment_number, } ) print "saving comment", p.ktp, c.comment_number except (Doctor.DoesNotExist, Officer.DoesNotExist, Patient.DoesNotExist): print "Doctor, officer, patient not exist" # update user, exceptional: username, server_create_timestamp for a in data["update"]["user"]: try: temp = User.objects.get(ktp=a["ktp"]) temp.password = a["password"] temp.name = a["name"] temp.address = a["address"] temp.email = a["email"] temp.phone = a["phone"] temp.description = a["description"] temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "user updated", a["ktp"] except User.DoesNotExist: print "user not exist", a["ktp"] # update patient, exceptional: ktp, server_create_timestamp for a in data["update"]["patient"]: try: temp = Patient.objects.get(ktp=a["ktp"]) name = (a["name"],) temp.address = (a["address"],) temp.phone = (a["phone"],) temp.birthdate = (a["birthdate"],) temp.description = (a["description"],) temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "patient updated", a["ktp"] except Patient.DoesNotExist: print "patient not exist", a["ktp"] # Update pregnancy, except patient pregnancy_number server_create_timestamp for a in data["update"]["pregnancy"]: try: temp = Pregnancy.objects.get(patient__ktp=a["patient_id"], pregnancy_number=a["pregnancy_number"]) temp.is_finish = a["is_finish"] temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "pregnancy updated", a["patient_id"], a["pregnancy_number"] except Pregnancy.DoesNotExist: print "pregnancy not exist", a["patient_id"], a["pregnancy_number"] # Update doctor, except user_ktp doctor_id server_arrival_timestamp for a in data["update"]["doctor"]: try: temp = Doctor.objects.get(user__ktp=a["ktp"]) temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "doctor updated ", a["ktp"] except Doctor.DoesNotExist: print "doctor not exist", a["ktp"] # Update clinic, except clinic_id server_arrival_timestamp for a in data["update"]["clinic"]: try: temp = Clinic.objects.get(clinic_id=a["clinic_id"]) temp.name = a["name"] temp.address = a["address"] temp.city = a["city"] temp.province = a["province"] temp.phone = a["phone"] temp.description = a["description"] temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "clinic updated ", a["clinic_id"] except Clinic.DoesNotExist: print "clinic not exist", a["clinic_id"] # Update officer, except user_ktp officer_id clinic_id server_arrival_timestamp for a in data["update"]["officer"]: try: temp = Officer.objects.get(user__ktp=a["ktp"]) temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "officer updated ", a["ktp"] except Officer.DoesNotExist: print "officer not exist", a["ktp"] # Update Photo, except patient_ktp, pregnancy_number, photo_number, officer_ktp server_arrival_timestamp for a in data["update"]["photo"]: try: temp = Photo.objects.get( pregnancy__patient__ktp=a["ktp"], pregnancy__pregnancy_number=a["pregnancy_number"], photo_number=a["photo_number"], ) temp.analyze_timestamp = a["analyze_timestamp"] temp.filename = a["filename"] temp.x = a["x"] temp.y = a["y"] temp.a = a["a"] temp.b = a["b"] temp.tetha = a["tetha"] temp.scale = a["scale"] temp.method = a["method"] temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "Photo updated ", a["ktp"], a["pregnancy_number"], a["photo_number"] except Photo.DoesNotExist: print "Photo not exist ", a["ktp"], a["pregnancy_number"], a["photo_number"] # Update Serve, except clinic_id patient_ktp server_arrival_timestamp for a in data["update"]["serve"]: try: temp = Serve.objects.get(clinic__clinic_id=a["clinic_id"], patient__ktp=a["ktp"]) temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "Serve updated ", a["clinic_id"], a["ktp"] except Serve.DoesNotExist: print "Serve not exist ", a["clinic_id"], a["ktp"] # Update WorksOn, except clinic_id doctor_ktp server_arrival_timestamp for a in data["update"]["works_on"]: try: temp = Works_On.objects.get(clinic__clinic_id=a["clinic_id"], doctor__user__ktp=a["ktp"]) temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "WorksOn updated ", a["clinic_id"], a["ktp"] except Works_On.DoesNotExist: print "WorksOn not exist ", a["clinic_id"], a["ktp"] # Update Validation, except photo_number, pregnancy_number, patient_ktp server_arrival_timestamp for a in data["update"]["validation"]: try: temp = Validation.objects.get( doctor__user__ktp=a["doctor_ktp"], photo__photo_number=a["photo_number"], photo__pregnancy__pregnancy_number=a["pregnancy_number"], photo__pregnancy__patient__ktp=a["patient_ktp"], ) temp.x = a["x"] temp.y = a["y"] temp.a = a["a"] temp.b = a["b"] temp.tetha = a["tetha"] temp.has_seen = a["has_seen"] temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "Validation updated ", a["doctor_ktp"], a["photo_number"], a["pregnancy_number"], a["patient_ktp"] except Validation.DoesNotExist: print "Validation not exist ", a["doctor_ktp"], a["photo_number"], a["pregnancy_number"], a["patient_ktp"] # Update Validation, except officer doctor comment_number patient_ktp server_arrival_timestamp for a in data["update"]["comment"]: try: temp = Comment.objects.get(patient__ktp=a["patient_ktp"], comment_number=a["comment_number"]) temp.from_doctor = a["from_doctor"] temp.content = a["content"] temp.has_seen = a["has_seen"] temp.temp.is_active = a["is_active"] temp.modify_timestamp = a["modify_timestamp"] temp.create_timestamp = a["create_timestamp"] temp.server_modify_timestamp = current_timestamp temp.save() print "Validation updated ", a["patient_ktp"], a["comment_number"] except Comment.DoesNotExist: print "Validation updated ", a["patient_ktp"], a["comment_number"] # confirm_doctor = [] # confirm_json = {'user':confirm_user, # 'doctor':confirm_doctor} ###Cari new Addition # table user new_user_json = [] new_users = User.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for user in new_users: new_user_json.append(user.get_json()) # table doctor new_doctor_json = [] new_doctors = Doctor.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for doctor in new_doctors: new_doctor_json.append(doctor.get_json()) # table clinic new_clinic_json = [] new_clinics = Clinic.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for clinic in new_clinics: new_clinic_json.append(clinic.get_json()) # table officer new_officer_json = [] new_officers = Officer.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for officer in new_officers: new_officer_json.append(officer.get_json()) # table patient new_patient_json = [] new_patients = Patient.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for patient in new_patients: new_patient_json.append(patient.get_json()) # table pregnancy new_pregnancy_json = [] new_pregnancies = Clinic.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for pregnancy in new_pregnancies: new_pregnancy_json.append(pregnancy.get_json()) # table photo new_photo_json = [] new_photos = Photo.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for photo in new_photos: new_photo_json.append(photo.get_json()) # table serve new_serve_json = [] new_serves = Serve.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for serve in new_serves: new_serve_json.append(serve.get_json()) # table works_on new_workson_json = [] new_worksons = Works_On.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for workson in new_worksons: new_workson_json.append(workson.get_json()) # table validation new_validation_json = [] new_validations = Validation.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for validation in new_validations: new_validation_json.append(validation.get_json()) # table comment new_comment_json = [] new_comments = Comment.objects.all().filter(server_arrival_timestamp__gt=timestamp, is_active=True) for comment in new_comments: new_comment_json.append(comment.get_json()) # table user update_user_json = [] update_users = User.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for user in update_users: update_user_json.append(user.get_json()) # table doctor update_doctor_json = [] update_doctors = Doctor.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for doctor in update_doctors: update_doctor_json.append(doctor.get_json()) # table clinic update_clinic_json = [] update_clinics = Clinic.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for clinic in update_clinics: update_clinic_json.append(clinic.get_json()) # table officer update_officer_json = [] update_officers = Officer.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for officer in update_officers: update_officer_json.append(officer.get_json()) # table patient update_patient_json = [] update_patients = Patient.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for patient in update_patients: update_patient_json.append(patient.get_json()) # table pregnancy update_pregnancy_json = [] update_pregnancies = Clinic.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for pregnancy in update_pregnancies: update_pregnancy_json.append(pregnancy.get_json()) # table photo update_photo_json = [] update_photos = Photo.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for photo in update_photos: update_photo_json.append(photo.get_json()) # table serve update_serve_json = [] update_serves = Serve.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for serve in update_serves: update_serve_json.append(serve.get_json()) # table works_on update_workson_json = [] update_worksons = Works_On.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for workson in update_worksons: update_workson_json.append(workson.get_json()) # table validation update_validation_json = [] update_validations = Validation.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for validation in update_validations: update_validation_json.append(validation.get_json()) # table comment update_comment_json = [] update_comments = Comment.objects.all().filter( Q(is_active=True) & Q(server_modify_timestamp__gt=timestamp) | Q(modify_timestamp__gt=timestamp) ) for comment in update_comments: update_comment_json.append(comment.get_json()) return HttpResponse( simplejson.dumps( { "add": { "user": new_user_json, "doctor": new_doctor_json, "clinic": new_clinic_json, "officer": new_officer_json, "patient": new_patient_json, "pregnancy": new_pregnancy_json, "photo": new_photo_json, "serve": new_serve_json, "works_on": new_workson_json, "validation": new_validation_json, "comment": new_comment_json, }, "update": { "user": update_user_json, "doctor": update_doctor_json, "clinic": update_clinic_json, "officer": update_officer_json, "patient": update_patient_json, "pregnancy": update_pregnancy_json, "photo": update_photo_json, "serve": update_serve_json, "works_on": update_workson_json, "validation": update_validation_json, "comment": update_comment_json, }, "confirm_add": {"photo": photo_confirmation, "comment": comment_confirmation}, }, indent=4, ), mimetype="application/json", )
def save_fb_user(content): """ Internal dao method to save/update an fb user """ res = {} res['valid'] = False try: user = User() user.userid = content['id'] user.firstname = content['first_name'] if 'first_name' in content else None user.lastname = content['last_name'] if 'last_name' in content else None user.email = content['email'] if 'email' in content else None user.birthday = datetime.strptime(content['birthday'], '%m/%d/%Y') if 'birthday' in content else None user.gender = content['gender'] if 'gender' in content else None user.access_token = content['access_token'] user.location = update_fb_user_location(content['location']) if 'location' in content else None user.save() res['valid'] = True res['userid'] = content['id'] res['access_token'] = content['access_token'] except: logger.exception("Unexpected error while saving user: "+str(sys.exc_info()[0])) res['valid'] = False return res return res