def index(request, slugs=None): # TODO This function is perfect for a request context processors reused # in gallery pages... parent_slug, current_category = process_category_thread(request, slugs, 'daguerro') categories = Gallery.objects.filter(parent__title_slug=parent_slug) if current_category: photos = current_category.photos.all() if current_category.photos_ordering: photos = photos.custom_order_by(current_category.photos_ordering) else: photos = Photo.objects.orphans() user_groups = request.user.groups.all().values_list("name", flat=True) if 'Editor' in user_groups and len(user_groups) == 1: return HttpResponseRedirect(reverse("daguerro-pages-index")) page_no = int(request.GET.get('page', 1)) paginator = DiggPaginator(photos, django_settings.get('DAG_RESULTS_PER_PAGE')) context = {'categories': categories, 'current_category': current_category, 'photos_page': paginator.page(page_no), 'add_photo_in_root': django_settings.get('DAG_ALLOW_PHOTOS_IN_ROOT_GALLERY'), 'no_image_thumb_url': os.path.join(settings.STATIC_URL, settings.DAG_NO_IMAGE[settings.DAG_GALLERY_THUMB_SIZE_KEY]), 'search_options_form': SearchOptionsForm(), } return render_to_response('daguerro/gallery.html', context, context_instance=RequestContext(request))
def _send_request_emails(subject, message, sender_email, photo_items): try: t = get_template('website/request_photos_mail.html') photos = Photo.objects.filter(pk__in=photo_items) no_image_thumb_url = os.path.join(settings.STATIC_URL, settings.DAG_NO_IMAGE[settings.DAG_GALLERY_THUMB_SIZE_KEY]) body = t.render(Context({'photos': photos, 'sender_email': sender_email, 'message': message, 'no_image_thumb_url': no_image_thumb_url} )) _send_html_mail(EmailMultiAlternatives(subject, body, django_settings.get('DAG_SMTP_HOST'), [django_settings.get('DAG_SMTP_HOST_USER')], headers = {'Reply-To': sender_email}) ) confirmation_body = settings.DAGUERRO_EMAIL_BODY % {'email': django_settings.get("DAG_SALES_EMAIL")} _send_html_mail(EmailMultiAlternatives(django_settings.get('DAG_CONFIRMATION_MAIL_SUBJECT'), confirmation_body, django_settings.get('DAG_SMTP_HOST_USER'), [sender_email],) ) except BadHeaderError: return HttpResponse('Invalid header found.')
def createPayment(order, amount, transaction_id, urls): data = { "orderNumber": transaction_id, "currency": "EUR", "locale": "fi_FI", "urlSet": urls, "price": str(order.order_total) } """ VAT = getattr(settings, 'SHOP_VAT', Decimal('0.24')) for o in order.items.all(): data['orderDetails']['products'].append( { "title": o.product_name, "code": str(o.product.id), "amount": str(o.quantity), "price": str((o.line_total*(1+VAT)).quantize(Decimal('0.01'))), "vat": str(VAT*100), "discount": "0.00", "type": "1" } ) """ AUTH_HELP = (getattr(settings, 'MERCHANT_ID', django_settings.get('merchant_id', default=None)), getattr(settings, 'MERCHANT_PASS', django_settings.get('merchant_pass', default=None))) r = requests.post(SERVICE_URL, headers=headers, auth=AUTH_HELP, data=json.dumps(data)) r.raise_for_status() return r.json()['url']
def gallery(request, slugs=None): parent_slug, current_gallery = process_category_thread(request, slugs) no_image_thumb_url = os.path.join(settings.STATIC_URL, settings.DAG_NO_IMAGE[settings.DAG_GALLERY_THUMB_SIZE_KEY]) # TODO Find a better way to do this (parent by default for a category, i.e. root) if current_gallery: children_galleries = current_gallery.get_children().filter(is_public=True) brother_galleries = current_gallery.get_siblings(include_self=True).filter(is_public=True) photos = current_gallery.photos.public() if current_gallery.photos_ordering: photos = photos.custom_order_by(current_gallery.photos_ordering) else: brother_galleries = None children_galleries = None photos = Photo.objects.public().orphans() page_no = int(request.GET.get('page', 1)) paginator = DiggPaginator(photos, django_settings.get('DAG_RESULTS_PER_PAGE')) template = 'website/gallery.html' if slugs else 'website/index.html' return render_to_response(template, {'gallery': current_gallery, 'brother_galleries': brother_galleries, 'children_galleries': children_galleries, 'search_options_form': SearchOptionsForm(), 'no_image_thumb_url': no_image_thumb_url, 'photos_page': paginator.page(page_no), }, context_instance=RequestContext(request) )
def page(request, action, id=None): if action == 'edit': current_action_title = _("Edit Page") page = get_object_or_404(DaguerroFlatPage, pk=id) elif action == 'add': current_action_title = _("Add Page") page = DaguerroFlatPage(registration_required=True) request.breadcrumbs(( (_("Pages"), reverse("daguerro-pages-index")), (current_action_title, None), )) if request.method == 'POST': form = FlatPageForm(request.POST, instance=page) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("daguerro-pages-index")) else: form = FlatPageForm(instance=page, initial={ 'registration_required': not django_settings.get('DAG_PUBLISH_BY_DEFAULT', default=True) }) return render_to_response('daguerro/page_form.html', {'form': form, 'current_action_title': current_action_title, 'current_action': action, }, context_instance=RequestContext(request))
def calcAuthCode(order_number, timestamp, paid, method): auth = order_number + "|" + timestamp if paid: auth += "|" + paid if method: auth += "|" + method auth += "|" + getattr(settings, 'MERCHANT_PASS', django_settings.get('merchant_pass', default=None)) return hashlib.md5(auth).hexdigest()
def get_billing_and_shipping_selection_form(self): form = super(NoShippingAddressCheckoutSelectionView, self).get_billing_and_shipping_selection_form() form.fields['shipping_method'].widget.attrs['class'] = "hidden" form.fields['shipping_method'].label = "" choices = self.get_billing_backends_choices() tpl = [] for c in choices: if c[0] == 'paytrail-payment' \ and django_settings.get('merchant_id') != "": tpl.append(c) #and django_settings.exists['payment_account_number']\ if c[0] == 'advance-payment' \ and django_settings.get('payment_account_number') != "": tpl.append(c) form.fields['payment_method'] = forms.ChoiceField( choices=tpl, label=_('Payment method')) form.helper = DefaultHelper() return form
def get_context_data(self, member_id): ctx = super().get_context_data() member = get_object_or_404(Member, token=member_id) ctx["season"] = Season.objects.current_season() ctx["member"] = member transactions = Transaction.objects.filter(owner=member) saldo = transactions.aggregate(Sum('amount'))['amount__sum'] # Limit transactions to only show the latest ctx["transactions"] = [] sld = 0 if saldo != None and saldo < 0: for tr in list(transactions.order_by('created_at')): sld = sld + tr.amount if sld >= Decimal('0.00'): ctx["transactions"] = [] if sld != Decimal('0.00'): ctx["transactions"].append(tr) else: season_type = ContentType.objects.get_for_model(ctx["season"]) act_type = ContentType.objects.get_for_model(Activity) acts = Activity.objects.filter(season=ctx["season"]).values_list( 'id', flat=True) ctx["transactions"] = transactions.filter( Q(source_type=season_type.id, source_id=ctx["season"].id) | Q(source_type=act_type.id, source_id__in=acts)) ctx['acts'] = ActivityParticipation.objects.filter_canceable( member=member) for a in ctx['acts']: tr = [x for x in ctx['transactions'] if x.source == a.activity] if tr: tr[0].cancel = CancelForm({ 'actpartid': a.id, 'member': member.token }) ctx["saldo"] = saldo ctx["last_check"] = Transaction.objects.filter( source_type=ContentType.objects.get_for_model( ReferenceNumber)).aggregate( Max('created_at'))['created_at__max'] if saldo and member.reference_numbers: barcode = "4" barcode = barcode + re.sub(r"[A-Za-z\s]+", "", django_settings.get('bank_account')) intpart, decimalpart = int(saldo), int((saldo - int(saldo)) * 100) barcode = barcode + str(1000000 - intpart)[1:] barcode = barcode + str(100 - decimalpart)[1:] barcode = barcode + '000' barcode = barcode + str( member.reference_numbers.first().number).zfill(20) barcode = barcode + timezone.now().strftime("%Y%m%d") ctx['barcode'] = barcode return ctx
def about_us(request): try: about_us_text = django_settings.get('rolunk') except: about_us_text = '' return render( request, 'about_us.html', { 'about_us_text': about_us_text } )
def settings(parser, token): var_name = None try: tag_name, arg = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError( "%r tag requires arguments" % token.contents.split()[0]) m = re.search(r'(.*?) as (\w+)', arg) if m: arg, var_name = m.groups() if not (arg[0] == arg[-1] and arg[0] in ('"', "'")): raise template.TemplateSyntaxError( "%r tag's argument should be in quotes" % tag_name) return ContextNode(django_settings.get(arg[1:-1]), var_name)
def price_list(request): products = Product.objects.all() try: price_list_text = django_settings.get('arlista_szovegalairas') except: price_list_text = '' return render( request, 'price_list.html', { 'products': products, 'price_list_text': price_list_text } )
def test_setting_value_few_times(self): typename = "MyString" django_settings.set(typename, 'test_string', 'data1') self.assert_equal(django_settings.exists('test_string'), True) self.assert_equal(django_settings.get("test_string"), "data1") django_settings.set(typename, 'test_string', 'data2') self.assert_equal(django_settings.data.get("test_string"), "data2") django_settings.set(typename, 'test_string', 'data3') self.assert_equal(django_settings.data.get("test_string"), "data3") django_settings.set(typename, 'test_string', 'data4') self.assert_equal(django_settings.data.get("test_string"), "data4")
def test_setting_value_few_times(self): typename = "MyString" django_settings.set(typename, 'test_string', 'data1') n.assert_equal(django_settings.exists('test_string'), True) n.assert_equal(django_settings.get("test_string"), "data1") django_settings.set(typename, 'test_string', 'data2') n.assert_equal(django_settings.data.get("test_string"), "data2") django_settings.set(typename, 'test_string', 'data3') n.assert_equal(django_settings.data.get("test_string"), "data3") django_settings.set(typename, 'test_string', 'data4') n.assert_equal(django_settings.data.get("test_string"), "data4")
def photo(request, action='add', slugs=None, slug=None): # TODO This function is perfect for a request context processor reused in gallery pages... parent_slug, current_category = process_category_thread(request, slugs, 'daguerro') if slug: current_action_title = _("Edit photography") extra_context = {'current_action': 'edit'} photo = get_object_or_404(Photo, title_slug=slug) initial_galleries = photo.galleries.all().values_list('id', flat=True) else: current_action_title = _("Add photography") extra_context = {'current_action': 'add'} photo = Photo() try: initial_galleries = [Gallery.objects.get(title_slug=parent_slug).id] except Gallery.DoesNotExist: initial_galleries = None request.breadcrumbs(current_action_title, None) if request.method == 'POST': # Force slugify, otherwise I need to fix photologue model or need client-side filling. request.POST['title_slug'] = slugify(request.POST['title']) form = PhotoForm(request.POST, request.FILES, instance=photo) if form.is_valid(): form.save() return redirect_to_gallery(slugs, page=request.GET.get("page", None)) else: form = PhotoForm(instance=photo, initial={ 'galleries': initial_galleries, 'is_public': django_settings.get('DAG_PUBLISH_BY_DEFAULT', default=False) }) return render_to_response('daguerro/photo.html', {'form': form, 'photo': photo, 'extra_context': extra_context, 'current_category': current_category, 'current_action_title': current_action_title, 'current_action': action, 'no_image_thumb_url': os.path.join(settings.STATIC_URL, settings.DAG_NO_IMAGE[settings.DAG_PHOTO_THUMB_SIZE_KEY]), }, context_instance=RequestContext(request))
def gallery(request, action='add', slugs=""): # TODO This function is perfect for a request context processors reused in gallery pages... parent_slug, current_category = process_category_thread(request, slugs, 'daguerro', action) if action == 'edit': current_action_title = _("Edit Gallery") parent_gallery = current_category.parent.id if current_category.parent else None gallery = get_object_or_404(Gallery, title_slug=current_category.title_slug) elif action == 'add': current_action_title = _("Add Gallery") parent_gallery = current_category.id if current_category else None gallery = Gallery() request.breadcrumbs(current_action_title, None) if request.method == 'POST': # Force slugify, otherwise I need to fix photologue model or need client-side filling. request.POST['title_slug'] = slugify(request.POST['title']) form = GalleryForm(request.POST, request.FILES, instance=gallery) if form.is_valid(): form.save() return redirect_to_gallery(slugs, gallery, action) else: form = GalleryForm(instance=gallery, initial={ 'parent': parent_gallery, 'is_public': django_settings.get('DAG_PUBLISH_BY_DEFAULT', default=False) }) return render_to_response('daguerro/gallery_form.html', {'form': form, 'current_category': current_category, 'current_action_title': current_action_title, 'current_action': action, 'no_image_thumb_url': os.path.join(settings.STATIC_URL, settings.DAG_NO_IMAGE['gallery']), 'search_options_form': SearchOptionsForm(), }, context_instance=RequestContext(request))
def get_context_data(self, member_id): ctx = super().get_context_data() member = get_object_or_404(Member, token=member_id) ctx["season"] = Season.objects.current_season() ctx["member"] = member transactions = Transaction.objects.filter(owner=member) saldo = transactions.aggregate(Sum('amount'))['amount__sum'] # Limit transactions to only show the latest ctx["transactions"] = [] sld = 0 for tr in list(transactions.order_by('created_at')): sld = sld + tr.amount if sld >= Decimal('0.00'): ctx["transactions"] = [] if sld != Decimal('0.00'): ctx["transactions"].append(tr) ctx['acts'] = ActivityParticipation.objects.filter_canceable(member=member) for a in ctx['acts']: tr = [x for x in ctx['transactions'] if x.source == a.activity] if tr: tr[0].cancel = CancelForm({ 'actpartid': a.id, 'member': member.token }) ctx["saldo"] = saldo ctx["last_check"] = Transaction.objects.filter( source_type=ContentType.objects.get_for_model(ReferenceNumber)).aggregate( Max('created_at'))['created_at__max'] if saldo and member.reference_numbers: barcode = "4" barcode = barcode + re.sub(r"[A-Za-z\s]+", "", django_settings.get('bank_account')) intpart,decimalpart = int(saldo),int((saldo-int(saldo))*100) barcode = barcode + str(1000000 - intpart)[1:] barcode = barcode + str(100 - decimalpart)[1:] barcode = barcode + '000' barcode = barcode + str(member.reference_numbers.first().number).zfill(20) barcode = barcode + timezone.now().strftime("%Y%m%d") ctx['barcode'] = barcode return ctx
def search_photo(request, format): term = request.GET.get('term', '') photos = Photo.objects.filter(title__icontains=term).order_by("title") if format == 'json': label = '<a><img src="%s"/><p>%s</p></a>' response = HttpResponse(simplejson.dumps([{ 'label': label % (p.get_thumbnail_url(), p.title), 'value': p.title, 'image': p.get_gallery_url(), 'id': p.id} for p in photos])) else: no_image_thumb_url = os.path.join(settings.STATIC_URL, settings.DAG_NO_IMAGE[settings.DAG_GALLERY_THUMB_SIZE_KEY]) num_results = len(photos) response = render_to_response( 'daguerro/gallery.html', { 'categories': {}, 'current_category': None, 'photos': photos, 'term': term, 'num_results': num_results, 'add_photo_in_root': django_settings.get('DAG_ALLOW_PHOTOS_IN_ROOT_GALLERY'), 'no_image_thumb_url': no_image_thumb_url,}, context_instance=RequestContext(request)) return response
def test_get_should_accept_default_param(self): result = django_settings.get('unexisting_value', default="DefaultValue") n.assert_equal(result, "DefaultValue")
def test_should_set_properly(self): n.assert_true(hasattr(django_settings.models, 'MyString')) assert not django_settings.exists('admin_email') django_settings.set('MyString', 'admin_email', '*****@*****.**') assert django_settings.get('admin_email') == '*****@*****.**'
def test_get_should_raise_DoesNotExist_if_theres_no_such_setting(self): self.assert_raises( django_settings.db.Setting.DoesNotExist, lambda: django_settings.get('unexisting_value'), )
def get_context_data(self, **kwargs): context = super(InfoView, self).get_context_data(**kwargs) context['content'] = django_settings.get('shop_info') return context
def post(self, request, *args, **kwargs): if request.POST: form = OrderForm(request.POST) if form.is_valid(): order = form.save() msg = u'E-mail: {}\nКомментарий: {}'.format(order.email, order.comment) send_mail(u'Заполнение формы на сайте art-lounge.ru',msg, '*****@*****.**', [django_settings.get('admin_email'),]) return HttpResponse('OK')
def handle(self, *args, **options): '''For each Team object check their sponsorship page and update their record in the database ''' # connect to the API if not settings.TWITTER_CONSUMER_KEY: raise Exception("There are no Twitter user credentials") api = TwitterAPI( settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, settings.TWITTER_ACCESS_TOKEN_KEY, settings.TWITTER_ACCESS_TOKEN_SECRET ) streams = TwitterStream.objects.all().filter( Q(type=TwitterStream.TWITTER) | Q(type=TwitterStream.TWITTER_LIST) ) for stream in streams: logging.debug("Now working on %s" % stream) # look up the settings in the database to see where # were we the last time we asked for tweets from Twitter since_id = django_settings.get('TWITTER_SINCE_ID_%s' % stream.stream_id, default=1) new_since_id = since_id # make APiI request and check HTTP response r = api.request('lists/statuses', { 'list_id': stream.stream_id, 'include_rts': stream.include_rts, 'since_id': since_id, 'count': 25 } ) if r.status_code != 200: logging.exception("API Call Failed") raise Exception("API Call Failed") # prcoess tweets for tweet in r.get_iterator(): try: try: tweet['retweeted_status'] # this key is only set on retweets # this is a retweet by our accounts # we care about the original tweet maker not ourselves tweet = tweet['retweeted_status'] except KeyError: pass # extract out the media from the entities try: media_url = tweet['entities']['media'][0]['media_url'] except: media_url = None # strip the timezone off the timestamp time_tz = dateutil.parser.parse(tweet['created_at']) time = datetime.datetime(time_tz.year, time_tz.month, time_tz.day, time_tz.hour, time_tz.minute, time_tz.second) if not Tweet.objects.all().filter(tweet_id=tweet['id']).exists(): new_tweet = Tweet.objects.create( tweet_id=tweet['id'], media_url=media_url, message=_html_for_tweet(tweet), time=time, in_reply_to_user_name=tweet['in_reply_to_screen_name'], retweeted=True, user_id=tweet['user']['id'], user_name=tweet['user']['screen_name'], user_photo=tweet['user']['profile_image_url'], team=None ) # update the since id so we don't get the same # tweets mutliple times from twitter if new_tweet.tweet_id < new_since_id: new_since_id = new_tweet.tweet_id logging.debug("Created tweet %i" % new_tweet.tweet_id) else: logging.debug("Tweet %s has already been added to the database" % tweet['id']) new_tweet = None except Exception as e: logging.exception("Failed to process tweet %d" % tweet['id']) # update settings datastore with highest tweet id django_settings.set('Integer', 'TWITTER_SINCE_ID_%s' % stream.stream_id, new_since_id)
from autobahn.twisted.websocket import listenWS from laptimer.server import APIServerFactory from twisted.internet import reactor from twisted.web.server import Site from twisted.web.static import File import django_settings import logging logger = logging.getLogger('laptimer') if __name__ == '__main__': # TODO: Get server and port from settings debug = django_settings.get('debug_app') factory = APIServerFactory('ws://localhost:9000', debug=debug, debugCodePaths=debug) listenWS(factory) webdir = File('.') web = Site(webdir) reactor.run()
def average_speed_per_hour(start, finish, distance): unit = django_settings.get('unit_of_measurement', default=settings.METRIC) if (unit == settings.METRIC): return average_kilometres_per_hour(start, finish, distance) else: return average_miles_per_hour(start, finish, distance)
def test_gpio_app_defaults_to_11(self): self.assertTrue(django_settings.exists('gpio_app')) self.assertEqual(15, django_settings.get('gpio_app'))
class PiTimeGPIO: '''' Class used to work with Raspberry Pi GPIO when triggering sensor events, as well as displaying information relating to application and lap status. ''' # TODO: Decouple gpio pins from django settings, instead add properties # for track and sensor. When these are not initialised, use the laptimer # API to define the track, sensor and gpio pins (in a separate class). # Needs some sort of registration process, since as soon as you have more # than one sensor (RPi), or if the sensor is on separate hardware from the # laptimer server, configuration can't be shared from django settings, so # it probably requires a separate db for the rpi app, and some client code # to talk to the laptimer app server. gpio_app = django_settings.get('gpio_app') '''GPIO pin which indicates whether application server is active.''' gpio_lap = django_settings.get('gpio_lap') '''GPIO pin which indicates whether a lap is currently active.''' gpio_sensor = django_settings.get('gpio_sensor') '''GPIO pin which indicates when a sensor event has been triggered.''' def __init__(self): GPIO.setmode(GPIO.BOARD) GPIO.setup(self.gpio_app, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(self.gpio_lap, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(self.gpio_sensor, GPIO.IN, initial=GPIO.LOW, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.gpio_sensor, GPIO.RISING, callback=_sensor_event, bouncetime=1000) logging.debug( 'GPIO channels configured as app: %i lap: %i sensor: %i' % (self.gpio_app, self.gpio_lap, self.gpio_sensor)) def appOpen(self): logging.debug('App open') _strobe_led(self.gpio_app, GPIO.HIGH) def appClose(self): logging.debug('App close') _strobe_led(self.gpio_app, GPIO.LOW) def cleanup(self): logging.debug('Cleaning up') GPIO.output(self.gpio_app, GPIO.LOW) GPIO.output(self.gpio_lap, GPIO.LOW) GPIO.remove_event_detect(self.gpio_sensor) GPIO.cleanup() def _sensor_event(self, channel): time = timezone.now() logging.debug('Sensor event') _strobe_led(self.gpio_lap, GPIO.LOW) # TODO: trigger event to call api.end_lap def _strobe_led(self, channel, final_state): on = not GPIO.input(channel) strobe_count = 10 # TODO: settings? strobe_sleep = 0.1 # for index in xrange(1, strobe_count): GPIO.output(channel, on) time.sleep(strobe_sleep) on = not on GPIO.output(channel, final_state)
def test_get_should_accept_default_param(self): result = django_settings.get('unexisting_value', default="DefaultValue") self.assert_equal(result, "DefaultValue")
def test_gpio_sensor_defaults_to_18(self): self.assertTrue(django_settings.exists('gpio_sensor')) self.assertEqual(18, django_settings.get('gpio_sensor'))
def test_get_should_raise_DoesNotExist_if_theres_no_such_setting(self): n.assert_raises( django_settings.db.Setting.DoesNotExist, lambda: django_settings.get('unexisting_value'), )
from django.conf import settings import django_settings try: dag_results_per_page = django_settings.get('DAG_RESULTS_PER_PAGE', default=20) settings.HAYSTACK_SEARCH_RESULTS_PER_PAGE = dag_results_per_page except: pass
from autobahn.twisted.websocket import listenWS from laptimer.server import APIServerFactory from twisted.internet import reactor from twisted.web.server import Site from twisted.web.static import File import django_settings import logging logger = logging.getLogger('laptimer') if __name__ == '__main__': # TODO: Get server and port from settings debug=django_settings.get('debug_app') factory = APIServerFactory('ws://localhost:9000', debug=debug, debugCodePaths=debug) listenWS(factory) webdir = File('.') web = Site(webdir) reactor.run()
def test_gpio_lap_defaults_to_13(self): self.assertTrue(django_settings.exists('gpio_lap')) self.assertEqual(16, django_settings.get('gpio_lap'))
def test_unit_of_measurement_defaults_to_metric(self): self.assertTrue(django_settings.exists('unit_of_measurement')) self.assertEqual(settings.METRIC, django_settings.get('unit_of_measurement'))
def test_should_set_properly(self): self.assert_true(hasattr(django_settings.models, 'MyString')) assert not django_settings.exists('admin_email') django_settings.set('MyString', 'admin_email', '*****@*****.**') assert django_settings.get('admin_email') == '*****@*****.**'