def _factory_election_data(websafe_election_key): """ Factory database with data from settings.py """ # create or update election if websafe_election_key is not None: election_key = ndb.Key(urlsafe=websafe_election_key) election = election_key.get() else: election = Election() election.populate(**ELECTION_DATA) election_key = election.put() for pos_data_orig in POSITION_DATA: # avoid directly delete on setting objects pos_data = pos_data_orig.copy() position_data = pos_data['data'] del pos_data['data'] position_name = pos_data['name'] position = Position.query(ancestor=election_key).\ filter(Position.name == position_name).get() if position is None: logger.debug('creating new position entity') position_id = ndb.Model.allocate_ids( size=1, parent=election_key)[0] position_key = ndb.Key(Position, position_id, parent=election_key) position = Position(key=position_key) position.populate(**pos_data) position_key = position.put() # remove all roles under position ndb.delete_multi(position.candidate_keys) # create all roles from data candidates = [] for index, data_dict in enumerate(position_data): candidate_id = ndb.Model.allocate_ids( size=1, parent=position_key)[0] candidate_key = ndb.Key( Candidate, candidate_id, parent=position_key) candidate = Candidate(key=candidate_key) data_dict['voting_index'] = index candidate.populate(**data_dict) candidates.append(candidate) position.candidate_keys = ndb.put_multi(candidates) position.put() return "update all data successfully"
def _create_election(request): data = request_to_dict(request) election = Election(**data) election.put() return election