def test_country(self): aus = Country('Aus') self.assertEqual('Australia', aus.name) ind = Country('INDIA') self.assertEqual(2, ind.rank) sa = Country('south africa') self.assertEqual('forestgreen', sa.bg_color) self.assertEqual('yellow', sa.color)
def addTestCountries(): country1 = Country(name = "United Kingdom", iso_code = "GBR") country2 = Country(name= "Germany", iso_code = "DEU") country3 = Country(name= "Brazil", iso_code = "BRA") country4 = Country(name= "France", iso_code = "FRA") db.session.add(country1) db.session.add(country2) db.session.add(country3) db.session.add(country4) countries = [country1, country2, country3, country4] db.session.commit() return countries
def setUp(self): super().setUp() db.create_all() self.user = User( id=100, username='******', email='*****@*****.**', password_hash= 'pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', enabled=True) try: entities = [ self.user, Country(id='c1', name='country1'), Currency(code='USD', name='US Dollar', rate=1), Currency(code='RUR', name='Russian rouble', rate=1), Country(id='c2', name='country2'), Shipping(id=1, name='Shipping1'), Shipping(id=2, name='Shipping2'), Shipping(id=3, name='Shipping3'), DHL(), ShippingRate(id=1, shipping_method_id=1, destination='c1', weight=100, rate=100), ShippingRate(id=5, shipping_method_id=2, destination='c1', weight=200, rate=110), ShippingRate(id=2, shipping_method_id=2, destination='c2', weight=100, rate=100), ShippingRate(id=3, shipping_method_id=2, destination='c2', weight=1000, rate=150), ShippingRate(id=4, shipping_method_id=3, destination='c2', weight=2000, rate=160) ] db.session.add_all(entities) db.session.commit() except: db.session.rollback()
def create_server(): '''Создает сервер типа farhub ''' if (API_KEY != request.args.get('api')): return jsonify({'error': 'Wrong api key'}), 400 json_data = request.get_json(force=True) try: srv = Server.objects.get(hash_id=json_data['hash_id']) srv.delete() except Exception: pass finally: try: coun = Country.objects.get(name=json_data['location']) except: coun = Country(name=json_data['location']) coun.save() try: server_name = Type_Of_Server.objects.get( type_of_server='gtn_farhub') except: server_name = Type_Of_Server(type_of_server='gtn_farhub') server_name.save() server = Server(type_of_server=server_name, address=json_data['server_ip'], location=coun, api_key=json_data['api_key'], data=json_data['data'], description=json_data['description'], hash_id=json_data['hash_id']) server.save() Country.synhro() monitoring_service() return '200 OK'
def addAllCountries(): # pragma: no cover # load csv file countries_file = os.getenv('COUNTRIES_CSV') filepath = os.path.join(os.path.dirname(__file__), countries_file) errors = [] with open(filepath) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: country = Country(name = row[0], iso_code = row[1]) try: db.session.add(country) db.session.flush() db.session.commit() except (SQLAlchemyError, DBAPIError) as err: errors.append(err) db.session.rollback() if len(errors) > 0: print("Errors generated when loading database!") return False return True
def setUp(self): super().setUp() db.create_all() admin_role = Role(name='admin') self.user = User( username='******', email='*****@*****.**', password_hash= 'pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', enabled=True) self.admin = User( username='******', email='*****@*****.**', password_hash= 'pbkdf2:sha256:150000$bwYY0rIO$320d11e791b3a0f1d0742038ceebf879b8182898cbefee7bf0e55b9c9e9e5576', enabled=True, roles=[admin_role]) self.try_add_entities([ self.user, self.admin, admin_role, Currency(code='USD', rate=0.5), Currency(code='RUR', rate=0.5), Country(id='c1', name='country1'), Product(id='0000', name='Test product', price=10, weight=10) ])
def before_request(): """ Updates users last activity """ if current_user.is_authenticated: current_user.last_seen = datetime.utcnow() db.session.commit() g.locale = str(get_locale()) if not Country.query.all(): countries = add_countries() for country in countries: new_country = Country(name=countries[country], code=country) db.session.add(new_country) db.session.commit() if not Subscribe.query.all(): standard_subs = Subscribe(name='Standard', price=10) advanced_subs = Subscribe(name='Advanced', price=11) pro_subs = Subscribe(name='Pro', price=13) db.session.add(standard_subs) db.session.add(advanced_subs) db.session.add(pro_subs) db.session.commit() if current_user.subs_id and current_user.subs_expiration.date() <= date.today(): current_user.subs_id = None current_user.subs_expiration = None db.session.commit() posts_from_world_news()
def seed_database(): '''add in Drugs, Countries, and a few markets''' drugs = [] for d in mock_data.drugs: q = Drug.query.filter_by(name=d).first() if q is None: drug = Drug(name=d) drugs.append(drug) db.session.add_all(drugs) db.session.commit() countries = [] for c in mock_data.all_countries: q = Country.query.filter_by(name=c[0]).first() if q is None: country = Country(name=c[0], c2=c[1]) countries.append(country) db.session.add_all(countries) db.session.commit() ms = ["Rechem", "DN1", "DN2"] markets = [] for m in ms: q = Market.query.filter_by(name=m).first() if q is None: market = Market(name=m) markets.append(market) db.session.add_all(markets) db.session.commit() return '', 204
def beenNew(): form = NewBeen() if form.validate_on_submit(): type = 1 blog = form.blog.data startDate = form.startDate.data endDate = form.endDate.data user=current_user.id country = form.country.data country = string.capwords(country) if Country.query.filter_by(name=form.country.data).first() is not None: c = Country.query.filter_by(name=form.country.data).first() else: c = Country(name=form.country.data) db.session.add(c) db.session.commit() city = form.city.data city = string.capwords(city) if City.query.filter_by(name=form.country.data).first() is not None: city1 = City.query.filter_by(name=form.country.data).first() else: city1 = City(name=city, countryID=c.id) db.session.add(city1) db.session.commit() p = Post(type=type, blog=blog, StartDate=startDate, EndDate=endDate, cityID=city1.id, userID=user) db.session.add(p) db.session.commit() flash('Blog Posted') return redirect('/beenList') return render_template('beenNew.html', title='New Been Post', form=form)
def create_user(): if current_user.is_authenticated: return redirect(url_for('index')) form = CreateAccountForm() if form.validate_on_submit(): new_user = form.username.data if User.query.filter_by(username=new_user).first() is not None: flash('User Already Exists') else: flash("New User {} Created!".format(form.username.data)) country = form.country.data country = string.capwords(country) if Country.query.filter_by(name=form.country.data).first() is not None: c =Country.query.filter_by(name=form.country.data).first() else: c = Country(name=form.country.data) db.session.add(c) db.session.commit() u1 = User(username=form.username.data, email=form.email.data, countryID=c.id) u1.set_password(form.password.data) db.session.add(u1) db.session.commit() return redirect('/login') return render_template('create_user.html', title="Create User", form=form)
def create_country(self): region_id = self.create_region().id country = Country(id=randint(0, 100), name=self.faker.country(), region_id=region_id) db.session.add(country) db.session.commit() return country
def test_country_model_fails_iso_length(self): country = Country(name="United Kingdom", iso_code="TOOLONG") try: db.session.add(country) db.session.commit() except DataError as error: db.session.rollback() self.assertTrue('value too long' in str(error))
def upload_players(self): # Index 0 1 2 3 4 5 6 7 8 9 hdr = [ 'name', 'country', 'type', 'tags', 'bid_order', 'matches', 'runs', 'catches', 'balls', 'wickets' ] if self.data_list[0] != hdr: return self.ERROR_INVALID_HEADER Player.delete_all() Bid.delete_all() Player.init_batch() for player_row in self.data_list[1:]: player_row.reverse() player = Player(player_row.pop().strip()) player.country = player_row.pop().strip() country = Country(player.country) player.rank = country.rank player.color = country.color player.bg_color = country.bg_color player.country_code = country.code player.type = player_row.pop().strip() tags = [ tag.strip().lower() for tag in player_row.pop().split(';') if len(tag) > 0 ] tags.append(player.country.lower()) tags.append(player.country_code.lower()) if player.type.lower() not in tags: tags.append(player.type.lower()) player.tags = tags try: player.bid_order = int(player_row.pop()) except ValueError: pass try: player.matches = int(player_row.pop()) except ValueError: pass try: player.runs = int(player_row.pop()) except ValueError: pass try: player.catches = int(player_row.pop()) except ValueError: pass try: player.balls = int(player_row.pop()) except ValueError: pass try: player.wickets = int(player_row.pop()) except ValueError: pass player.update_batch() Player.commit_batch() Game.init_game() return self.SUCCESS
def save_country_from_row(review_row): country = Country() country.country_name = review_row[0] country.country_code = review_row[1] country.iso_codes = review_row[2] country.population = review_row[3] country.area = review_row[4] country.gdp = review_row[5] country.save()
def scrap_countries(): data = Crawler.get_countries('http://wildstat.com/p/20') for item in data: country = Country.query.filter_by(country_id=data[item]).first() if country is None: country = Country(country_id=data[item], name=item) db.session.add(country) db.session.commit() return 'ok'
def addcountry(): form = CountryForm() if form.validate_on_submit(): country=Country(country=form.country.data) db.session.add(country) db.session.commit() flash(_('Added')) return redirect(url_for('main.database_index')) return render_template('edit_database/addcountry.html', form=form)
def create_country(db: SQLAlchemy, data: list): for name in data: country = Country.query.filter_by(name=name).first() if country is None: country = Country(name=name) db.session.add(country) yield country
def countries(self): data = json.loads(open("section_a_locations.json").read()) country_names = set( [data[i].get('country') for i in range(0, len(data))]) country_names.remove(None) print(country_names) for c in country_names: db.session.add(Country(name=c)) db.session.commit()
def backend(request): context = {} context['ajout'] = False if request.method == 'POST': pays = request.POST.get("pays", "") newPays = Country(name=pays, date=timezone.now()) newPays.save() context['ajout'] = True return render(request, 'backend.html', context)
def add(): for data in l: country = Country(name=data['country'], image="default.jpg", infected=data['data'][0], deaths=data['data'][1], recovered=data['data'][2], active=data['data'][3]) db.session.add(country) db.session.commit()
def create_country(id, title, quiet=True): country = Country() country.id = id country.title = title db.session.add(country) db.session.commit() if not quiet: print 'Country created: %s' % country.id
def admin_country(): form = CountryForm() countries = Country.query.all() if request.method=='POST': country = Country( country_name = form.country_name.data ) db.session.add(country) db.session.commit() return redirect(url_for('admin_country')) return loginCheck(render_template('admin/country.html',form=form,countries=countries))
def init_db(): db.drop_all() db.create_all() # Init tag db.session.add(Tag(id=1, name="渣三维")) db.session.add(Tag(id=2, name="转专业")) db.session.add(Tag(id=3, name="高GT")) db.session.add(Tag(id=4, name="高GPA")) # Init project db.session.add(Project(id=1, name="无相关实习经历,有个人项目", value=2)) db.session.add(Project(id=2, name="国内小公司实习", value=2)) db.session.add(Project(id=3, name="国内大公司实习", value=3)) db.session.add(Project(id=4, name="BAT实习", value=4)) db.session.add(Project(id=5, name="外企实习", value=5)) # Init Recommendation db.session.add(Recommendation(id=1, name="无推荐信", value=1)) db.session.add(Recommendation(id=2, name="国内普通推", value=2)) db.session.add(Recommendation(id=3, name="海外普通推", value=3)) db.session.add(Recommendation(id=4, name="国内牛推", value=4)) db.session.add(Recommendation(id=5, name="海外牛推", value=5)) # Init Research db.session.add(Research(id=1, name="无科研经历", value=1)) db.session.add(Research(id=2, name="初步的科研经历", value=2)) db.session.add(Research(id=3, name="大学实验室做过较深入的研究", value=3)) db.session.add(Research(id=4, name="1~3个月的海外研究经历", value=4)) db.session.add(Research(id=5, name="大于3个月的海外研究经历", value=5)) # Init Country db.session.add(Country(id=1, name="美国")) db.session.add(Country(id=2, name="英国")) db.session.add(Country(id=3, name="加拿大")) db.session.add(Country(id=4, name="澳大利亚")) db.session.add(Country(id=5, name="德国")) db.session.add(Country(id=6, name="法国")) db.session.add(Country(id=7, name="香港")) db.session.add(Country(id=8, name="日本")) db.session.add(Country(id=9, name="新加坡")) db.session.commit() # https://api.github.com/search/repositories?q=tetris+language:assembly&sort=stars&order=desc
def deploy(): """ Run deployment tasks. """ from flask.ext.migrate import upgrade # migrate database to latest revision upgrade() init_models = list() init_models.append((Vendor, ["Unknown", "Cisco", "Avaya", "HP"])) system_categories = (SystemCategory, [ "Unknown", "Load Balancer", "Router", "Switch", "Firewall", "Server" ]) init_models.append(system_categories) init_models.append((L2Domain, ["Unknown", "None", "L2D"])) init_models.append( (HardwareType, ["Chassis", "Line Card", "Power Supply", "SFP"])) for model, init_items in init_models: for init_item in init_items: m = model() m.name = init_item db.session.add(m) db.session.commit() m.add_index() software = Software() software.name = "IOS" software.vendor = Vendor.query.filter_by(name="Cisco").first() db.session.add(software) db.session.commit() software.add_index() software = Software() software.name = "NXOS" software.vendor = Vendor.query.filter_by(name="Cisco").first() db.session.add(software) db.session.commit() software.add_index() with open("iso-3166-2.txt", "r") as f: country_codes = f.readlines() country_codes.insert(0, "?? Unknown") for line in country_codes: line = line.split() code = line[0] country = " ".join(line[1::]) c = Country() c.name = country c.code = code db.session.add(c) db.session.commit() c.add_index()
def addcountries(): """Add country list from csv file""" with open('install/iso_3166_2_countries.csv') as csvfile: data = csv.reader(csvfile, delimiter=',') data = list(data) for r in data[2:]: # print(r[1], r[10]) country = Country.query.filter_by(cc=r[10]).first() if country is None: country = Country(cc=r[10], name=r[1]) db.session.add(country) db.session.commit()
def parse(self, **kwargs): worksheet = GoogleSheetsParser.get_worksheet(self, '1Mp9r7CNxVnKip-tLAFpbGp4K_MY2iUrbrBOQBcsKLVE') i = 2 while True: values_list = worksheet.row_values(i) i += 1 if not values_list[0]: break try: country = Country.objects.get( name=values_list[4] ) except ObjectDoesNotExist: country = Country( name=values_list[4] ) self.country_count += 1 country.save() try: region = Region.objects.get( name=values_list[1] ) except ObjectDoesNotExist: region = Region( name=values_list[1], country=country ) self.region_count += 1 region.save() try: city = City.objects.get( name=values_list[0] ) except ObjectDoesNotExist: city = City( name=values_list[0], lat=values_list[2], lon=values_list[3], region=region ) self.city_count += 1 city.save() return [ 'New Countries: ' + str(self.country_count), 'New Regions: ' + str(self.region_count), 'New Cities: ' + str(self.city_count), ]
def create_country(country_name): '''Создает страну''' if (API_KEY != request.args.get('api')): return jsonify({'error': 'Wrong api key'}), 400 if country_name is None or not country_name: return 'Incorrect Query' try: country = Country.objects.get(name=country_name) return 'Объект существует' except Exception: country = Country(name=country_name) country.save() return '200 OK'
def get_or_create_country(country_name): session = db_session() country = session.query(Country).filter_by(name=country_name).first() if not country: new_country = Country(name=country_name) session.add(new_country) session.commit() session.expunge_all() session.close() return new_country session.expunge_all() session.close() return country
def seedData(): country = Country(code="VN", name="Viet Nam") user = ClientAccount.createClientUser( email="*****@*****.**", password="******", firstName="lam", lastName="tran", countryId=1, ) db.session.add(country) db.session.add(user) db.session.commit()
def get_country_info_from_french(self, endpoint, logs=False): soup = self.get_soup(self.config.WIKI_URL + endpoint) title = self.clean_wiki_string( soup.find("h1", { "id": "firstHeading" }).string) infobox_div = soup.find("div", {"class": "infobox_v3"}) for table in infobox_div.findAll("table"): if table.caption and (table.caption.string == "Administration"): administration_table = table if table.caption and (table.caption.string == "Géographie"): geography_table = table if table.caption and (table.caption.string == "Démographie"): demography_table = table # Administration for tr in administration_table.findAll("tr"): if tr.th.a and (tr.th.a.string == "Capitale"): # Delete parasiting coordinates if tr.td.p: tr.td.p.decompose() capital = tr.td.a and tr.td.a.string or tr.td.text capital = self.clean_wiki_string(capital) break # Géographie area = 0 for tr in geography_table.findAll("tr"): if tr.th.string == "Superficie totale": area = self.clean_wiki_number(tr.td.text) break # Démographie for tr in demography_table.findAll("tr"): if tr.th.a and (tr.th.a.string == "Population totale"): text = tr.td.text population = self.clean_wiki_number(text) if "million" in text: population = population * 1000000 break if logs: print(f"{title}: {capital}, {area}, {population}") return Country(name=title, capital=capital, area=area, population=population)