def post(self): payload = json.loads(self.request.body) org = Organization(title=payload['title']) org.users = [users.get_current_user().email()] org.key = org.put() self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps({'title': org.title, 'key': org.key.id_or_name()}))
def create_group(): if not request.json: abort(400) Organization.create(request.json['name'], request.json['description']) return 'Created', 201
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() org = Organization(title='Test') org.users = ['*****@*****.**'] org.key = org.put() self.org = Organization.all().get()
def put(self): payload = json.loads(self.request.body) id = int(self.request.url.rsplit('/', 1)[1]) org = Organization.get_by_id(id) org.title = str(payload['title']) org.alert_email = str(payload['alert_email']) org.put()
def UpdateOrganization(self, request, context): try: organization_identity = Organization.get_identity_resource({ "uuid": request.uuid, "visible": True }) if not organization_identity: return make_pb({}, UpdateOrganizationIdentityResponse) organization_identity.organization_domain = request.organization_domain organization_identity.name = request.name organization_identity.save() except Exception as e: warning(e) raise e return UpdateOrganizationIdentityResponse( uuid=organization_identity.uuid)
def post(self): payload = json.loads(self.request.body) org = Organization.get_by_id(int(payload['organization'])) inv = Invitation(parent=org) inv.email = payload['email'] inv.put() inv.send()
def CreateBranchOffice(self, request, context): try: branch_office_dict = dict() branch_office_dict["name"] = request.name branch_office_dict["street"] = request.street branch_office_dict["number"] = request.number branch_office_dict["city"] = request.city branch_office_dict["state"] = request.state branch_office_dict["zip_code"] = request.zip_code branch_office_dict["organization"] = dict() branch_office_dict["organization"][ "uuid"] = request.organization_uuid organization_identity = Organization.get_identity_resource({ "uuid": request.organization_uuid, "visible": True }) if not organization_identity: return make_pb({}, CreateBranchOfficeIdentityResponse) branch_office_identity = BranchOfficeSchema().load( branch_office_dict) branch_office_identity.save() except Exception as e: warning(e) raise e return CreateBranchOfficeIdentityResponse( uuid=branch_office_identity.uuid)
def save(self): cpf_check = User.check_cpf(self.cpf) if cpf_check: self.password = User.hash_password(self.password) organization = Organization(cpf_cnpj=self.cpf, description=self.fullname) organization.save() # creates an User. db.session.add(self) db.session.commit() else: raise Exception("CPF Inválido!")
def createOrganization(orgCalled): organization = Organization(called=orgCalled) print( "Enter more details of the organization: long name, legal name, uri, emailSuffix, classifiers" ) print("Press Enter if not present.") organization.longName = getStrInput("Long name") organization.legalName = getStrInput("Legal name") organization.uri = getStrInput("Uri") organization.emailSuffix = getStrInput("Email Suffix") organization.classifiers = getStrArrInput("Classifiers") organization.addToDB() return organization
def get(self): id = int(self.request.url.rsplit('/', 3)[1]) org = Organization.get_by_id(id) key = self.request.url.rsplit('/', 1)[1] heart = Heart.get_by_key_name(key, parent=org) flatlines = Flatline.all().ancestor(heart).order("-start").fetch(10) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps({'title': heart.title or heart.key().id_or_name(), 'time_zone': heart.time_zone, 'cron': heart.cron, 'threshold': heart.threshold, 'last_pulse': str(heart.last_pulse), 'flatlines': map(lambda f: {'start': str(f.start), 'end': str(f.end), 'active': str(f.active)}, flatlines)}))
def post(self): # create a new organization # parse data recept by POST and get only fields of the object newobj = self.parseInput(Organization) # getting new integer id newobj['iid'] = yield Task(self.new_iid, Organization.collection()) try: neworg = Organization(newobj) neworg.validate() # the new object is valid, so try to save try: newsaved = yield self.db.organizations.insert( neworg.to_native()) output = neworg.to_native() info(output) output['obj_id'] = str(newsaved) # Change iid to id in the output self.switch_iid(output) self.finish( self.json_encode({ 'status': 'success', 'message': 'new organization saved', 'data': output })) except Exception as e: # duplicated index error self.response(409, 'Duplicated name for an organization.') except Exception as e: # received data is invalid in some way self.response(400, 'Invalid input data.')
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() self.testbed.init_taskqueue_stub() self.testbed.init_taskqueue_stub( root_path=os.path.join(os.path.dirname(__file__), '..')) self.taskqueue_stub = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME) org = Organization(title='Test') org.users = ['*****@*****.**'] org.key = org.put() self.org = Organization.all().get() app = webapp2.WSGIApplication([('/checkforflatlines.*', CheckForFlatlineHandler)]) self.testapp = webtest.TestApp(app)
def read_org(self,org_dict): if (org_dict is None): return None name = org_dict[0] location = org_dict[1] hyperlink = org_dict[2] org_id = org_dict[3] org = Organization(name,hyperlink,location,org_id,org_dict[4]) return org
def register(self): cpf_check = True # User.check_cpf(self.cpf) if cpf_check: self.password = User.hash_password(self.password) organization = Organization(cpf_cnpj=self.cpf, description=self.fullname) organization.save() self.organization = organization self.fk_organizations_id = organization.id # creates an User. db.session.add(self) db.session.commit() else: raise Exception("CPF Inválido!")
def create_organization(): content = dict(wikidata_from(request.json['name'])) organization = Organization.create_or_modify(content, 'entity') ApiHandler.save(organization) return jsonify(as_dict(organization)), 201
def get(self): id = int(self.request.url.rsplit('/', 2)[1]) org = Organization.get_by_id(id) hearts = Heart.all().ancestor(org.key()).order("-created").fetch(2000) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps({ 'title': org.title, 'hearts': map(indextransform, hearts) }))
def delete(self): id = int(self.request.url.rsplit('/', 3)[1]) org = Organization.get_by_id(id) key = self.request.url.rsplit('/', 1)[1] heart = Heart.get_by_key_name(key, parent=org) flatlines = Flatline.all(keys_only=True).ancestor(heart).order("-start") heart.delete() for f in flatlines: db.delete(f)
def get(self): id = int(self.request.url.rsplit('/', 1)[1]) org = Organization.get_by_id(id) newhearts = Heart.all().ancestor(org.key()).filter('title =', '').fetch(2000) flatlines = Flatline.all().filter("active =", True).fetch(2000) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps({ 'newhearts': map(indextransform, newhearts), 'flatlines': map(flatlinetransform, flatlines), }))
def GetOrganizations(self, request, context): organization_identities = Organization.get_all() organization_identities_dict = OrganizationSchema( many=True).dump(organization_identities) for organization_identity in organization_identities_dict: yield make_pb(organization_identity or {}, GetOrganizationsResponse)
def construct_contributors(in_json): # need to know if it is person or organization # TODO make better algorithm for this, but for now use if there is firstname or lastname it is a Person, otherwise, organization is_person = False try: firstname = in_json["firstName"] is_person = True except: pass try: lastname = in_json["lastName"] is_person = True except: pass try: middlename = in_json["middleName"] is_person = True except: pass contributor_dataset = None if is_person: contributor_dataset = Person('') contributor_dataset, restjson = datasetutils.update_person_dataset_from_json( contributor_dataset, in_json) # set affiliation try: affilication_json = in_json['affiliation'] affilication_dataset = Organization('') affilication_dataset, restjson = datasetutils.update_organization_dataset_from_json( affilication_dataset, affilication_json) contributor_dataset.set_affilication(affilication_dataset) del restjson['affiliation'] except: pass else: # organization contributor_dataset = Organization('') contributor_dataset, restjson = datasetutils.update_organization_dataset_from_json( contributor_dataset, in_json) return contributor_dataset, restjson, None
def get(self): id = int(self.request.url.rsplit('/', 2)[1]) org = Organization.get_by_id(id) hearts = Heart.all().ancestor(org.key()).order("-created").fetch(2000) # Activate hearts before deactivated onces hearts.sort( cmp=lambda x,y: -1 if x.threshold > 0 else 1 ) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps({ 'organization': indextransform( org ), 'hearts': map(heartlisttransform, hearts) }))
def get(self): id = self.request.get_all('id')[0] org = int(self.request.get_all('org')[0]) if id.find('\\') > 0: self.response.write('key must not contain backslash') return h = Organization.get_by_id(org).get_heart(id) h.register_pulse() self.response.write('ok')
def get(self): id = int(self.request.url.rsplit('/', 1)[1]) org = Organization.get_by_id(id) newhearts = Heart.all().ancestor(org.key()).filter('title =', '').fetch(2000) flatlines = Flatline.all().filter("active =", True).fetch(2000) self.response.headers['Content-Type'] = 'application/json' self.response.out.write( json.dumps({ 'newhearts': map(indextransform, newhearts), 'flatlines': map(flatlinetransform, flatlines), }))
def get(self): id = self.request.get_all('id')[0] org = int(self.request.get_all('org')[0]) if id.find('\\') > 0: self.response.write('key must not contain backslash') return h = Organization.get_by_id(org).get_heart(id) h.registerPulse() self.response.write('ok')
def put(self): payload = json.loads(self.request.body) id = int(self.request.url.rsplit('/', 3)[1]) org = Organization.get_by_id(id) key = self.request.url.rsplit('/', 1)[1] heart = Heart.get_by_key_name(key, parent=org) heart.title = str(payload['title']) heart.threshold = int(payload['threshold']) heart.cron = str(payload['cron']) heart.time_zone = str(payload['time_zone']) croniter(heart.cron) heart.put()
def export(self): """Generate single JSON file defining dynamic site objects Export dynamic data, such as Organizations and Access Strategies for import into other sites. This does NOT export values expected to live in the site config file or the static set generated by the seed managment command. To import the data, use the seed command as defined in manage.py """ d = self.__header__({}) d['entry'] = [] # Add organizations orgs = Organization.generate_bundle() d['entry'] += orgs['entry'] # Add strategies (AKA access rules) # and sharable portions of interventions for intervention in INTERVENTION: d['entry'].append(intervention.as_json()) rules = [x.as_json() for x in intervention.access_strategies] if rules: d['entry'] += rules # Add Questionnaires for q in Questionnaire.query.all(): d['entry'].append(q.as_fhir()) # Add QuestionnaireBanks for qb in QuestionnaireBank.query.all(): d['entry'].append(qb.as_json()) # Add customized app strings app_strings = AppText.query.all() for app_string in app_strings: d['entry'].append(app_string.as_json()) # Add communication requests crs = CommunicationRequest.query.all() for cr in crs: d['entry'].append(cr.as_fhir()) # Add scheduled job info for job in ScheduledJob.query.all(): d['entry'].append(job.as_json()) # Add site.cfg config_data = read_site_cfg() d['entry'].append(config_data) self.__write__(d)
def update_org(org_fhir): org = Organization.from_fhir(org_fhir) existing = Organization.query.get(org.id) if existing: details = StringIO() if not dict_match(org_fhir, existing.as_fhir(), details): self._log("Organization {id} collision on " "import. {details}".format( id=org.id, details=details.getvalue())) existing.update_from_fhir(org_fhir) else: self._log("org {} not found - importing".format(org.id)) db.session.add(org)
def post(self): id = self.request.get_all('id')[0] org = int(self.request.get_all('org')[0]) if id.find('\\') > 0: self.response.write('key must not contain backslash') return pulse_time = datetime.datetime.strptime(self.request.get('pulse_time'),"%Y-%m-%d %H:%M:%S.%f") h = Organization.get_by_id(org).get_heart(id) h.register_pulse(pulse_time) self.response.write('ok')
def GetOrganizationByUUID(self, request, context): organization_identity = Organization.get_identity_resource({ "uuid": request.uuid, "visible": True }) organization_identity = OrganizationSchema().dump( organization_identity) warning(organization_identity) return make_pb(organization_identity or {}, GetOrganizationIdentityByUUIDResponse)
def findOrganization(): orgCalled = input("Search for the organization you interacted with: ") organizationResults = Organization.findByCalled(orgCalled) if len(organizationResults) == 0: print(orgCalled + " is not in the database, please add it in") return createOrganization(orgCalled) else: print("Here are the organizations found: ") for i in range(0, len(organizationResults)): print(" {}. {}".format(str(i + 1), organizationResults[i].called)) i = getIntInput( "Type the index of the organization you interacted with: ") return organizationResults[i - 1]
def put(self): payload = json.loads(self.request.body) id = int(self.request.url.rsplit('/', 3)[1]) org = Organization.get_by_id(id) key = self.request.url.rsplit('/', 1)[1] heart = Heart.get_by_key_name(key, parent=org) heart.title = str(payload['title']) heart.check_deactivation(int(payload['threshold'])) heart.threshold = int(payload['threshold']) heart.maintenance_day = datetime.strptime(payload['maintenance_day'], '%Y-%m-%d').date() if len( payload['maintenance_day'] ) > 0 else None heart.cron = str(payload['cron']) heart.time_zone = str(payload['time_zone']) croniter(heart.cron) heart.check_maintenance() heart.put()
def get(self): id = int(self.request.url.rsplit('/', 2)[1]) org = Organization.get_by_id(id) rangestart = datetime.utcnow() - timedelta(days=7) hearts = Heart.all().ancestor(org.key()).filter('title !=', '').count() oldflatlines = Flatline.all().filter("start >", rangestart).order("-start").fetch(2000) oldflatlinesactive = Flatline.all().filter("end >", rangestart).order("-end").fetch(2000) oldflatlines = list(set(oldflatlines) | set(oldflatlinesactive)) alltime = hearts*24*60*60*7 if hearts > 0 else 1 downtime = sum(map(lambda x: x.seconds, map(lambda x: (x.end if x.end is not None else datetime.utcnow()) - (x.start if x.start < rangestart else rangestart),oldflatlines))) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps({ 'organization': indextransform( org ), 'flatlines': map(flatlinetransform, oldflatlines), 'availablility' : 1 - float(downtime)/alltime, 'downtime' : downtime, 'hearts': hearts }))
def create_organization(user, name, git, members=0, admin=0, verify=None): try: organization = Organization(name, git, members=1) db.session.add(organization) db.session.flush() members = Members(organization.id, user.id, admin=1) db.session.add(members) if verify: db.session.delete(verify) db.session.commit() clear_organization_cache(organization, user=user) return organization, None except sqlalchemy.exc.IntegrityError, e: db.session.rollback() if 'Duplicate entry' in e.message: return None, code.ORGANIZATION_GITNAME_EXISTS logger.exception(e) return None, code.UNHANDLE_EXCEPTION
def GetBranchOfficesByEmail(self, request, context): filter_dict = dict() filter_dict["organization_domain"] = request.organization_domain filter_dict["visible"] = True organization_identity = Organization.get_identity_resource(filter_dict) organization_identity_dict = OrganizationSchema( only=("branch_offices", )).dump(organization_identity) branch_office_identity_list = BranchOfficeSchema( many=True, only=("uuid", "name")).dump(organization_identity_dict["branch_offices"]) for branch_office_identity in branch_office_identity_list: yield make_pb(branch_office_identity or {}, GetBranchOfficesByEmailResponse)
def get(self): org_id = self.request.url.rsplit('/', 1)[1] if not org_id.isdigit(): self.abort(404) org = Organization.get_by_id(int(org_id)) if org is None: self.abort(404) newhearts = Heart.all().ancestor(org.key()).filter('title =', '').fetch(2000) maintenancehearts = Heart.all().ancestor(org.key()).filter('maintenance_day !=', None).order('-maintenance_day').fetch(2000) flatlines = Flatline.all().filter("active =", True).fetch(2000) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps({ 'title': org.title, 'newhearts': map(indextransform, newhearts), 'flatlines': map(flatlinetransform, flatlines), 'maintenancehearts': map(heartlisttransform, maintenancehearts), 'users': org.users, 'alert_email' : org.alert_email, }))
def DeleteOrganization(self, request, context): try: filter_dict = dict() filter_dict["uuid"] = request.uuid organization_identity = Organization.get_identity_resource( filter_dict) if not organization_identity: return DeleteOrganizationIdentityResponse( uuid=organization_identity) organization_identity.disable() except Exception as e: warning(e) raise e return DeleteOrganizationIdentityResponse( uuid=organization_identity.uuid)
def get(self): id = int(self.request.url.rsplit('/', 3)[1]) org = Organization.get_by_id(id) key = self.request.url.rsplit('/', 1)[1] heart = Heart.get_by_key_name(key, parent=org) flatlines = Flatline.all().ancestor(heart).order("-active").order("-start").order("-end").fetch(10) response = {'organization': indextransform(org), 'title': heart.title or heart.key().id_or_name(), 'time_zone': heart.time_zone, 'cron': heart.cron, 'threshold': heart.threshold, 'last_pulse': str(heart.last_pulse or ''), 'maintenance_day': str(heart.maintenance_day or ''), 'flatlines': map(flatlinetransform, flatlines), 'calculated_flatline': str(heart.calculate_next_flatline() or '') } self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(response))
def publish_point_received( self, point_id: PyObjectId, organization_id: PyObjectId, device_id: PyObjectId, ): topic = self.topic_to_routing_key(self.topic_point_received) topic = topic.replace("#", str(organization_id)) organization = db.organizations.find_one({"_id": organization_id}) organization = Organization.validate(organization) organization_dict = organization.dict(by_alias=True) organization_dict["_id"] = str(organization.id) result = json.dumps( { "point_id": str(point_id), "device_id": str(device_id), "organization": organization_dict, }, ensure_ascii=False, ) self.mqtt.publish(topic, result, qos=0, retain=True) OnMessageLog(logging.INFO, "포인트 수신 신호 전달", topic, result).report()
def social_from_row(row, unused_index=None): if row.get('url') is None: return None organization_name = row['url'].replace('https://www.', '') \ .split('/')[0] \ .split('.')[0] \ .title() organization = Organization.create_or_modify({ '__SEARCH_BY__': 'name', 'name': organization_name }) medium_dict = { '__SEARCH_BY__': 'scienceFeedbackIdentifier', 'name': row['Name'], 'organization': organization, 'scienceFeedbackIdentifier': row['airtableId'], 'url': row['url'] } return Medium.create_or_modify(medium_dict)
async def handle_data_topics(client, topic, payload, qos, properties): """TOPIC_POINT_GROUP Handler""" logger.info(f"point received! {topic}, {payload}") response = payload.decode() response = json.loads(response) # 현재 기기에서 보낸 데이터면 유저의 바코드 입력을 처리 try: device_id = response.get("device_id") if device_id == self.device_id: point_id = response.get("point_id") db.upsert(DBType.last_point, point_id) await config.ws.send_text("inserted") else: await config.ws.send_text("point") except: pass organization = Organization.parse_obj(response.get("organization")) organization = organization.dict(by_alias=True) organization["_id"] = str(organization["_id"]) db.upsert(DBType.organization, organization)
def create_or_modify_sf_organization_and_media(): organization = Organization.create_or_modify({ '__SEARCH_BY__': 'name', 'name': 'Science Feedback', }) ApiHandler.save(organization) climate_medium = Medium.create_or_modify({ '__SEARCH_BY__': 'name', 'logoUrl': 'https://climatefeedback.org/wp-content/themes/wordpress-theme/dist/images/Climate_Feedback_logo_s.png', 'name': 'Climate Feedback', 'organization': organization, 'url': 'https://climatefeedback.org', }) health_medium = Medium.create_or_modify({ '__SEARCH_BY__': 'name', 'logoUrl': 'https://healthfeedback.org/wp-content/themes/wordpress-theme/dist/images/healthfeedback_logo.png', 'name': 'Health Feedback', 'organization': organization, 'url': 'https://healthfeedback.org', }) science_medium = Medium.create_or_modify({ '__SEARCH_BY__': 'name', 'logoUrl': 'https://sciencefeedback.co/wp-content/themes/SF-wordpress/dist/images/sciencefeedback_logo.png', 'name': 'Science Feedback', 'organization': organization, 'url': 'https://sciencefeedback.co', }) ApiHandler.save(climate_medium, health_medium, science_medium)
async def organization_list(): return [ Organization(**i) for i in db.organizations.find().sort("point", -1) ]
def get(self): user = users.get_current_user() orgs = Organization.all().filter('users =', user.email()) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(map(indextransform, orgs)))
def get(self): rangestart = datetime.utcnow() - timedelta(days=7) organizations = Organization.all(); for org in organizations: send_report(org, rangestart) self.response.out.write("ok")
def make_org(self, data, **kwargs): from models.organization import Organization return Organization(**data)
return data response = {'messages':list()} for fn in files: print(jsonpath+fn) data = readData(jsonpath+fn) if fn == 'organizations.json': print('Importing Organizations') for d in data: obj = dict(d) obj['iid'] = obj['id'] del obj['id'] obj['created_at'] = datetime.strptime(obj['created_at'], '%Y-%m-%d %H:%M:%S.%f') obj['updated_at'] = datetime.strptime(obj['updated_at'], '%Y-%m-%d %H:%M:%S.%f') try: newobj = Organization(obj) newobj.validate() nob = db.organizations.insert(newobj.to_native()) print 'added: '+str(nob)+' - '+obj['name'] except ValidationError, e: print('Fail to import organizations. Errors: '+str(e)) break response['messages'].append('organizations imported') elif fn == 'lions.json': print('Importing Organizations') for d in data: obj = dict(d) obj['iid'] = obj['id'] del obj['id'] obj['organization_iid'] = obj['organization_id'] del obj['organization_id']
print(str(printNew.uuid) + str(printNew.interactionMaterial_uuids[0])) newInteractionMaterial = InteractionMaterial(name="testinteractionmaterial") newInteractionMaterial.addToDB() printNew = InteractionMaterial.getByUUID(newInteractionMaterial.uuid) print(str(printNew.uuid) + printNew.name) newOrg = Organization(called="testOrg", longName="test organization") newOrg.addToDB() printNew = Organization.getByUUID(newOrg.uuid) print(str(printNew.uuid) + printNew.called) newPerson = Person(called="Don", givenName="Donald", surName="Burton", gender="Male", hasUserAccount=True, isTeamMember=True) newPerson.addToDB() printNew = Person.getByUUID(newPerson.uuid) print(str(printNew.uuid) + printNew.gender)