def create_country_nodes(df): n_nodes = 0 for _, row in df.drop_duplicates(subset=["country"]).iterrows(): country = Country(name=row["country"]) country.save() n_nodes += 1 print("created {} nodes".format(n_nodes))
def setUp(self): self.data = [ Country(name="United States of America", iso_two_letter="US"), Country(name="The Netherlands", iso_two_letter="NL"), Country(name="Germany", iso_two_letter="DE"), Country(name="Czech Republic", iso_two_letter="CZ") ]
def get_country_objects(filename: str): from models import engine, db_session, Country with open(filename, 'r') as readfile: reader = csv.reader(readfile) country_list = [] for index, row in enumerate(reader): print(f'row: {row}') if index == 0: continue if row[2] == '': row[2] = '0.0' try: country = Country(name=row[0], total_cases=int(float(row[1])), total_deaths=int(float(row[2]))) country_list.append(country) except ValueError: country = Country(name=row[0], total_cases=0.0, total_deaths=int(row[2])) country_list.append(country) return country_list
def test01_initial_sql(self): "Testing geographic initial SQL." if DISABLE: return if SpatialBackend.oracle: # Oracle doesn't allow strings longer than 4000 characters # in SQL files, and I'm stumped on how to use Oracle BFILE's # in PLSQL, so we set up the larger geometries manually, rather # than relying on the initial SQL. # Routine for returning the path to the data files. data_dir = os.path.join(os.path.dirname(__file__), 'sql') def get_file(wkt_file): return os.path.join(data_dir, wkt_file) State(name='Colorado', poly=fromfile(get_file('co.wkt'))).save() State(name='Kansas', poly=fromfile(get_file('ks.wkt'))).save() Country(name='Texas', mpoly=fromfile(get_file('tx.wkt'))).save() Country(name='New Zealand', mpoly=fromfile(get_file('nz.wkt'))).save() # Ensuring that data was loaded from initial SQL. self.assertEqual(2, Country.objects.count()) self.assertEqual(8, City.objects.count()) # Oracle cannot handle NULL geometry values w/certain queries. if SpatialBackend.oracle: n_state = 2 else: n_state = 3 self.assertEqual(n_state, State.objects.count())
def un_hdi_import(): book = open_workbook('./data/un_hdi.xlsx') sheet = book.sheet_by_name('Table 2') connect(host=db) for row in range(7, sheet.nrows): name = sheet.cell(row, 1).value hdi_score = sheet.cell(row, 14).value hdi_rank = sheet.cell(row, 0).value Country.objects(name=name).update(hdi_score=hdi_score, hdi_rank=hdi_rank)
def main(): c = Country() c.countryname = "testName" print("{0} {1}".format(c.countryname, c.countryid)) _session = Session() _session.add(c) _session.commit() result = _session.query(Country) c2 = result.first() print(c2.countryname)
def POST(self, name): """Inserts new country.""" data = json.loads(web.data()) country_code = data.get('country_code') country_name = data.get('country_name') try: assert country_code and country_name except AssertionError as error: logger.debug(error) raise Error(BADPARAMS) country = Country(country_code, country_name) country.save() return [country.__dict__]
def happiness_import(): book = open_workbook('./data/kaggle_happiness.xlsx') sheet = book.sheet_by_name('2017') connect(host=db) for row in range(1, sheet.nrows): name = sheet.cell(row, 0).value happiness_score = sheet.cell(row, 2).value happiness_rank = sheet.cell(row, 1).value Country.objects(name=name).update( happiness_score=happiness_score, happiness_rank=happiness_rank)
def GET(self, name): """ Get countries.""" logger.debug("Query: %s" % (web.input())) country_name = web.input().get('country_name') if country_name: results = Country.get_from_name(country_name) else: results = Country.get_all() if not results: raise Error(NORESULT) data = results_to_countries(results) return data
def pre_request_setup(): global cached_countries if not cached_countries: stored_countries = [ country.format() for country in Country.query.all() ] if not stored_countries: countries = requests.get(REST_COUNTRIES_ALL) simplified_countries = get_simplified_countries( countries.json()) Country.insert_all(simplified_countries) cached_countries = simplified_countries else: cached_countries = stored_countries
def load_countries(request, indexfile=""): if indexfile == "": indexfile = "iso3166codes.csv" fin = open(indexfile, 'rb') csvin = csv.reader(fin) headers = csvin.next() for row in csvin: print(row[0] + ":" + row[1]) print(type(row[1])) newcountry = Country(ISOalpha3=row[0].decode('latin-1'), ISOname=row[1].decode('latin-1')) newcountry.save() return HttpResponse("Country details loaded from file "+ indexfile)
def load_countries(request, indexfile=""): if indexfile == "": indexfile = "iso3166codes.csv" fin = open(indexfile, 'rb') csvin = csv.reader(fin) headers = csvin.next() for row in csvin: print(row[0] + ":" + row[1]) print(type(row[1])) newcountry = Country(ISOalpha3=row[0].decode('latin-1'), ISOname=row[1].decode('latin-1')) newcountry.save() return HttpResponse("Country details loaded from file " + indexfile)
def get_country(fields=[], lang='en'): items = [] if lang == 'en': items = Country.objects().exclude("translation") items = items2dict(items) # items = json.dumps(items) elif lang: items = Country.objects(translation__language=lang).exclude( "name").exclude("language").order_by("translation__name") items = items2dict(items) items = translations_unify(items, lang) else: items = [] return items
def api_country_insert(): new_country = request.get_json() country = Country(id=new_country['id'], name=new_country['name']) db.session.add(country) db.session.commit() country_json = {"id": country.id, "name": country.name} return jsonify(country_json)
def fill_data(): countries = ['Portugal', 'Germany', 'Spain', 'France', 'USA', 'China', 'Russia', 'Japan'] for country in countries: c = Country(name=country) try: db.session.add(c) db.session.commit() except Exception as e: log.error("Update ViewMenu error: {0}".format(str(e))) db.session.rollback() try: data = db.session.query(CountryStats).all() if len(data) == 0: for x in range(1, 40): cs = CountryStats() cs.population = random.randint(1, 100) cs.unemployed = random.randint(1, 100) cs.college = random.randint(1, 100) year = random.choice(range(1900, 2012)) month = random.choice(range(1, 12)) day = random.choice(range(1, 28)) cs.stat_date = datetime.datetime(year, month, day) cs.country_id = random.randint(1, len(countries)) db.session.add(cs) db.session.commit() except Exception as e: log.error("Update Data error: {0}".format(str(e))) db.session.rollback()
def post(self): if request.json: data = request.json else: data = request.form if (len(data.get('country_id')) == 0 or len(data.get('country_name')) == 0 or len(str(data.get('region_id'))) == 0 or int(data.get('region_id')) == 0): return jsonify({'message': 'Informe todos os campos.'}), 409 countryID = Country.query.filter_by( country_id=data.get('country_id')).first() if countryID: return jsonify({'message': 'Country ID já cadastrado.'}), 409 country = Country().department_form_data(data) db.session.add(country) try: db.session.commit() return jsonify({'message': 'Country inserido.'}) except Exception as e: return jsonify( {'message': 'Não foi possivel executar a operação.'}), 500
def get_game_questions(countries, questions_len=10): selected_countries = sample(countries, questions_len * QUESTION_CHOICES) questions = [] for i in range(0, len(selected_countries), QUESTION_CHOICES): correct_answer_index = randint(0, QUESTION_CHOICES - 1) correct_answer = selected_countries[i:i + QUESTION_CHOICES][ correct_answer_index]["id"] question = { "correctAnswer": correct_answer, "options": [ Country( id=s_c["id"], name=s_c["name"], capital=s_c["capital"], region=s_c["region"], flag="", ).format() for s_c in selected_countries[i:i + QUESTION_CHOICES] ], } questions.append(question) return questions
def test_country_4(self): c = Country(name='Cowland') a = Article(title='President Cowy McMoo to Ban Strawberry Milk') c.articles.append(a) db.session.add(c) first = Country.query.first() self.assertEqual(len(first.articles), 1)
def test_country_5(self): c = Country(name='Cowland') s = Organization(name='Monthly Milkpost') c.organizations.append(s) db.session.add(s) first = Country.query.first() self.assertEqual(len(first.organizations), 1)
def set_country_menu(bot, update, to_edit): uid = util.uid_from_update(update) countries = Country.select().order_by(Country.name).execute() buttons = util.build_menu([ InlineKeyboardButton('{} {}'.format(c.emojized, c.name), callback_data=util.callback_for_action( CallbackActions.SET_COUNTRY, { 'cid': c.id, 'bid': to_edit.id })) for c in countries ], 3) buttons.insert(0, [ InlineKeyboardButton(captions.BACK, callback_data=util.callback_for_action( CallbackActions.EDIT_BOT, {'id': to_edit.id})), InlineKeyboardButton("None", callback_data=util.callback_for_action( CallbackActions.SET_COUNTRY, { 'cid': 'None', 'bid': to_edit.id })), ]) return bot.formatter.send_or_edit( uid, util.action_hint( "Please select a country/language for {}".format(to_edit)), to_edit=util.mid_from_update(update), reply_markup=InlineKeyboardMarkup(buttons))
def __init__(self, **kwargs): super(RV, self).__init__(**kwargs) for country in Country.select(): self.data_items.append(country.name) self.data_items.append(country.abbr) self.data_items.append(country.phone) self.data = [{'text': str(x)} for x in self.data_items]
def store_city(): country = request.json.get("country", "ni") city = request.json.get("city", "Managua") active = request.json.get("active", False) country_rs = Country.query.filter(Country.country == country).one_or_none() if country_rs is not None: city_rs = City.query.filter(City.country_id == country_rs.id).filter( City.city == city).one_or_none() if city_rs is None: city_rs = City(city=city, active=active, country_id=country_rs.id) db.session.add(city_rs) db.session.commit() else: country_rs = Country(country=country) db.session.add(country_rs) db.session.commit() city_rs = City(city=city, active=active, country_id=country_rs.id) db.session.add(city_rs) db.session.commit() info = {"active": active, "country": country, "city": city} return jsonify(info)
def add_to_data_load(data): country = Country( code=data.get('alpha2Code'), name=data.get('name'), capital=data.get('capital'), region=data.get('region') or 'Unknown', subregion=data.get('subregion'), population=data.get('population'), flag=data.get('flag'), ) if country not in countries: countries.append(country) for language_data in data.get('languages'): language = Language(code=language_data.get('iso639_2'), name=language_data.get('name')) if language not in languages: languages.append(language) country_language.append( CountryLanguage(country_code=country.code, language_code=language.code)) for currency_data in data.get('currencies'): if currency := validate_currency(currency_data): if currency not in currencies: currencies.append(currency) country_currency.append( CountryCurrency(country_code=country.code, currency_code=currency.code))
def update_user(payload={}, fields=[]): if 'user_id' in payload: user_id = payload.pop('user_id') # print(payload) user = User.objects(pk=user_id) if user is not None: user = user.first() if 'country' in payload: payload['country'] = Country(pk=payload['country']) if 'gender' in payload and payload['gender'] is not None: payload['gender'] = Gender(pk=int(payload['gender'])) if 'languages' in payload: payload['languages'] = [ Language(pk=lang) for lang in payload['languages'] ] if 'department' in payload and payload['department'] is not None: payload['department'] = Department( pk=int(payload['department'])) if 'chair' in payload and payload['chair'] is not None: payload['chair'] = Chair(pk=int(payload['chair'])) if 'bio' in payload: payload["bio"] = payload['bio'] updated = user.update(**payload) print(user) return updated >= 1, payload else: print("Not found") return False, None else: print("Not found") return False, None
def view_regions_serialise(request, country): if request.method == "GET": if request.GET.has_key("format") and request.GET["format"] == "csv": contents = "" c = Country.get_by_key_name(country) if c is not None: for r in Country.get_by_key_name(country).region_set: contents_list = [r.key().name(), r.long_name] contents += string.join(contents_list, ",") contents += "\n" return HttpResponse(contents) return HttpResponseNotFound()
def view_events_serialise(request, country, region): """ AJAX return list of events for given country and region if user is registered, than provide information about favorite and RSVP state """ if request.method == "GET": if request.GET.has_key("format") and request.GET["format"] == "csv": r = None c = None if country != u"all": c = Country.get_by_key_name(country.strip()) if c is None: return HttpResponse("") if region != u"all": r = Region.get_by_key_name(region.strip()) if r is None: return HttpResponse("") # if r defined, then c has to be defined as well assert not r or (r and c) q = Event.all() if c: q.filter("country =", c) if r: q.filter("region =", r) in_iframe = request.GET.has_key("in_iframe") return HttpResponse(serialise_events_for_query(q, request.user, in_iframe, True, True)) return HttpResponseNotFound()
def apply(self): try: if self.subject is None: self.delete_instance() return False except Bot.DoesNotExist: self.delete_instance() return False if self.action == 'category': from models import Category try: cat = Category.get(Category.id == self.value) self.subject.category = cat except Category.DoesNotExist: raise AttributeError("Category to change to does not exist.") elif self.action == 'name': self.subject.name = self.value elif self.action == 'username': self.subject.username = self.value elif self.action == 'description': self.subject.description = self.value elif self.action == 'extra': self.subject.extra = self.value elif self.action == 'country': if self._value == 'None' or self._value is None: self.subject.country = None else: from models import Country try: con = Country.get(id=self._value) self.subject.country = con except Country.DoesNotExist: raise AttributeError( "Country to change to does not exist.") elif self.action == 'inlinequeries': self.subject.inlinequeries = bool(self.value) elif self.action == 'official': self.subject.official = bool(self.value) elif self.action == 'offline': self.subject.offline = bool(self.value) elif self.action == 'spam': self.subject.spam = bool(self.value) elif self.action == 'add_keyword': kw_obj = Keyword(name=self.value, entity=self.subject) kw_obj.save() elif self.action == 'remove_keyword': try: kw_obj = Keyword.get(name=self.value, entity=self.subject) kw_obj.delete_instance() except Keyword.DoesNotExist: raise AttributeError( "Keyword to disable does not exist anymore.") self.subject.save() self.executed = True self.save() return True
def get(self): country_name = self.request.get('country_name') country = Country.get_by_name(country_name) if country: self.response.out.write( self.entity_browser_entity_part(country.key())) else: self.response.out.write(json.dumps("Country not found."))
def test_article_5(self): c = Country(name='Cowland') a = Article(title='Why you shouldn\'t drink your own milk') a.countries.append(c) db.session.add(a) first = Article.query.first() self.assertEqual(len(first.countries), 1) self.assertEqual(len(c.articles), 1)
def entity_browser_body(self, *args): country_key = args[0] entity_list = None if country_key: entity_list = Entity.gql("where country=:country_key", country_key=country_key) else: member = self.current_member() country = Country.gql("WHERE name = :country_name", country_name=member.country).get() entity_list = Entity.gql("where country=:country_key", country_key=country.key()) param = self.render_parameters() param["entity_list"] = entity_list param["country_list"] = Country.all() return self.render("entity_browser_body", param)
def db_update(all_sts_ls): """Update databse, as input take double nested list of stats""" rtn_change_id = [] logger.debug(str(len(all_sts_ls))) for country in all_sts_ls: ctry = search(country[1]) if ctry == None: logger.info("NEW COUNTRY:" + country[1]) ctry = Country(c_pos=country[0], c_name = country[1], c_name_pl=country[1], c_ill_sum = country[2], c_inf_tdy = country[3], c_dead = country[4], c_deaths_tdy = country[5], c_recover = country[6], c_curr_cases = country[7], c_crit_cases = country[8], c_case_1m = country[9], c_dead_1m = country[10]) db.session.add(ctry) else: logger.debug("%d, %s" %(ctry.c_id, ctry.c_name)) chng = ctry.update(country[0], country[2], country[3], country[4], country[5], country[6], country[8], country[9], country[10], country[11]) if chng: rtn_change_id.append(ctry.c_id) db.session.commit() return rtn_change_id
def __init__(self): self.players = pd.DataFrame(list(Player.select().dicts())) self.country = pd.DataFrame(list(Country.select().dicts())) self.league = pd.DataFrame(list(League.select().dicts())) self.team = pd.DataFrame(list(Team.select().dicts())) self.match = pd.DataFrame(list(Match.select().dicts())) self.player_attributes = pd.DataFrame( list(PlayerAttributes.select().dicts())) self.team_attributes = pd.DataFrame( list(TeamAttributes.select().dicts())) self.preprocess()
def wineCountryNew(): """Create a new country""" if request.method == 'POST': newCountry = Country(name=request.form['name']) DBSession = open_db_session() DBSession.add(newCountry) DBSession.commit() DBSession.close() return redirect(url_for('wine_bp.wineCountriesRegions')) else: # Route should only be called with POST return redirect(url_for("auth_bp.wineLogin"))
def setUp(self): db.create_all() laureate1 = Laureate("Yuan", 1, "1956-11-2", "M", "u1", 1) laureate1.search_text = "yuan taiwan" laureate2 = Laureate("Yuan", 2, "1939-4-7", "F", "u2", 1) laureate2.search_text = "yuan" prize1 = Prize("Physics", 1991, 2, "motivation1", "u1") prize1.search_text = "one yuan" prize2 = Prize("Physics", 1991, 2, "motivation1", "u1") prize2.search_text = "taiwan one yuan" country1 = Country("SE", "Sweden", 10, 7, 10000000, "u1") country1.search_text = "taiwan ldksfjsl;fkjsd yuan" country2 = Country("SR", "Sweden", 10, 7, 10000000, "u1") country2.search_text = "two yuan" db.session.add(laureate1) db.session.add(laureate2) db.session.add(prize1) db.session.add(prize2) db.session.add(country1) db.session.add(country2) db.session.commit()
def __init__(self, *args, **kwargs): super(BaseEventFilterForm, self).__init__(*args, **kwargs) q = Country.all().order('long_name') choices = [('all', 'All')] for c in q: choices.append( (c.key().name(), '%s [%s]'%(c.long_name, c.key().name())) ) self.fields['country'].choices = choices q = Region.all().order('long_name') choices = [('all', 'All')] for r in q: choices.append( (r.key().name(), '%s'%(r.long_name)) ) self.fields['region'].choices = choices
def get(self): if self.user: c = Country.all().order('-name') countries = list(c) s = Subregion.all().order('-name') subregion = list(s) wt = WineType.all().order('-name') wine_types = list(wt) g = Grape.all().order('-name') grapes = list(g) self.render("newwine.html",countries=countries, subregions=subregion, wine_types=wine_types, grapes=grapes) else: self.redirect("/login")
def handle(self, countryNameKey, areaNameKey): country = Country.get_by_id(self.helper.getNormalisedCountryName(countryNameKey)) if country is None: raise PageNotFoundException() area = country.getAreaForName(areaNameKey) if area is None: raise PageNotFoundException() return { "subtemplate": self.resolveTemplatePath("area.html"), "title": "Shark Attack Data: %s, %s" % (area.name, country.name), "country": country, "area": area, "breadcrumb_data": self.getBreadcrumbData(area), "meta_description": "A complete list of the shark attacks that have occurred in %s, %s." % (area.name, country.name) }
def view_subscribe(request): # login is required here # if not ( request.user and request.user.is_authenticated() ): # return HttpResponseRedirect() if request.user.subscription_set.count() >= Subscription._MAX_SUBSCRIPTIONS_PER_USER: Message( user=request.user, message=ugettext("You've reached maximum number of subscriptions. Delete some and try again."), ).put() elif request.method == "GET": search_form = AdvancedEventFilterForm(request.GET) if search_form.is_valid(): country = Country.get_by_key_name(search_form.cleaned_data["country"]) region = Region.get_by_key_name(search_form.cleaned_data["region"]) free = search_form.cleaned_data["forfree"] if search_form.cleaned_data["forwho"] == "custom": event_types = 0 for t in search_form.cleaned_data["typelist"]: event_types += 1 << int(t) elif search_form.cleaned_data["forwho"] == "everyone": event_types = Event.OPEN_EVENTS_MASK else: # assert(search_form.cleaned_data['forwho'] == 'members') event_types = Event.MEMBERS_EVENTS_MASK s = Subscription(user=request.user, country=country, region=region, event_types=event_types, free=free) s.put() Message(user=request.user, message=ugettext("Subscription created")).put() return HttpResponseRedirect( reverse("events.views.view_event_list", kwargs={"subscription_id": s.key().id()}) ) return HttpResponseRedirect(reverse("events.views.view_event_list"))
def find(request): if request.method == 'GET': return HttpResponse('Error') if 'username' not in request.POST: return HttpResponse('Error') name = request.POST['username'] if is_none(name): name = strings.DEFAULT_USERNAME user = User(name) recent_tracks = user.get_recent_tracks() if is_none(recent_tracks): return HttpResponse('Error') tracks_by_date = group_tracks_by_date(recent_tracks) if is_none(tracks_by_date): return HttpResponse('Error') countries_and_top_songs = Country.get_countries_and_top_songs() song_data = [] for date in tracks_by_date: songs_listened = tracks_by_date[date] country_object = match_songs_with_country(songs_listened, countries_and_top_songs) song_data.append({'date':date, 'country':country_object['country'], 'match_rate':country_object['match_rate']}) return render(request, 'results.html', {'data':json.dumps(song_data)})
def save(self): obj = super(_EventForm, self).save() # check if this country exists and create if necessary country_raw = self.cleaned_data['country'] # assuming 'country name [SHORT]' format of the name result = re.match('(.*)\[(.*)\]', country_raw) try: country_long = result.group(1).strip() country_short = result.group(2).strip() except (IndexError, AttributeError): country_long = '' country_short = country_raw country = Country.get_or_insert( country_short, long_name = country_long ) obj.country = country # check region region_raw = self.cleaned_data['region'] if region_raw != '': result = re.match('(.*)\[(.*)\]', region_raw) try: region_long = result.group(1).strip() region_short = result.group(2).strip() except (IndexError, AttributeError): region_long = region_raw region_short = region_raw region = Region.get_or_insert( region_short, long_name = region_long, country=country ) obj.region = region else: obj.region = None return obj
def getCountries(self): query = Country.query().order(Country.name) countries = query.fetch() return countries
def onGet(self, countryNameKey): self._country = Country.get_by_id(self.helper.getNormalisedCountryName(countryNameKey)) if self._country is None: return self._areas = [y for y in Area.query(ancestor=self._country.key).fetch()]
from models import Country, Grape, WineType, Subregion cts = {"AD":"Andorra","AE":"United Arab Emirates","AF":"Afghanistan","AG":"Antigua and Barbuda","AI":"Anguilla","AL":"Albania","AM":"Armenia","AN":"Netherlands Antilles","AO":"Angola","AQ":"Antarctica","AR":"Argentina","AS":"American Samoa","AT":"Austria","AU":"Australia","AW":"Aruba","AX":"\u00c5land Islands","AZ":"Azerbaijan","BA":"Bosnia and Herzegovina","BB":"Barbados","BD":"Bangladesh","BE":"Belgium","BF":"Burkina Faso","BG":"Bulgaria","BH":"Bahrain","BI":"Burundi","BJ":"Benin","BL":"Saint Barth\u00e9lemy","BM":"Bermuda","BN":"Brunei","BO":"Bolivia","BQ":"British Antarctic Territory","BR":"Brazil","BS":"Bahamas","BT":"Bhutan","BV":"Bouvet Island","BW":"Botswana","BY":"Belarus","BZ":"Belize","CA":"Canada","CC":"Cocos [Keeling] Islands","CD":"Congo - Kinshasa","CF":"Central African Republic","CG":"Congo - Brazzaville","CH":"Switzerland","CI":"C\u00f4te d\u2019Ivoire","CK":"Cook Islands","CL":"Chile","CM":"Cameroon","CN":"China","CO":"Colombia","CR":"Costa Rica","CS":"Serbia and Montenegro","CT":"Canton and Enderbury Islands","CU":"Cuba","CV":"Cape Verde","CX":"Christmas Island","CY":"Cyprus","CZ":"Czech Republic","DD":"East Germany","DE":"Germany","DJ":"Djibouti","DK":"Denmark","DM":"Dominica","DO":"Dominican Republic","DZ":"Algeria","EC":"Ecuador","EE":"Estonia","EG":"Egypt","EH":"Western Sahara","ER":"Eritrea","ES":"Spain","ET":"Ethiopia","FI":"Finland","FJ":"Fiji","FK":"Falkland Islands","FM":"Micronesia","FO":"Faroe Islands","FQ":"French Southern and Antarctic Territories","FR":"France","FX":"Metropolitan France","GA":"Gabon","GB":"United Kingdom","GD":"Grenada","GE":"Georgia","GF":"French Guiana","GG":"Guernsey","GH":"Ghana","GI":"Gibraltar","GL":"Greenland","GM":"Gambia","GN":"Guinea","GP":"Guadeloupe","GQ":"Equatorial Guinea","GR":"Greece","GS":"South Georgia and the South Sandwich Islands","GT":"Guatemala","GU":"Guam","GW":"Guinea-Bissau","GY":"Guyana","HK":"Hong Kong SAR China","HM":"Heard Island and McDonald Islands","HN":"Honduras","HR":"Croatia","HT":"Haiti","HU":"Hungary","ID":"Indonesia","IE":"Ireland","IL":"Israel","IM":"Isle of Man","IN":"India","IO":"British Indian Ocean Territory","IQ":"Iraq","IR":"Iran","IS":"Iceland","IT":"Italy","JE":"Jersey","JM":"Jamaica","JO":"Jordan","JP":"Japan","JT":"Johnston Island","KE":"Kenya","KG":"Kyrgyzstan","KH":"Cambodia","KI":"Kiribati","KM":"Comoros","KN":"Saint Kitts and Nevis","KP":"North Korea","KR":"South Korea","KW":"Kuwait","KY":"Cayman Islands","KZ":"Kazakhstan","LA":"Laos","LB":"Lebanon","LC":"Saint Lucia","LI":"Liechtenstein","LK":"Sri Lanka","LR":"Liberia","LS":"Lesotho","LT":"Lithuania","LU":"Luxembourg","LV":"Latvia","LY":"Libya","MA":"Morocco","MC":"Monaco","MD":"Moldova","ME":"Montenegro","MF":"Saint Martin","MG":"Madagascar","MH":"Marshall Islands","MI":"Midway Islands","MK":"Macedonia","ML":"Mali","MM":"Myanmar [Burma]","MN":"Mongolia","MO":"Macau SAR China","MP":"Northern Mariana Islands","MQ":"Martinique","MR":"Mauritania","MS":"Montserrat","MT":"Malta","MU":"Mauritius","MV":"Maldives","MW":"Malawi","MX":"Mexico","MY":"Malaysia","MZ":"Mozambique","NA":"Namibia","NC":"New Caledonia","NE":"Niger","NF":"Norfolk Island","NG":"Nigeria","NI":"Nicaragua","NL":"Netherlands","NO":"Norway","NP":"Nepal","NQ":"Dronning Maud Land","NR":"Nauru","NT":"Neutral Zone","NU":"Niue","NZ":"New Zealand","OM":"Oman","PA":"Panama","PC":"Pacific Islands Trust Territory","PE":"Peru","PF":"French Polynesia","PG":"Papua New Guinea","PH":"Philippines","PK":"Pakistan","PL":"Poland","PM":"Saint Pierre and Miquelon","PN":"Pitcairn Islands","PR":"Puerto Rico","PS":"Palestinian Territories","PT":"Portugal","PU":"U.S. Miscellaneous Pacific Islands","PW":"Palau","PY":"Paraguay","PZ":"Panama Canal Zone","QA":"Qatar","RE":"R\u00e9union","RO":"Romania","RS":"Serbia","RU":"Russia","RW":"Rwanda","SA":"Saudi Arabia","SB":"Solomon Islands","SC":"Seychelles","SD":"Sudan","SE":"Sweden","SG":"Singapore","SH":"Saint Helena","SI":"Slovenia","SJ":"Svalbard and Jan Mayen","SK":"Slovakia","SL":"Sierra Leone","SM":"San Marino","SN":"Senegal","SO":"Somalia","SR":"Suriname","ST":"S\u00e3o Tom\u00e9 and Pr\u00edncipe","SU":"Union of Soviet Socialist Republics","SV":"El Salvador","SY":"Syria","SZ":"Swaziland","TC":"Turks and Caicos Islands","TD":"Chad","TF":"French Southern Territories","TG":"Togo","TH":"Thailand","TJ":"Tajikistan","TK":"Tokelau","TL":"Timor-Leste","TM":"Turkmenistan","TN":"Tunisia","TO":"Tonga","TR":"Turkey","TT":"Trinidad and Tobago","TV":"Tuvalu","TW":"Taiwan","TZ":"Tanzania","UA":"Ukraine","UG":"Uganda","UM":"U.S. Minor Outlying Islands","US":"United States","UY":"Uruguay","UZ":"Uzbekistan","VA":"Vatican City","VC":"Saint Vincent and the Grenadines","VD":"North Vietnam","VE":"Venezuela","VG":"British Virgin Islands","VI":"U.S. Virgin Islands","VN":"Vietnam","VU":"Vanuatu","WF":"Wallis and Futuna","WK":"Wake Island","WS":"Samoa","YD":"People's Democratic Republic of Yemen","YE":"Yemen","YT":"Mayotte","ZA":"South Africa","ZM":"Zambia","ZW":"Zimbabwe","ZZ":"Unknown or Invalid Region"} for item in cts: c = Country(name=cts[item]) c.put() from models import Country, Subregion c = Country.by_name("France") Subregion(name="Lorena",country=c).put() Subregion(name="Bretanha",country=c).put() Subregion(name="Alsassia",country=c).put() from models import WineType WineType(name="Champanhe").put() WineType(name="Espumante").put() WineType(name="Cava").put() from models import Grape Grape(name="Moscatel").put() Grape(name="Cabernet Sauvignon").put() Grape(name="Merlot").put()
def index(request): countries = Country.with_artists(min=3).order_by('?') context = { 'countries': serializers.serialize("json", countries), } return render(request, 'index.html', context)
def generate_events_per_country_list(): result = [] for c in Country.all(): result.append([c.key().name(), c.long_name, c.event_set.count()]) return result