def detail(request, pk, format=None): """Detail page for choice/request.""" choice = get_object_or_404(Choice, pk=pk) if not request.user in [choice.tutee, choice.tutor]: messages.error(request, 'This is not your request') return HttpResponseRedirect(reverse('choices.views.requests')) if request.method == 'POST' and request.user.profile.tutee: date = request.POST.get('date') address = request.POST.get('address') city_name = request.POST.get('city_name') state_name = request.POST.get('state_name') try: month, day, year = date.split('/') except ValueError: date = None if date and address and city_name and state_name: date = datetime(int(year), int(month), int(day)) address = address.lower() city_name = city_name.lower() state_name = state_name.lower() try: state = State.objects.get(name=state_name) except State.DoesNotExist: state = State(name=state_name) state.save() try: city = state.city_set.get(name=city_name) except City.DoesNotExist: city = City(name=city_name, state=state) city.save() choice.address = address choice.city = city choice.state = state if choice.day.value == int(date.strftime('%w')): choice.date = date messages.success(request, 'Tutor has been notified of your date and place') # Create notification for channel with this choice try: channel = Channel.objects.get(choice=choice) channel.create_notification(request.user, 'update') except Channel.DoesNotExist: pass else: messages.error(request, 'Date must be a %s' % choice.day.name.title()) choice.save() if format and format == '.json': data = { 'choice': choice.to_json(), } return HttpResponse(json.dumps(data), mimetype='application/json') d = { 'choice': choice, 'choice_notes': choice.choicenote_set.all().order_by('-created'), 'title': '%s on %s at %s' % (choice.interest.name.title(), choice.day.name.title(), choice.hour.time_string()), } return render(request, 'choices/detail.html', add_csrf(request, d))
def setUp(self): country = Country( population=0 ) country.save() city1 = City( name='city1', name_std='city1....', country=country, location=Point(0, 0, srid=4326), population=0, ) city1.save() self.city2 = City( name='city2', name_std='city2....', country=country, location=Point(100, 100, srid=4326), population=0, ) self.city2.save() self.city3 = City( name='city3', name_std='city3....', country=country, location=Point(1000, -1000, srid=4326), population=0, ) self.city3.save()
class TestCommandAirports(TestCase): def setUp(self): country = Country(population=0) country.save() city1 = City( name='city1', name_std='city1....', country=country, location=Point(0, 0, srid=4326), population=0, ) city1.save() self.city2 = City( name='city2', name_std='city2....', country=country, location=Point(100, 100, srid=4326), population=0, ) self.city2.save() self.city3 = City( name='city3', name_std='city3....', country=country, location=Point(1000, -1000, srid=4326), population=0, ) self.city3.save() def test_get_city(self): city = get_city('test', 1000, -1000) self.assertEqual(city, self.city3) def tearDown(self): pass
def test_create_or_update(self): data = { 'name': 'foo', 'url': 'bar' } City.create_or_update(data) self.assertEqual(1, City.objects.count()) City.create_or_update(data) self.assertEqual(1, City.objects.count())
def test_model_city_duplicate(self): try: a_city = City(name='A') a_city.full_clean() except ValidationError as e: self.assertEqual( {'name': ['Город with this Город already exists.']}, e.message_dict)
def test_model_city_duplicate( self): # функция проверки дублирования назваия городов try: a_city = City(name='A') a_city.full_clean() except ValidationError as e: self.assertEqual( {'name': ['Город with this Город already exists.']}, e.message_dict)
def load_cities(): cs = get_cities() f = open("../list_of_cities.txt") eu = [] for line in f: eu.append(line[1:-3]) for c in cs: if any(c[1] in city for city in eu): add = City(name=c[1],country=c[0],long=0,lat=0) add.save()
def setUp(self): country = Country(name="Empire anarchique du Bachibouzouc", population=12000) country.save() region = Region(name="Province dépendante du Bazar", country=country) region.save() city1 = City(name="Trifouillis les Oies", region=region, country=country, location=Point(42, 127), population=42) city1.save() city2 = City(name="Montcuq", region=region, country=country, location=Point(42, 127), population=127) city2.save() data = { "username": "******", "email": "*****@*****.**", "password": "******" } response = self.client.post(register_url, data, format="json") data = { "username": "******", "password": "******", } response = self.client.post(login_url, data, format="json") token = response.data["auth_token"] self.client.credentials(HTTP_AUTHORIZATION='Token ' + token)
def setUp(self): country = Country(population=0) country.save() city1 = City( name='city1', name_std='city1....', country=country, location=Point(0, 0, srid=4326), population=0, ) city1.save() self.city2 = City( name='city2', name_std='city2....', country=country, location=Point(100, 100, srid=4326), population=0, ) self.city2.save() self.city3 = City( name='city3', name_std='city3....', country=country, location=Point(1000, -1000, srid=4326), population=0, ) self.city3.save()
def test_query_param_city_no_groups(self): City(name="Oslo") request = self.factory.get("/groups/", {"city": "Oslo"}) response = get_response(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data.get("results")), 0)
def run(cls): response = urlopen(cls.url) html = response.read() cities = SiteParser().run(html) for city_data in cities: city = City.create_or_update(city_data) django_rq.enqueue(CityImporter.run, city)
def test_assert_correct_fields(self): """ The serializer should include only the name and search_name fields """ araras = City(code=1, name='Araras', search_name='araras') serializer_data = CitySerializer(araras).data self.assertEqual(5, len(serializer_data)) self.assertEqual('Araras', serializer_data['name']) self.assertEqual('araras', serializer_data['search_name']) self.assertEqual(1, serializer_data['code'])
def test_assert_correct_fields(self): """ The serializer should include only the name and search_name fields """ araras = City(code=1, name="Araras", search_name="araras") serializer_data = CitySerializer(araras).data self.assertEqual(5, len(serializer_data)) self.assertEqual("Araras", serializer_data["name"]) self.assertEqual("araras", serializer_data["search_name"]) self.assertEqual(1, serializer_data["code"])
class TestCommandAirports(TestCase): def setUp(self): country = Country( population=0 ) country.save() city1 = City( name='city1', name_std='city1....', country=country, location=Point(0, 0, srid=4326), population=0, ) city1.save() self.city2 = City( name='city2', name_std='city2....', country=country, location=Point(100, 100, srid=4326), population=0, ) self.city2.save() self.city3 = City( name='city3', name_std='city3....', country=country, location=Point(1000, -1000, srid=4326), population=0, ) self.city3.save() def test_get_city(self): city = get_city('test', 1000, -1000) self.assertEqual(city, self.city3) def tearDown(self): pass
def load_cities(self, city_file): #Emply the City table self.delete_cities() errors = {} errors["data"] = [] errors["trailer"] = [] #Traverse the cities line by line count = 0 try: for line in city_file[:-1]: #Increment count to check against count += 1 city = {} finds = list(re.search('(.{20})(.{20})(.{2})', line).groups()) city["city_label"] = finds[0].strip() city["city_name"] = finds[1].strip() city["state"] = finds[2].strip() if not City.objects.filter(city_label=city["city_label"]): db_city = City(**city) db_city.save() else: error = "City label, {}, is a duplicate".format( city["city_label"]) log.error("error") errors["data"].append(error) except Exception as e: log.error(str(e)) errors["data"].append( "Please make sure your file if properly formatted") errors["trailer"] += self.load_trailer(city_file[-1], count) log.info("Cities Updated") return errors
def load_cities(self, city_file): #Emply the City table self.delete_cities() errors = {} errors["data"] = [] errors["trailer"] = [] #Traverse the cities line by line count = 0 try: for line in city_file[:-1]: #Increment count to check against count += 1 city = {} finds = list(re.search('(.{20})(.{20})(.{2})',line).groups()) city["city_label"] = finds[0].strip() city["city_name"] = finds[1].strip() city["state"] = finds[2].strip() if not City.objects.filter(city_label=city["city_label"]): db_city = City(**city) db_city.save() else: error = "City label, {}, is a duplicate".format(city["city_label"]) log.error("error") errors["data"].append(error) except Exception as e: log.error(str(e)) errors["data"].append("Please make sure your file if properly formatted") errors["trailer"] += self.load_trailer(city_file[-1], count) log.info("Cities Updated") return errors
def echo_server(my_port): sock = socket(AF_INET, SOCK_STREAM) # 소켓 객체를 생성 sock.bind( ('192.168.0.63', my_port)) # 소켓객체에 주소값을 바인딩 시킴 호스트와 포트로 된 튜플값을 인자로 받음 sock.listen(5) # 리스닝 수 = 5 print('server started') while True: # 프로세스가 죽을때 까지 conn, client_addr = sock.accept() # 서버소켓에 클라이언트가 연결되면 클라이언트 소켓, 주소를 반환 print('connected by', client_addr) # 어떤 주소에서 연결되었는지 프린트 try: while True: data = conn.recv(1024) #클라이언트로부터 1024바이트 만큼 데이터를 받아옴 if not data: break # 소켓이 닫힐때 까지 print('server received', data.decode()) r_msg = data.decode() s = r_msg.split() db = sqlite3.connect('temperature.db') cursor = db.cursor() # data type load if (s[0][5:] == 'load'): # 데이터타입이 load 이면 datein = (s[1][5:] + " " + s[2])[:19] # 날짜와 초 단위까지나오게 tmp = s[3][-5:] cursor.execute( "INSERT INTO TMP VALUES(?, ?);", (datein, tmp)) # 데이터 베이스에 값 datein, temperature값 저장 db.commit() msg = "server received\n" conn.send(msg.encode()) City(name=tmp, state=datein).save() db.close() # Exception Handling except OSError as e: print('socket error: ', e) except Exception as e: print('Exception at listening:'.format(e)) else: print('client closed', client_addr) finally: conn.close()
import sqlite3 import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "citysearch_project.settings") django.setup() from cities.models import City conn = sqlite3.connect('temperature.db') c = conn.cursor() for row in c.execute('SELECT * FROM TMP'): City(name=row[0], state=row[1]).save() print(row)
def test_model_city_duplicate(self): try: a_city = City(name='A') a_city.full_clean() except ValidationError as e: self.assertEqual({'name': ['Город с таким Город (один) уже существует.']}, e.message_dict)
def test_model_city_duplicate(self): '''Тестирование при возникновении ошибок при создании дупликата города''' city = City(name='A') with self.assertRaises(ValidationError): city.full_clean()
def get_fallback_city(): return City(timezone=pytz.UTC, name='Ciudad No Identificada', country=Country(name='Pais No Identificado'))
import csv from cities.models import City with open('cities/cities.csv', newline='') as fp: reader = csv.reader(fp, delimiter='\t') header = next(reader) for row in reader: #print(row[1], row[2], row[3].replace(',','')) c = City(name=row[1], country_id=row[2], population=int(row[3].replace(',', ''))) c.save()
def import_city(self): uptodate = self.download_once('city') if uptodate and not self.force: return data = self.get_data('city') self.build_country_index() self.build_region_index() self.logger.info("Importing city data") for item in data: if not self.call_hook('city_pre', item): continue if item['featureCode'] not in city_types: continue city = City() try: city.id = int(item['geonameid']) except: continue city.name = item['name'] city.kind = item['featureCode'] city.name_std = item['asciiName'] city.slug = slugify(city.name_std) city.location = Point(float(item['longitude']), float(item['latitude'])) city.population = int(item['population']) city.timezone = item['timezone'] try: city.elevation = int(item['elevation']) except: pass country_code = item['countryCode'] try: country = self.country_index[country_code] city.country = country except: self.logger.warning( "{0}: {1}: Cannot find country: {2} -- skipping".format( "CITY", city.name, country_code)) continue region_code = item['admin1Code'] try: region = self.region_index[country_code + "." + region_code] city.region = region except: self.logger.warning( "{0}: {1}: Cannot find region: {2} -- skipping".format( country_code, city.name, region_code)) continue subregion_code = item['admin2Code'] try: subregion = self.region_index[country_code + "." + region_code + "." + subregion_code] city.subregion = subregion except: if subregion_code: self.logger.warning( "{0}: {1}: Cannot find subregion: {2} -- skipping". format(country_code, city.name, subregion_code)) pass if not self.call_hook('city_post', city, item): continue city.save() self.logger.debug("Added city: {0}".format(city))
def test_create(self): test_city = City(name='Another City Name') self.assertEquals(test_city.name='Another City Name')
def edit(request, slug, format=None): """Edit user page.""" profile = get_object_or_404(Profile, slug=slug) user = profile.user if request.user != user: return HttpResponseRedirect(reverse('users.views.edit', args=[request.user.profile.slug])) if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=profile) if profile_form.is_valid(): profile = profile_form.save() if request.POST.get('phone'): profile.phone = request.POST.get('phone')[0:10] profile.save() city_name = request.POST.get('city_name') state_name = request.POST.get('state_name') if city_name and state_name: city_name = city_name.lower() state_name = state_name.lower() try: # Check to see if state exists state = State.objects.get(name=state_name) try: # Check to see if city exists in that state city = state.city_set.get(name=city_name) except City.DoesNotExist: # If no city in that state exists, create one in that state city = City(name=city_name, state=state) city.save() except State.DoesNotExist: # If state does not exist, create one state = State(name=state_name) state.save() # Then create a city for that state city = City(name=city_name, state=state) city.save() profile.city = city profile.save() if format and format == '.json': data = { 'user': profile.to_json(), } return HttpResponse(json.dumps(data), mimetype='application/json') messages.success(request, 'Profile updated') return HttpResponseRedirect(reverse('users.views.detail', args=[profile.slug])) days = [] day_ids = [dayfree.day.pk for dayfree in user.dayfree_set.all()] hours_am = [] hours_pm = [] hour_ids = [hourfree.hour.pk for hourfree in user.hourfree_set.all()] if profile.tutor: for day in Day.objects.filter(value__gte=0, value__lte=6): button_class = '' if day.pk in day_ids: button_class = 'selected' days.append((day, button_class)) for hour in Hour.objects.filter(value__gte=0, value__lte=23): button_class = '' if hour.pk in hour_ids: button_class = 'selected' if hour.value >= 0 and hour.value <= 11: hours_am.append((hour, button_class)) elif hour.value >= 12 and hour.value <= 23: hours_pm.append((hour, button_class)) hours_am.sort(key=lambda (x, c): x.value) hours_pm.sort(key=lambda (x, c): x.value) profile_form = ProfileForm(instance=profile) skills = [skill for skill in user.skill_set.all()] # Autocomplete source for city name if profile.city and profile.city.state: state_slug = profile.city.state.name.replace(' ', '-') city_autocomplete_source = reverse('cities.views.city_list', args=[state_slug]) else: city_autocomplete_source = reverse('cities.views.city_list') d = { 'city_autocomplete_source': city_autocomplete_source, 'days': days, 'hours_am': hours_am, 'hours_pm': hours_pm, 'profile_form': profile_form, 'skills': sorted(skills, key=lambda x: x.interest.name), 'title': 'Edit', } return render(request, 'users/edit.html', add_csrf(request, d))
def test_model_city_duplicate(self): '''Testing Cities for doppelgangers''' city = City(name='A') with self.assertRaises(ValidationError): city.full_clean()
def test_model_city_duplicate(self): '''Тестирование возникновения ошибки при создании дубля города''' city = City(name="A") with self.assertRaises(ValidationError): city.full_clean()
def test_model_city_duplicate(self): city = City(name='A') with self.assertRaises(ValidationError): city.full_clean()
def test_modul_city_dublicate(self): # Тестирование возникновения ошибки при создании дубля города city = City(name='A') with self.assertRaises(ValidationError): city.full_clean()
def import_city(self): uptodate = self.download_once('city') if uptodate and not self.force: return data = self.get_data('city') self.build_country_index() self.build_region_index() self.logger.info("Importing city data") for item in data: if not self.call_hook('city_pre', item): continue if item['featureCode'] not in city_types: continue city = City() try: city.id = int(item['geonameid']) except: continue city.name = item['name'] city.kind = item['featureCode'] city.name_std = item['asciiName'] city.slug = slugify(city.name_std) city.location = Point(float(item['longitude']), float(item['latitude'])) city.population = int(item['population']) city.timezone = item['timezone'] try: city.elevation = int(item['elevation']) except: pass country_code = item['countryCode'] try: country = self.country_index[country_code] city.country = country except: self.logger.warning("{0}: {1}: Cannot find country: {2} -- skipping".format("CITY", city.name, country_code)) continue region_code = item['admin1Code'] try: region = self.region_index[country_code + "." + region_code] city.region = region except: self.logger.warning("{0}: {1}: Cannot find region: {2} -- skipping".format(country_code, city.name, region_code)) continue subregion_code = item['admin2Code'] try: subregion = self.region_index[country_code + "." + region_code + "." + subregion_code] city.subregion = subregion except: if subregion_code: self.logger.warning("{0}: {1}: Cannot find subregion: {2} -- skipping".format(country_code, city.name, subregion_code)) pass if not self.call_hook('city_post', city, item): continue city.save() self.logger.debug("Added city: {0}".format(city))