def process_item(self, item, spider): existing_svc = Service.objects.filter( name__iexact=item['package']['service']) if existing_svc: svc = existing_svc[0] else: svc = Service(name=item['package']['service']) svc.save() existing_pkg = Package.objects.filter( name__iexact=item['package']['name'], service=svc) if existing_pkg: pkg = existing_pkg[0] else: pkg = Package(name=item['package']['name'], price=item['package']['price']) pkg.service = svc pkg.save() existing_chn = Channel.objects.filter(name__iexact=item['name']) if existing_chn: chn = existing_chn[0] else: chn = Channel(name=item['name']) chn.save() chn.packages.add(pkg) return item
def test_can_save_service(self): service = Service(name="web design", description="A very long description") service.save() self.assertTrue(Service.save.called) # NOQA self.assertEqual(Service.save.call_count, 1) # NOQA
def create(request): template = 'services/create_service.html' harvests = Harvest.objects.all() products = Product.objects.all() if request.method == 'POST': name = request.POST.get('name', '') cost = request.POST.get('cost', '') date_start = request.POST.get('date_start', '') date_end = request.POST.get('date_end', '') harvest_id = request.POST.get('harvest_id', '') service = Service( name=name, cost=cost, date_start=date_start, date_end=date_end, harvest_id=harvest_id, ) service.save() for product in products: qtd = int(request.POST.get('{}'.format(product.id), 0)) if qtd != 0: used_prod = UsedProducts( product_id=product.id, service=service, quantity=qtd, price=0, ) used_prod.save() return render(request, template, {'harvests': harvests, 'products': products})
def test_cant_save_without_name_data_provided(self): service = Service(description="A very long description") with self.assertRaisesMessage(ValidationError, "Name field cannot be empty"): service.save() self.assertEqual(Service.objects.count(), 0, "No Item should be created in the db")
def test_slug_is_generated_on_save(self): service = Service( name="Prometheus", operator=self.tenant_operator, owner=self.tenant_owner, platform=self.platform, ) self.assertEquals("", service.slug) service.save() self.assertEquals("prometheus", service.slug)
def test_get_brief_description(self): service = Service(name="web design", description=("A very long description A very " "long description A very long description A very long description")) service.save() site = AdminSite() service_admin = ServiceAdmin(Service, site) result = service_admin.get_brief_description(service) self.assertEqual(result, truncatewords(service.description, 20), "should return few characters")
def handle_service(d, keyword_handler): obj = servicesyncher.get(d['id']) if not obj: obj = Service(id=d['id']) obj._changed = True obj._changed |= save_translated_field(obj, 'name', d, 'ontologyword') period_enabled = d['can_add_schoolyear'] clarification_enabled = d['can_add_clarification'] obj._changed |= period_enabled != obj.period_enabled obj._changed |= clarification_enabled != obj.clarification_enabled obj.period_enabled = period_enabled obj.clarification_enabled = clarification_enabled obj._changed = keyword_handler.sync_searchwords(obj, d, obj._changed) if obj._changed: obj.last_modified_time = datetime.now(UTC_TIMEZONE) obj.save() if importer: importer.services_changed = True servicesyncher.mark(obj) return obj
def generate_services(): """Create services unless they already exist. Also assigns allowed data fields for each created service. """ services = [] for service_type in ServiceType: service = Service.objects.filter(service_type=service_type).first() if not service: service = Service(service_type=service_type, title=service_type.name) if service_type in SERVICE_TRANSLATIONS: for language in ["fi", "en", "sv"]: service.set_current_language(language) service.title = SERVICE_TRANSLATIONS[service_type][ "title"][language] service.description = SERVICE_TRANSLATIONS[service_type][ "description"][language] service.save() for field in AllowedDataField.objects.all(): if (field.field_name != "ssn" or service.service_type == ServiceType.BERTH): service.allowed_data_fields.add(field) services.append(service) return services
def get_user_credentials_by_ip(ip_addr: str): try: ip_addr = IPv4Address(ip_addr) except AddressValueError: return None with connection.cursor() as cur: cur.execute("SELECT * FROM find_customer_service_by_ip(%s::inet)", (str(ip_addr), )) res = cur.fetchone() if res is None: return None f_id, f_speed_in, f_speed_out, f_cost, f_calc_type, f_is_admin, f_speed_burst, f_start_time, f_deadline = res if f_id is None: return None srv = Service( pk=f_id, title=None, descr=None, speed_in=f_speed_in, speed_out=f_speed_out, speed_burst=f_speed_burst, cost=f_cost, calc_type=f_calc_type, is_admin=f_is_admin, ) return CustomerService(service=srv, start_time=f_start_time, deadline=f_deadline)
def db_content(db): """ Generate some content to test against """ s = Service(id=1, name='Kirjasto', unit_count=0, last_modified_time=timezone.now()) s.save() u = Unit(id=27586, provider_type=1, origin_last_modified_time=timezone.now(), name='Kallion kirjasto', desc='Kirjasto kallion keskustassa', street_address='Arentikuja 3') u.save() u.services.add(s) uc = UnitConnection(unit=u, name='John Doe', phone='040 123 1234') uc.save() call_command('update_index', interactive=False, verbosity=0) return {'service': s, 'unit': u}
def test_create_service(self): service = Service(name="Test Service", description="Test description service", price = 59) self.assertEqual(service.name, 'Test Service') self.assertEqual(service.description, "Test description service") self.assertEqual(service.price, 59) self.assertFalse(service.main_image)
def service_det(request, page_name): c = get_common_context(request) p = Service.get(page_name, request.LANGUAGE_CODE) if p: c.update({'s': p, 'icon': Service.objects.get(slug=page_name).icon1 }) return render_to_response('sevice_detail.html', c, context_instance=RequestContext(request)) else: raise Http404()
def get_token(cls, user): token = super().get_token(user) token['aud'] = [] user_services = Service.for_user(user) for service in user_services: token['aud'].append(service.identifier) return token
def test_service_is_active_by_default(self): service = Service( name="Prometheus", operator=self.tenant_operator, owner=self.tenant_owner, platform=self.platform, ) self.assertEquals(ServiceStatusChoices.ACTIVE, service.status)
def _handle_service(self, service, keyword_handler): koodi = int( service["koodi"] ) # Cast to int as koodi should always be a stringified integer obj = self.servicesyncher.get(koodi) if not obj: obj = Service(id=koodi, clarification_enabled=False, period_enabled=False) obj._changed = True set_syncher_tku_translated_field(obj, "name", service.get("nimi_kieliversiot")) obj._changed = keyword_handler.sync_searchwords( obj, service, obj._changed) self._save_object(obj) self.servicesyncher.mark(obj)
def offer(request): model = Service post = Service.objects.all() if request.method == 'POST': form = ServiceForm(request.POST, request.FILES) if form.is_valid(): newdoc = Service(user = request.user, title = request.POST['title'], docfile = request.FILES['docfile'], active = request.POST['active'], description = request.POST['description'], duraction = request.POST['duraction'], zip_Code = request.POST['zip_Code'], address = request.POST['address'], expire_date = request.POST['expire_date']) newdoc.save() return redirect('services:offer_detail_service', pk=newdoc.pk) else: form = ServiceForm() # A empty, unbound form # Load documents for the list page return render_to_response( 'services/service.html', {'form': form}, context_instance=RequestContext(request) )
def generate_services(): """Create services unless they already exist. Also assigns allowed data fields for each created service. """ services = [] for service_spec in SERVICES: service_name = service_spec["name"] try: service = Service.objects.get(name=service_name) except Service.DoesNotExist: service = Service(name=service_name, title=service_name) for language, translations in service_spec.get("translations", {}).items(): service.set_current_language(language) for field, text in translations.items(): setattr(service, field, text) service.save() allowed_data_fields = service_spec.get("allowed_data_fields", []) for field in AllowedDataField.objects.filter( field_name__in=allowed_data_fields): service.allowed_data_fields.add(field) services.append(service) return services
def test_create_review(self): service = Service(name="Test Service for review", description="Test description service review", price=29) review = Review(service=service, date=timezone.now(), comments="test review", rating=4) self.assertEqual(review.service.name, "Test Service for review") self.assertEqual(review.comments, "test review") self.assertEqual(review.rating, 4) self.assertFalse(review.approved)
def put(request): result = Result() service_name = request.POST.get('service_name') if not service_name or not re.match("^[A-Za-z]+(_[0-9]+)?$", service_name): result.code = CODE_SYS_TIPS result.message = "service_name format error" return JsonResponse(result.serializer()) service_name = service_name.lower() domain = request.POST.get('domain') port = request.POST.get('port') service_uri = request.POST.get('service_uri') meta = request.POST.get('meta') status = request.POST.get('status') language = request.POST.get('language') language = language if not language else 'EN' # 访问秘钥 secret = encrypt.digest_random() secret = encrypt.digest(secret) try: with transaction.atomic(): service = Service(service_name=service_name, domain=domain, port=port, service_uri=service_uri, meta=meta, secret=secret, status=status) service.save() service_dict = ServiceSerializer(service).data cache.set(create_key(CACHE_SERVICE, service.id), service_dict, timeout=None) cache.set(create_key(CACHE_SERVICE_NAME, service_name), service_dict, timeout=None) result.data = service_dict except Exception as e: log.error(e) result.code = CODE_SYS_DB_ERROR result.message = get_error_message(result.code, language) return JsonResponse(result.serializer())
def db_content(): """ Generate some content to test against """ s = Service(id=1, name='Kirjasto', unit_count=0, last_modified_time=timezone.now()) s.save() o = Organization(id=1, name="Helsingin kaupunki") o.save() u = Unit(id=27586, provider_type=1, organization=o, origin_last_modified_time=timezone.now(), name='Kallion kirjasto', description='Kirjasto kallion keskustassa', street_address='Arentikuja 3') u.save() u.services.add(s) uc = UnitConnection(unit=u, name='John Doe', phone='040 123 1234', type=999) uc.save() return {'service': s, 'unit': u}
def find_customer_service_by_device_credentials(customer_id: int, current_service_id: int): customer_id = safe_int(customer_id) current_service_id = safe_int(current_service_id) # TODO: make tests for it with connection.cursor() as cur: query = "SELECT * FROM " "find_customer_service_by_device_credentials(%s, %s)" cur.execute(query, [customer_id, current_service_id]) res = cur.fetchone() if res is None or res[0] is None: return None ( customer_service_id, service_id, speed_in, speed_out, cost, calc_type, is_admin, speed_burst, start_time, deadline, ) = res srv = Service( pk=service_id, title="", descr="", speed_in=float(speed_in), speed_out=float(speed_out), cost=float(cost), calc_type=calc_type, is_admin=is_admin, speed_burst=speed_burst, ) customer_service = CustomerService(pk=customer_service_id, service=srv, start_time=start_time, deadline=deadline) return customer_service
def test_get_absolute_url(self): service = Service(name="web design", description="A very long description") service.save() self.assertEqual(service.get_absolute_url(), "/services/web-design/")
def test_get_absolute_url_is_not_none(self): service = Service(name="web design", slug="web-design", description="A very long description") self.assertIsNotNone(service.get_absolute_url(), "should return a valid url")
def test_string_representation(self): service = Service(name="web design", description="A very long description") self.assertEqual(str(service), "web design", "should return the name of the service")
def test_cant_save_without_description_provided(self): service = Service(name="web design") with self.assertRaisesMessage(ValidationError, "Description field cannot be empty"): service.save()
def test_slug_is_automatically_generated_on_save_if_not_present(self): service = Service(name="web design", description="A very long description") service.save() self.assertEqual(service.slug, 'web-design')
def person_application(request, template_name='membership/new_person_application.html'): if settings.MAINTENANCE_MESSAGE != None: return redirect('frontpage') chosen_email_forward = None if request.method != 'POST': application_form = PersonApplicationForm() elif request.method == 'POST': application_form = PersonApplicationForm(request.POST) if not application_form.is_valid(): try: chosen_email_forward = application_form.fields[ 'email_forward'].clean( application_form.data['email_forward']) except: pass else: f = application_form.cleaned_data try: # Separate a contact dict from the other fields contact_dict = {} for k, v in f.items(): if k not in [ 'nationality', 'municipality', 'public_memberlist', 'email_forward', 'unix_login', 'extra_info', 'mysql_database', 'postgresql_database', 'login_vhost' ]: contact_dict[k] = v person = Contact(**contact_dict) person.save() membership = Membership( type='P', status='N', person=person, nationality=f['nationality'], municipality=f['municipality'], public_memberlist=f['public_memberlist'], extra_info=f['extra_info']) membership.save() # Service handling services = [] login_alias = Alias(owner=membership, name=f['unix_login'], account=True) login_alias.save() unix_account_service = Service( servicetype=ServiceType.objects.get( servicetype='UNIX account'), alias=login_alias, owner=membership, data=f['unix_login']) unix_account_service.save() services.append(unix_account_service) if f['email_forward'] != 'no' and f['email_forward'] != f[ 'unix_login']: forward_alias = Alias(owner=membership, name=f['email_forward']) forward_alias.save() forward_alias_service = Service( servicetype=ServiceType.objects.get( servicetype='Email alias'), alias=forward_alias, owner=membership, data=f['unix_login']) forward_alias_service.save() services.append(forward_alias_service) if f['mysql_database'] == True: mysql_service = Service( servicetype=ServiceType.objects.get( servicetype='MySQL database'), alias=login_alias, owner=membership, data=f['unix_login'].replace('-', '_')) mysql_service.save() services.append(mysql_service) if f['postgresql_database'] == True: postgresql_service = Service( servicetype=ServiceType.objects.get( servicetype='PostgreSQL database'), alias=login_alias, owner=membership, data=f['unix_login']) postgresql_service.save() services.append(postgresql_service) if f['login_vhost'] == True: login_vhost_service = Service( servicetype=ServiceType.objects.get( servicetype='WWW vhost'), alias=login_alias, owner=membership, data=f['unix_login']) login_vhost_service.save() services.append(login_vhost_service) logger.debug( "Attempting to save with the following services: %s." % ", ".join((str(service) for service in services))) # End of services transaction.commit() logger.info("New application %s from %s:." % (str(person), request.META['REMOTE_ADDR'])) send_mail( _('Membership application received'), render_to_string( 'membership/application_confirmation.txt', { 'membership': membership, 'membership_type': MEMBER_TYPES_DICT[membership.type], 'person': membership.person, 'billing_contact': membership.billing_contact, 'tech_contact': membership.tech_contact, 'ip': request.META['REMOTE_ADDR'], 'services': services }), settings.FROM_EMAIL, [membership.email_to()], fail_silently=False) return redirect('new_person_application_success') except Exception, e: transaction.rollback() logger.critical("%s" % traceback.format_exc()) logger.critical( "Transaction rolled back while trying to process %s." % repr(application_form.cleaned_data)) return redirect('new_application_error')
def post(request): result = Result() service_id = request.POST.get('service_id') if not service_id: result.code = CODE_SYS_TIPS result.message = "service_id can't be empty" return JsonResponse(result.serializer()) service_name = request.POST.get('service_name') if service_name and not re.match("^[A-Za-z]+(_[0-9]+)?$", service_name): result.code = CODE_SYS_TIPS result.message = "service_name format error" return JsonResponse(result.serializer()) if service_name: service_name = service_name.lower() domain = request.POST.get('domain') port = request.POST.get('port') service_uri = request.POST.get('service_uri') meta = request.POST.get('meta') status = request.POST.get('status') service = Service() service.__dict__ = cache.get(create_key(CACHE_SERVICE, service_id)) # 修改标记 update_flag = 0 if service_name and service.service_name != service_name: update_flag += 1 service.service_name = service_name elif domain and service.domain != domain: update_flag += 1 service.domain = domain elif port and service.port != int(port): update_flag += 1 service.port = port elif service_uri and service.service_uri != service_uri: update_flag += 1 service.service_uri = service_uri elif meta and service.meta != meta: update_flag += 1 service.meta = meta elif status and service.status != int(status): update_flag += 1 service.status = status if update_flag == 0: result.code = CODE_SYS_TIPS result.message = "nothing to be updated" return JsonResponse(result.serializer()) language = request.POST.get('language') language = language if not language else 'EN' result = Result() try: with transaction.atomic(): count = Service.objects.filter(id=service_id).update(service_name=service.service_name, domain=service.domain, port=service.port, service_uri=service.service_uri, meta=service.meta, status=service.status) service_dict = ServiceSerializer(service).data cache.set(create_key(CACHE_SERVICE, service.id), service_dict, timeout=None) cache.set(create_key(CACHE_SERVICE_NAME, service_name), service_dict, timeout=None) result.data = count except Exception as e: log.error(e) result.code = CODE_SYS_DB_ERROR result.message = get_error_message(result.code, language) return JsonResponse(result.serializer())
def create_dummy_member(self, i, duplicate_of=None): fname = random_first_name() d = { 'street_address' : 'Testikatu %d'%i, 'postal_code' : '%d' % (i+1000), 'post_office' : 'Paska kaupunni', 'country' : 'Finland', 'phone' : "%09d" % (40123000 + i), 'sms' : "%09d" % (40123000 + i), 'email' : '*****@*****.**' % i, 'homepage' : 'http://www.example.com/%d'%i, 'first_name' : fname, 'given_names' : '%s %s' % (fname, "Kapsi"), 'last_name' : random_last_name(), } if duplicate_of is not None: d['first_name'] = duplicate_of.person.first_name d['last_name'] = duplicate_of.person.last_name person = Contact(**d) person.save() membership = Membership(type='P', status='N', person=person, nationality='Finnish', municipality='Paska kaupunni', extra_info='Hintsunlaisesti semmoisia tietoja.') self.stdout.write(unicode(person)) membership.save() forward_alias = Alias(owner=membership, name=Alias.email_forwards(membership)[0]) forward_alias.save() login_alias = Alias(owner=membership, account=True, name=choice(Alias.unix_logins(membership))) login_alias.save() # Services forward_alias_service = Service(servicetype=ServiceType.objects.get(servicetype='Email alias'), alias=forward_alias, owner=membership, data=forward_alias.name) forward_alias_service.save() unix_account_service = Service(servicetype=ServiceType.objects.get(servicetype='UNIX account'), alias=login_alias, owner=membership, data=login_alias.name) unix_account_service.save() if random() < 0.6: mysql_service = Service(servicetype=ServiceType.objects.get(servicetype='MySQL database'), alias=login_alias, owner=membership, data=login_alias.name.replace('-', '_')) mysql_service.save() if random() < 0.6: postgresql_service = Service(servicetype=ServiceType.objects.get(servicetype='PostgreSQL database'), alias=login_alias, owner=membership, data=login_alias.name) postgresql_service.save() # End of services logger.info("New application %s from %s:." % (str(person), '::1')) return membership
def import_services(self, request, pk=None, *args, **kwargs): obj = self.get_queryset().filter(pk=pk).first() file = request.data['file'] with tempfile.NamedTemporaryFile(suffix='.xlsx') as nf: nf.delete = True with open(nf.name, 'w+') as fp: fp.write(str(file.read())) book = openpyxl.load_workbook(file) sheet = book.get_active_sheet() reversed_field_map = dict([ (d[1], d[0]) for d in serializers_v2.ServiceExcelSerializer.FIELD_MAP.items() ]) headers = [ sheet.cell(row=1, column=c).value for c in range(1, sheet.max_column + 1) ] headers = [ reversed_field_map[h] if h in reversed_field_map else h for h in headers ] rows = [[ sheet.cell(row=r, column=c).value for c in range(1, sheet.max_column + 1) ] for r in range(2, sheet.max_row + 1)] rows_to_use = [dict(zip(headers, r)) for r in rows] errors = {} try: with atomic() as t: for a in rows_to_use: for f in [ "name_{}".format(k) for k, v in settings.LANGUAGES ]: if f not in a or not a[f]: a[f] = '' for f in [ "description_{}".format(k) for k, v in settings.LANGUAGES ]: if f not in a or not a[f]: a[f] = '' for f in [ "address_{}".format(k) for k, v in settings.LANGUAGES ]: if f not in a or not a[f]: a[f] = '' serialized = serializers_v2.ServiceExcelSerializer( data=a, partial=True) if serialized.is_valid(): if 'delete' in a and a['delete']: service = Service.objects.get(id=a['id']) service.delete() continue if a['id']: service = Service.objects.get(id=a['id']) else: region = a['region'] region = GeographicRegion.objects.filter( id=region).first() serialized.validated_data.pop('region', '') service = Service(region=region, provider=obj, **serialized.validated_data) service.save() if 'location' in a and a['location']: location = Point(*reversed([ float(b.strip()) for b in a['location'].split(',') ]), srid=4326) else: location = service.location if 'location' in serialized.validated_data: del serialized.validated_data['location'] Service.objects.filter(id=service.id).update( location=location, **serialized.validated_data) else: errors = serialized.errors raise IntegrityError return Response(None, status=204) except IntegrityError: return Response(errors, status=400)
def organization_application_save(request): try: membership = Membership( type='O', status='N', nationality=request.session['membership']['nationality'], municipality=request.session['membership']['municipality'], extra_info=request.session['membership']['extra_info']) organization = Contact(**request.session['organization']) try: billing_contact = Contact(**request.session['billing_contact']) except: billing_contact = None try: tech_contact = Contact(**request.session['tech_contact']) except: tech_contact = None organization.save() membership.organization = organization if billing_contact: billing_contact.save() membership.billing_contact = billing_contact if tech_contact: tech_contact.save() membership.tech_contact = tech_contact membership.save() services = [] session = request.session login_alias = Alias(owner=membership, name=session['services']['unix_login'], account=True) login_alias.save() unix_account_service = Service( servicetype=ServiceType.objects.get(servicetype='UNIX account'), alias=login_alias, owner=membership, data=session['services']['unix_login']) unix_account_service.save() services.append(unix_account_service) if session['services'].has_key('mysql_database'): mysql_service = Service( servicetype=ServiceType.objects.get( servicetype='MySQL database'), alias=login_alias, owner=membership, data=session['services']['mysql_database'].replace('-', '_')) mysql_service.save() services.append(mysql_service) if session['services'].has_key('postgresql_database'): postgresql_service = Service( servicetype=ServiceType.objects.get( servicetype='PostgreSQL database'), alias=login_alias, owner=membership, data=session['services']['postgresql_database']) postgresql_service.save() services.append(postgresql_service) if session['services'].has_key('login_vhost'): login_vhost_service = Service( servicetype=ServiceType.objects.get(servicetype='WWW vhost'), alias=login_alias, owner=membership, data=session['services']['login_vhost']) login_vhost_service.save() services.append(login_vhost_service) transaction.commit() send_mail( _('Membership application received'), render_to_string( 'membership/application_confirmation.txt', { 'membership': membership, 'membership_type': MEMBER_TYPES_DICT[membership.type], 'organization': membership.organization, 'billing_contact': membership.billing_contact, 'tech_contact': membership.tech_contact, 'ip': request.META['REMOTE_ADDR'], 'services': services }), settings.FROM_EMAIL, [membership.email_to()], fail_silently=False) logger.info("New application %s from %s:." % (unicode(organization), request.META['REMOTE_ADDR'])) request.session.set_expiry( 0) # make this expire when the browser exits for i in ['membership', 'billing_contact', 'tech_contact', 'services']: try: del request.session[i] except: pass return redirect('new_organization_application_success') except Exception, e: transaction.rollback() logger.error("%s" % traceback.format_exc()) logger.error("Transaction rolled back.") return redirect('new_application_error')
def create_services(self): service = Service(name="A new name", description="A new description") service.save() service2 = Service(name="Another new name", description="Another new description") service2.save() service3 = Service(name="Yet Another new name", description="Another new description") service3.save() return service, service2, service3
def test_str(self): # str returns name_en service = Service(name_en="Frederick") self.assertEqual("Frederick", str(service))
def organization_application_save(request): try: membership = Membership(type='O', status='N', nationality=request.session['membership']['nationality'], municipality=request.session['membership']['municipality'], extra_info=request.session['membership']['extra_info']) organization = Contact(**request.session['organization']) try: billing_contact = Contact(**request.session['billing_contact']) except: billing_contact = None try: tech_contact = Contact(**request.session['tech_contact']) except: tech_contact = None organization.save() membership.organization = organization if billing_contact: billing_contact.save() membership.billing_contact = billing_contact if tech_contact: tech_contact.save() membership.tech_contact = tech_contact membership.save() services = [] session = request.session login_alias = Alias(owner=membership, name=session['services']['unix_login'], account=True) login_alias.save() unix_account_service = Service(servicetype=ServiceType.objects.get(servicetype='UNIX account'), alias=login_alias, owner=membership, data=session['services']['unix_login']) unix_account_service.save() services.append(unix_account_service) if session['services'].has_key('mysql_database'): mysql_service = Service(servicetype=ServiceType.objects.get(servicetype='MySQL database'), alias=login_alias, owner=membership, data=session['services']['mysql_database'].replace('-', '_')) mysql_service.save() services.append(mysql_service) if session['services'].has_key('postgresql_database'): postgresql_service = Service(servicetype=ServiceType.objects.get(servicetype='PostgreSQL database'), alias=login_alias, owner=membership, data=session['services']['postgresql_database']) postgresql_service.save() services.append(postgresql_service) if session['services'].has_key('login_vhost'): login_vhost_service = Service(servicetype=ServiceType.objects.get(servicetype='WWW vhost'), alias=login_alias, owner=membership, data=session['services']['login_vhost']) login_vhost_service.save() services.append(login_vhost_service) transaction.commit() send_mail(_('Membership application received'), render_to_string('membership/application_confirmation.txt', { 'membership': membership, 'membership_type': MEMBER_TYPES_DICT[membership.type], 'organization': membership.organization, 'billing_contact': membership.billing_contact, 'tech_contact': membership.tech_contact, 'ip': request.META['REMOTE_ADDR'], 'services': services}), settings.FROM_EMAIL, [membership.email_to()], fail_silently=False) logger.info("New application %s from %s:." % (unicode(organization), request.META['REMOTE_ADDR'])) request.session.set_expiry(0) # make this expire when the browser exits for i in ['membership', 'billing_contact', 'tech_contact', 'services']: try: del request.session[i] except: pass return redirect('new_organization_application_success') except Exception, e: transaction.rollback() logger.error("%s" % traceback.format_exc()) logger.error("Transaction rolled back.") return redirect('new_application_error')
def person_application(request, template_name='membership/new_person_application.html'): if settings.MAINTENANCE_MESSAGE != None: return redirect('frontpage') chosen_email_forward = None if request.method != 'POST': application_form = PersonApplicationForm() elif request.method == 'POST': application_form = PersonApplicationForm(request.POST) if not application_form.is_valid(): try: chosen_email_forward = application_form.fields['email_forward'].clean(application_form.data['email_forward']) except: pass else: f = application_form.cleaned_data try: # Separate a contact dict from the other fields contact_dict = {} for k, v in f.items(): if k not in ['nationality', 'municipality', 'public_memberlist', 'email_forward', 'unix_login', 'extra_info', 'mysql_database', 'postgresql_database', 'login_vhost']: contact_dict[k] = v person = Contact(**contact_dict) person.save() membership = Membership(type='P', status='N', person=person, nationality=f['nationality'], municipality=f['municipality'], public_memberlist=f['public_memberlist'], extra_info=f['extra_info']) membership.save() # Service handling services = [] login_alias = Alias(owner=membership, name=f['unix_login'], account=True) login_alias.save() unix_account_service = Service(servicetype=ServiceType.objects.get(servicetype='UNIX account'), alias=login_alias, owner=membership, data=f['unix_login']) unix_account_service.save() services.append(unix_account_service) if f['email_forward'] != 'no' and f['email_forward'] != f['unix_login']: forward_alias = Alias(owner=membership, name=f['email_forward']) forward_alias.save() forward_alias_service = Service(servicetype=ServiceType.objects.get(servicetype='Email alias'), alias=forward_alias, owner=membership, data=f['unix_login']) forward_alias_service.save() services.append(forward_alias_service) if f['mysql_database'] == True: mysql_service = Service(servicetype=ServiceType.objects.get(servicetype='MySQL database'), alias=login_alias, owner=membership, data=f['unix_login'].replace('-', '_')) mysql_service.save() services.append(mysql_service) if f['postgresql_database'] == True: postgresql_service = Service(servicetype=ServiceType.objects.get(servicetype='PostgreSQL database'), alias=login_alias, owner=membership, data=f['unix_login']) postgresql_service.save() services.append(postgresql_service) if f['login_vhost'] == True: login_vhost_service = Service(servicetype=ServiceType.objects.get(servicetype='WWW vhost'), alias=login_alias, owner=membership, data=f['unix_login']) login_vhost_service.save() services.append(login_vhost_service) logger.debug("Attempting to save with the following services: %s." % ", ".join((str(service) for service in services))) # End of services transaction.commit() logger.info("New application %s from %s:." % (str(person), request.META['REMOTE_ADDR'])) send_mail(_('Membership application received'), render_to_string('membership/application_confirmation.txt', { 'membership': membership, 'membership_type': MEMBER_TYPES_DICT[membership.type], 'person': membership.person, 'billing_contact': membership.billing_contact, 'tech_contact': membership.tech_contact, 'ip': request.META['REMOTE_ADDR'], 'services': services}), settings.FROM_EMAIL, [membership.email_to()], fail_silently=False) return redirect('new_person_application_success') except Exception, e: transaction.rollback() logger.critical("%s" % traceback.format_exc()) logger.critical("Transaction rolled back while trying to process %s." % repr(application_form.cleaned_data)) return redirect('new_application_error')
def create_dummy_member(self, i, duplicate_of=None): fname = random_first_name() d = { "street_address": "Testikatu %d" % i, "postal_code": "%d" % (i + 1000), "post_office": "Paska kaupunni", "country": "Finland", "phone": "%09d" % (40123000 + i), "sms": "%09d" % (40123000 + i), "email": "*****@*****.**" % i, "homepage": "http://www.example.com/%d" % i, "first_name": fname, "given_names": "%s %s" % (fname, "Kapsi"), "last_name": random_last_name(), } if duplicate_of is not None: d["first_name"] = duplicate_of.person.first_name d["last_name"] = duplicate_of.person.last_name person = Contact(**d) person.save() if random() < 0.2: public_memberlist = True else: public_memberlist = False membership = Membership( type="P", status="N", person=person, nationality="Finnish", municipality="Paska kaupunni", public_memberlist=public_memberlist, extra_info="Hintsunlaisesti semmoisia tietoja.", ) self.stdout.write(unicode(person)) membership.save() forward_alias = Alias(owner=membership, name=Alias.email_forwards(membership)[0]) forward_alias.save() login_alias = Alias(owner=membership, account=True, name=choice(Alias.unix_logins(membership))) login_alias.save() # Services forward_alias_service = Service( servicetype=ServiceType.objects.get(servicetype="Email alias"), alias=forward_alias, owner=membership, data=forward_alias.name, ) forward_alias_service.save() unix_account_service = Service( servicetype=ServiceType.objects.get(servicetype="UNIX account"), alias=login_alias, owner=membership, data=login_alias.name, ) unix_account_service.save() if random() < 0.6: mysql_service = Service( servicetype=ServiceType.objects.get(servicetype="MySQL database"), alias=login_alias, owner=membership, data=login_alias.name.replace("-", "_"), ) mysql_service.save() if random() < 0.6: postgresql_service = Service( servicetype=ServiceType.objects.get(servicetype="PostgreSQL database"), alias=login_alias, owner=membership, data=login_alias.name, ) postgresql_service.save() # End of services logger.info("New application %s from %s:." % (str(person), "::1")) return membership