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 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 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 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 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 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 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 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 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 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 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 load_countries(): property_list = ('name', 'tld', 'abbr' 'phone', 'curr_code', 'curr_name') countries = dict() with open('./data/countries/country-by-abbreviation.json') as json_file: for line in yaml.safe_load(json_file): country = dict([('name', line['country']), ('abbr', line['abbreviation'])]) countries[line['country']] = country with open('./data/countries/country-by-domain-tld.json') as json_file: for line in yaml.safe_load(json_file): if line['country'] in countries: country = countries[line['country']] if not line['tld'] is None: country['tld'] = line['tld'][1:] with open('./data/countries/country-by-currency-code.json') as json_file: for line in yaml.safe_load(json_file): if line['country'] in countries: country = countries[line['country']] if not line['currency_code'] is None: country['curr_code'] = line['currency_code'] with open('./data/countries/country-by-currency-name.json') as json_file: for line in yaml.safe_load(json_file): if line['country'] in countries: country = countries[line['country']] if not line['currency_name'] is None: country['curr_name'] = line['currency_name'] with open('./data/countries/country-by-calling-code.json') as json_file: for line in yaml.safe_load(json_file): if line['country'] in countries: country = countries[line['country']] if not line['calling_code'] is None: country['phone'] = line['calling_code'] start_db() for k, v in countries.items(): country = Country(name=v['name']) if 'tld' in v: country.tld = v['tld'] if 'abbr' in v: country.abbr = v['abbr'] if 'phone' in v: country.phone = v['phone'] country.save() stop_db() print(json.dumps(countries, indent=4, sort_keys=True))
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 add_country(request): name = request.GET['name'] population = request.GET['population'] if not population.isdigit(): print 'Error: Population ', population, ' is not an int' return HttpResponse(content_type="application/json", status_code=406) # Create the area area = Country(name=name, population=int(population)) if dao.save_area(area) is False: return HttpResponse(content_type="application/json", status_code=406) return HttpResponse(content_type="application/json", status_code=200)
def newCountry(): """Create a new country""" # The user must be logged in to create a country # but the user_id is not stored like it is for a wine if request.method == 'POST': newCountry = Country(name=request.form['name']) session = DBSession() session.add(newCountry) session.commit() session.close() return redirect(url_for('showCatalog')) else: return render_template('newCountry.html')
def DELETE(self, name): """Deletes country using either country name or country code.""" country_name = web.input().get('country_name') country_code = web.input().get('country_code') try: if country_name: assert country_name and not country_code elif country_code: assert country_code and not country_name except AssertionError as error: logger.debug(error) raise Error(BADPARAMS) try: if country_name: r = Country.get_from_name(country_name)[0] country = Country(r['country_code']) country.delete_name(country_name) elif country_code: country = Country(country_code) country.delete() except: raise Error(NOTFOUND, msg="The country does not exist.") return [country.__dict__]
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 add_static_data(self): with app.app_context(): category1 = Category('Test Category 1') category2 = Category('Test Category 2') db.session.add(category1) db.session.add(category2) course1 = Course('Test Course 1') course2 = Course('Test Course 2') db.session.add(course1) db.session.add(course2) cuisine1 = Cuisine('Test Cuisine 1') cuisine2 = Cuisine('Test Cuisine 2') db.session.add(cuisine1) db.session.add(cuisine2) country1 = Country('Test Country 1') country2 = Country('Test Country 2') db.session.add(country1) db.session.add(country2) author_country1 = Country.query.filter_by( country_name='Test Country 1').first() author1 = Author('Test Author 1') author_country1.authors.append(author1) db.session.add(author_country1) author_country2 = Country.query.filter_by( country_name='Test Country 2').first() author2 = Author('Test Author 2') author_country2.authors.append(author2) db.session.add(author_country2) measurement1 = Measurement('Test Measurement 1') measurement2 = Measurement('Test Measurement 2') db.session.add(measurement1) db.session.add(measurement2) ingredient1 = Ingredient('Test Ingredient 1') ingredient2 = Ingredient('Test Ingredient 2') db.session.add(ingredient1) db.session.add(ingredient2) db.session.commit()
def addcountry(): ''' Handles new country after logging in ''' if 'google_token' not in session: message = 'Login to access the resource' flash(message) return redirect(url_for('index')) user_info_oauth = google.get('userinfo') # returns a oauthlib object userdata = user_info_oauth.data # we just need the data from me object curr_user_id = getUserId(userdata["email"]) if request.method == 'POST': newcountry = Country(name=request.form['countrySelect'], user_id=curr_user_id) checkcountry = dbsession.query(Country).filter_by( user_id=curr_user_id).all() exists = False for item in checkcountry: if newcountry.name == item.name: exists = True if not exists: dbsession.add(newcountry) dbsession.commit() message = '' message += newcountry.name message += ' added to your country list!' flash(message) else: message = 'This country is already in your list!' flash(message) return redirect(url_for('addcountry')) else: allcountrycoors = [] allcountrynames = [] listcountries = dbsession.query(Country).filter_by( user_id=curr_user_id).all() listlen = len(listcountries) for i in range(listlen): g = geocoder.google(listcountries[i].name, key=geocoder_key) countrycoors = g.latlng countryname = listcountries[i].name allcountrycoors.append(countrycoors) allcountrynames.append(countryname) # print(allcountrynames, file=sys.stderr) return render_template('addcountry.html', coors=allcountrycoors, allcountries=allcountrynames, countries=listcountries)
def post(self): status_code = 200 parser = reqparse.RequestParser() parser.add_argument("code") parser.add_argument("name") args = parser.parse_args() try: country = Country(code=args['code'], name=args['name']) db.session.add(country) db.session.commit() result = {'country': country.name} except: status_code = 404 result = {'message': 'There is some error'} return result, status_code
def write_csv_data_to_database(filename): from models import engine, db_session, Country with open(filename, 'r') as readfile: reader = csv.reader(readfile) 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]))) db_session.add(country) except ValueError: country = Country(name=row[0], total_cases=0.0, total_deaths=int(row[2])) db_session.add(country) db_session.commit()
def get_list_of_countries(self): region_api = RegionApi() regions = region_api.list() countries = [] for region in regions: country_api = CountryApi() any_country = country_api.get_one_by_region(region) country = Country(name=any_country['name'], alpha2code=any_country['alpha2Code'], alpha3code=any_country['alpha3Code'], capital=any_country['capital'], region=any_country['region'], language=any_country['languages'], time=any_country['time']) countries.append(country.__dict__) return countries
def country(): wb = xlrd.open_workbook("/Users/liyin/Downloads/1.xlsx") wb.sheet_names() sh = wb.sheet_by_name(u'Sheet1') count = 0 for rownum in range(sh.nrows): country = Country( sh.row_values(rownum)[0], sh.row_values(rownum)[1], sh.row_values(rownum)[2]) db.session.add(country) db.session.commit() db.create_all() count += 1 print count
def load_countries(): """Load countries from CSV file into database.""" Country.query.delete() with open('static/data/countries.csv', 'rb') as csvfile: next(csvfile) countries_reader = csv.reader(csvfile) for row in countries_reader: code = row[1] name = row[2] country = Country(code=code, name=name) db.session.add(country) db.session.commit()
def handle_country(): body = request.get_json() # if body is None: # raise APIException("You need to specify the request body as a json object", status_code=400) # if 'username' not in body: # raise APIException('You need to specify the username', status_code=400) # if 'email' not in body: # raise APIException('You need to specify the email', status_code=400) country1 = Country(user_id=body['user_id'], latitude=body['latitude'], longitude=body['longitude'], country_value=body['country_value'], country_label=body['country_label']) db.session.add(country1) db.session.commit() return "ok", 200