Python django.http.HttpResponse() Examples

The following are code examples for showing how to use django.http.HttpResponse(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-xadmin   Author: MarkHoo   File: editable.py    MIT License 7 votes vote down vote up
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c)) 
Example 2
Project: django-xadmin   Author: MarkHoo   File: editable.py    MIT License 6 votes vote down vote up
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c)) 
Example 3
Project: django-xadmin   Author: MarkHoo   File: editable.py    MIT License 6 votes vote down vote up
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c)) 
Example 4
Project: django-xadmin   Author: MarkHoo   File: importexport.py    MIT License 6 votes vote down vote up
def get_response(self, response, context, *args, **kwargs):
        has_view_perm = self.has_model_perm(self.model, 'view')
        if not has_view_perm:
            raise PermissionDenied

        export_format = self.request.GET.get('file_format')

        if not export_format:
            messages.warning(self.request, _('You must select an export format.'))
        else:
            formats = self.get_export_formats()
            file_format = formats[int(export_format)]()
            queryset = self.get_export_queryset(self.request, context)
            export_data = self.get_export_data(file_format, queryset, request=self.request)
            content_type = file_format.get_content_type()
            # Django 1.7 uses the content_type kwarg instead of mimetype
            try:
                response = HttpResponse(export_data, content_type=content_type)
            except TypeError:
                response = HttpResponse(export_data, mimetype=content_type)
            response['Content-Disposition'] = 'attachment; filename=%s' % (
                self.get_export_filename(file_format),
            )
            post_export.send(sender=None, model=self.model)
            return response 
Example 5
Project: pinax-documents   Author: pinax   File: views.py    MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        if settings.DOCUMENTS_USE_X_ACCEL_REDIRECT:
            response = HttpResponse()
            response["X-Accel-Redirect"] = self.object.file.url
            # delete content-type to allow Gondor to determine the filetype and
            # we definitely don't want Django's crappy default :-)
            del response["content-type"]
        else:
            # Note:
            #
            # The 'django.views.static.py' docstring states:
            #
            #     Views and functions for serving static files. These are only to be used
            #     during development, and SHOULD NOT be used in a production setting.
            #
            response = static.serve(request, self.object.file.name,
                                    document_root=settings.MEDIA_ROOT)
        return response 
Example 6
Project: pinax-documents   Author: pinax   File: test_views.py    MIT License 6 votes vote down vote up
def test_download(self):
        """
        Ensure the requested Document file is served.
        """
        simple_file = SimpleUploadedFile("delicious.txt", self.file_contents)
        document = Document.objects.create(name="Honeycrisp",
                                           author=self.user,
                                           file=simple_file,
                                           )
        document.save()

        with self.login(self.user):
            # Verify `django.views.static.serve` is called to serve up the file.
            # See related note in .views.DocumentDownload.get().
            with mock.patch("django.views.static.serve") as serve:
                serve.return_value = HttpResponse()
                self.get_check_200(self.download_urlname, pk=document.pk)
                self.assertTrue(serve.called) 
Example 7
Project: django-yandex-cash-register   Author: bzzzzzz   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_response(self, params):
        if 'code' not in params:
            params['code'] = 0

        for key in params:
            try:
                params[key] = str(params[key])
            except UnicodeEncodeError:
                pass

        content = getattr(E, '{}Response'.format(self.accepted_action))()
        for key, value in params.items():
            content.attrib[key] = value
        data = etree.tostring(content, xml_declaration=True, encoding='UTF-8',
                              method='xml')
        logger.info('Response: %r', data)
        return HttpResponse(data, content_type='application/xml') 
Example 8
Project: django-config   Author: shinznatkid   File: decorators.py    MIT License 6 votes vote down vote up
def json_response(func):
    """
    A decorator thats takes a view response and turns it
    into json. If a callback is added through GET or POST
    the response is JSONP.
    """
    def decorator(request, *args, **kwargs):
        objects = func(request, *args, **kwargs)
        if isinstance(objects, HttpResponse):
            return objects
        try:
            data = json.dumps(objects)
            if 'callback' in request.GET:
                # a jsonp response!
                data = '%s(%s);' % (request.GET['callback'], data)
                return HttpResponse(data, "text/javascript")
            if 'callback' in request.POST:
                # a jsonp response!
                data = '%s(%s);' % (request.POST['callback'], data)
                return HttpResponse(data, "text/javascript")
        except:
            data = json.dumps(str(objects))
        return HttpResponse(data, "application/json")
    return decorator 
Example 9
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 6 votes vote down vote up
def assets(request, url):
    url = str(url).replace("https://", "https:/").replace("https:/", "https://")  # This is stupid
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(request)
    info = response.info()
    return HttpResponse(response.read(), content_type=info.get_content_type()) 
Example 10
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 6 votes vote down vote up
def get_result(request):
    return HttpResponse(serializers.serialize("json", Result.objects.all().order_by('-score')[0:10]), content_type='application/json') 
Example 11
Project: Servo   Author: fpsw   File: customer.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def filter(request):
    """
    Search for customers by name
    May return JSON for ajax requests
    or a rendered list
    """
    import json
    from django.http import HttpResponse

    if request.method == "GET":
        results = list()
        query = request.GET.get("query")
        customers = Customer.objects.filter(fullname__icontains=query)

        for c in customers:
            results.append(u"%s <%s>" % (c.name, c.email))
            results.append(u"%s <%s>" % (c.name, c.phone))
    else:
        query = request.POST.get("name")
        results = Customer.objects.filter(fullname__icontains=query)
        data = {'results': results, 'id': request.POST['id']}

        return render(request, "customers/search-results.html", data)

    return HttpResponse(json.dumps(results), content_type="application/json") 
Example 12
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render_to_response(self, context, **response_kwargs):
        out = {
            'order': self.object.code,
            'status': self.object.get_status_name(),
            'status_description': self.object.get_status_description(),
        }

        if Configuration.conf('checkin_timeline'):
            timeline = []
            for i in self.object.orderstatus_set.exclude(status=None):
                status = {'badge': i.get_badge()}
                status['status'] = i.status.title
                status['started_at'] = i.started_at.isoformat()
                status['description'] = i.status.description
                timeline.append(status)

            out['timeline'] = timeline

        return HttpResponse(json.dumps(out), content_type='application/json') 
Example 13
Project: Servo   Author: fpsw   File: order.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def download_results(request):
    import csv
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="orders.csv"'

    writer = csv.writer(response)
    header = [
        'CODE',
        'CUSTOMER',
        'CREATED_AT',
        'ASSIGNED_TO',
        'CHECKED_IN',
        'LOCATION'
    ]
    writer.writerow(header)

    for o in request.session['order_queryset']:
        row = [o.code, o.customer, o.created_at,
               o.user, o.checkin_location, o.location]
        coded = [unicode(s).encode('utf-8') for s in row]

        writer.writerow(coded)

    return response 
Example 14
Project: Servo   Author: fpsw   File: note.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def toggle_flag(request, kind, pk, flag):
    """
    Toggles a flag of a note (read/unread, flagged/not, reported/not)
    """
    if kind == 'articles':
        note = get_object_or_404(Article, pk=pk)
        if flag == 'flagged':
            note.toggle_flagged(request.user)
            return HttpResponse(note.get_flagged_title(request.user))
        if flag == 'read':
            note.toggle_read(request.user)
            return HttpResponse(note.get_read_title(request.user))

    field = 'is_%s' % flag
    note = get_object_or_404(Note, pk=pk)
    attr = getattr(note, field)
    setattr(note, field, not attr)
    note.save()

    return HttpResponse(getattr(note, 'get_%s_title' % flag)()) 
Example 15
Project: autolims   Author: scottbecker   File: views.py    MIT License 5 votes vote down vote up
def index(request):
    return HttpResponse("Hello world") 
Example 16
Project: xadmin_bugfix   Author: vip68   File: base.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_response(self, content, response_type='json'):
        if response_type == 'json':
            response = HttpResponse(content_type="application/json; charset=UTF-8")
            response.write(
                json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
            return response
        return HttpResponse(content) 
Example 17
Project: xadmin_bugfix   Author: vip68   File: website.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self, request):
        key = request.POST['key']
        val = request.POST['value']
        us, created = UserSettings.objects.get_or_create(
            user=self.user, key=key)
        us.value = val
        us.save()
        return HttpResponse('') 
Example 18
Project: xadmin_bugfix   Author: vip68   File: actions.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post_response(self, response, *args, **kwargs):
        request = self.admin_view.request
        av = self.admin_view

        # Actions with no confirmation
        if self.actions and 'action' in request.POST:
            action = request.POST['action']

            if action not in self.actions:
                msg = _("Items must be selected in order to perform "
                        "actions on them. No items have been changed.")
                av.message_user(msg)
            else:
                ac, name, description, icon = self.actions[action]
                select_across = request.POST.get('select_across', False) == '1'
                selected = request.POST.getlist(ACTION_CHECKBOX_NAME)

                if not selected and not select_across:
                    # Reminder that something needs to be selected or nothing will happen
                    msg = _("Items must be selected in order to perform "
                            "actions on them. No items have been changed.")
                    av.message_user(msg)
                else:
                    queryset = av.list_queryset._clone()
                    if not select_across:
                        # Perform the action only on the selected objects
                        queryset = av.list_queryset.filter(pk__in=selected)
                    response = self.response_action(ac, queryset)
                    # Actions may return an HttpResponse, which will be used as the
                    # response from the POST. If not, we'll be a good little HTTP
                    # citizen and redirect back to the changelist page.
                    if isinstance(response, HttpResponse):
                        return response
                    else:
                        return HttpResponseRedirect(request.get_full_path())
        return response 
Example 19
Project: xadmin_bugfix   Author: vip68   File: export.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_response(self, response, context, *args, **kwargs):
        file_type = self.request.GET.get('export_type', 'csv')
        charset = 'UTF-8' if file_type == 'xml' or file_type == 'json' else 'gbk'
        response = HttpResponse(
            content_type="%s; charset=%s" % (self.export_mimes[file_type], charset))

        file_name = self.opts.verbose_name.replace(' ', '_')
        response['Content-Disposition'] = ('attachment; filename=%s.%s' % (
            file_name, file_type)).encode('utf-8')

        response.write(getattr(self, 'get_%s_export' % file_type)(context))
        return response

    # View Methods 
Example 20
Project: claxon   Author: vanatteveldt   File: views.py    GNU General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        project = Project.objects.get(pk=self.kwargs['project'])
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

        writer = csv.writer(response)
        writer.writerow(['document_id', 'label', 'gold', 'predict', 'score'])
        for doc, label, accept, predict, score in get_predictions(project):
            writer.writerow([str(doc), label, int(accept), int(predict), score])
        return response 
Example 21
Project: mun   Author: hmlON   File: views.py    MIT License 5 votes vote down vote up
def callback(request):
    body = json.loads(request.body)
    text = body['message']['text'].split(' ')
    token = None
    if len(text) > 1:
        token = text[1]

    bot_key = os.environ.get('TELEGRAM_API_KEY')
    chat_id = body['message']['chat']['id']

    try:
        notification = Notification.objects.get(channel='telegram', connect_token=token)
        notification.channel_id = chat_id
        notification.save()

        text = "Welcome to the MuN"
        send_message_url = f'https://api.telegram.org/bot{bot_key}/sendMessage?chat_id={chat_id}&text={text}'
        requests.post(send_message_url)

        return HttpResponse()
    except Notification.DoesNotExist:
        text = "Sorry, seems like the MuN is too far..."
        send_message_url = f'https://api.telegram.org/bot{bot_key}/sendMessage?chat_id={chat_id}&text={text}'
        requests.post(send_message_url)

        return HttpResponse() 
Example 22
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def render_response(self, content, response_type='json'):
        if response_type == 'json':
            response = HttpResponse(content_type="application/json; charset=UTF-8")
            response.write(
                json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
            return response
        return HttpResponse(content) 
Example 23
Project: django-xadmin   Author: MarkHoo   File: website.py    MIT License 5 votes vote down vote up
def post(self, request):
        key = request.POST['key']
        val = request.POST['value']
        us, created = UserSettings.objects.get_or_create(
            user=self.user, key=key)
        us.value = val
        us.save()
        return HttpResponse('') 
Example 24
Project: django-xadmin   Author: MarkHoo   File: actions.py    MIT License 5 votes vote down vote up
def post_response(self, response, *args, **kwargs):
        request = self.admin_view.request
        av = self.admin_view

        # Actions with no confirmation
        if self.actions and 'action' in request.POST:
            action = request.POST['action']

            if action not in self.actions:
                msg = _("Items must be selected in order to perform "
                        "actions on them. No items have been changed.")
                av.message_user(msg)
            else:
                ac, name, description, icon = self.actions[action]
                select_across = request.POST.get('select_across', False) == '1'
                selected = request.POST.getlist(ACTION_CHECKBOX_NAME)

                if not selected and not select_across:
                    # Reminder that something needs to be selected or nothing will happen
                    msg = _("Items must be selected in order to perform "
                            "actions on them. No items have been changed.")
                    av.message_user(msg)
                else:
                    queryset = av.list_queryset._clone()
                    if not select_across:
                        # Perform the action only on the selected objects
                        queryset = av.list_queryset.filter(pk__in=selected)
                    response = self.response_action(ac, queryset)
                    # Actions may return an HttpResponse, which will be used as the
                    # response from the POST. If not, we'll be a good little HTTP
                    # citizen and redirect back to the changelist page.
                    if isinstance(response, HttpResponse):
                        return response
                    else:
                        return HttpResponseRedirect(request.get_full_path())
        return response 
Example 25
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_response(self, response, context, *args, **kwargs):
        file_type = self.request.GET.get('export_type', 'csv')
        response = HttpResponse(
            content_type="%s; charset=UTF-8" % self.export_mimes[file_type])

        file_name = self.opts.verbose_name.replace(' ', '_')
        response['Content-Disposition'] = ('attachment; filename=%s.%s' % (
            file_name, file_type)).encode('utf-8')

        response.write(getattr(self, 'get_%s_export' % file_type)(context))
        return response

    # View Methods 
Example 26
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def render_response(self, content, response_type='json'):
        if response_type == 'json':
            response = HttpResponse(content_type="application/json; charset=UTF-8")
            response.write(
                json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
            return response
        return HttpResponse(content) 
Example 27
Project: django-xadmin   Author: MarkHoo   File: website.py    MIT License 5 votes vote down vote up
def post(self, request):
        key = request.POST['key']
        val = request.POST['value']
        us, created = UserSettings.objects.get_or_create(
            user=self.user, key=key)
        us.value = val
        us.save()
        return HttpResponse('') 
Example 28
Project: django-xadmin   Author: MarkHoo   File: actions.py    MIT License 5 votes vote down vote up
def post_response(self, response, *args, **kwargs):
        request = self.admin_view.request
        av = self.admin_view

        # Actions with no confirmation
        if self.actions and 'action' in request.POST:
            action = request.POST['action']

            if action not in self.actions:
                msg = _("Items must be selected in order to perform "
                        "actions on them. No items have been changed.")
                av.message_user(msg)
            else:
                ac, name, description, icon = self.actions[action]
                select_across = request.POST.get('select_across', False) == '1'
                selected = request.POST.getlist(ACTION_CHECKBOX_NAME)

                if not selected and not select_across:
                    # Reminder that something needs to be selected or nothing will happen
                    msg = _("Items must be selected in order to perform "
                            "actions on them. No items have been changed.")
                    av.message_user(msg)
                else:
                    queryset = av.list_queryset._clone()
                    if not select_across:
                        # Perform the action only on the selected objects
                        queryset = av.list_queryset.filter(pk__in=selected)
                    response = self.response_action(ac, queryset)
                    # Actions may return an HttpResponse, which will be used as the
                    # response from the POST. If not, we'll be a good little HTTP
                    # citizen and redirect back to the changelist page.
                    if isinstance(response, HttpResponse):
                        return response
                    else:
                        return HttpResponseRedirect(request.get_full_path())
        return response 
Example 29
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_response(self, response, context, *args, **kwargs):
        file_type = self.request.GET.get('export_type', 'csv')
        response = HttpResponse(
            content_type="%s; charset=UTF-8" % self.export_mimes[file_type])

        file_name = self.opts.verbose_name.replace(' ', '_')
        response['Content-Disposition'] = ('attachment; filename=%s.%s' % (
            file_name, file_type)).encode('utf-8')

        response.write(getattr(self, 'get_%s_export' % file_type)(context))
        return response

    # View Methods 
Example 30
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def render_response(self, content, response_type='json'):
        if response_type == 'json':
            response = HttpResponse(content_type="application/json; charset=UTF-8")
            response.write(
                json.dumps(content, cls=JSONEncoder, ensure_ascii=False))
            return response
        return HttpResponse(content) 
Example 31
Project: django-xadmin   Author: MarkHoo   File: website.py    MIT License 5 votes vote down vote up
def post(self, request):
        key = request.POST['key']
        val = request.POST['value']
        us, created = UserSettings.objects.get_or_create(
            user=self.user, key=key)
        us.value = val
        us.save()
        return HttpResponse('') 
Example 32
Project: django-xadmin   Author: MarkHoo   File: actions.py    MIT License 5 votes vote down vote up
def post_response(self, response, *args, **kwargs):
        request = self.admin_view.request
        av = self.admin_view

        # Actions with no confirmation
        if self.actions and 'action' in request.POST:
            action = request.POST['action']

            if action not in self.actions:
                msg = _("Items must be selected in order to perform "
                        "actions on them. No items have been changed.")
                av.message_user(msg)
            else:
                ac, name, description, icon = self.actions[action]
                select_across = request.POST.get('select_across', False) == '1'
                selected = request.POST.getlist(ACTION_CHECKBOX_NAME)

                if not selected and not select_across:
                    # Reminder that something needs to be selected or nothing will happen
                    msg = _("Items must be selected in order to perform "
                            "actions on them. No items have been changed.")
                    av.message_user(msg)
                else:
                    queryset = av.list_queryset._clone()
                    if not select_across:
                        # Perform the action only on the selected objects
                        queryset = av.list_queryset.filter(pk__in=selected)
                    response = self.response_action(ac, queryset)
                    # Actions may return an HttpResponse, which will be used as the
                    # response from the POST. If not, we'll be a good little HTTP
                    # citizen and redirect back to the changelist page.
                    if isinstance(response, HttpResponse):
                        return response
                    else:
                        return HttpResponseRedirect(request.get_full_path())
        return response 
Example 33
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_response(self, response, context, *args, **kwargs):
        file_type = self.request.GET.get('export_type', 'csv')
        charset = 'UTF-8' if file_type == 'xml' or file_type == 'json' else 'gbk'
        response = HttpResponse(
            content_type="%s; charset=%s" % (self.export_mimes[file_type], charset))

        file_name = self.opts.verbose_name.replace(' ', '_')
        response['Content-Disposition'] = ('attachment; filename=%s.%s' % (
            file_name, file_type)).encode('utf-8')

        response.write(getattr(self, 'get_%s_export' % file_type)(context))
        return response

    # View Methods 
Example 34
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def home(request):
    redirect_uri = request.build_absolute_uri(reverse('tutorial:gettoken'))
    sign_in_url = get_signin_url(redirect_uri)

    return HttpResponse('<a href="' + sign_in_url +'">Click here to sign in and view your mail</a>') 
Example 35
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def mail(request):
    access_token = request.session['access_token']
    # If there is no token in the session, redirect to home
    if not access_token:
        return HttpResponseRedirect(reverse('tutorial:home'))
    else:
        messages = get_my_messages(access_token)
        return HttpResponse('Messages: {0}'.format(messages)) 
Example 36
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def post_events(request):
    access_token = request.session['access_token']
    if not access_token:
        return HttpResponseRedirect(reverse('tutorial:home'))
    else:
        post_event_results = post_my_events(access_token)
        return HttpResponse('Messages: {0}'.format(post_event_results)) 
Example 37
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def contacts(request):
    access_token = request.session['access_token']
    # If there is no token in the session, redirect to home
    if not access_token:
        return HttpResponseRedirect(reverse('tutorial:home'))
    else:
        contacts = get_my_contacts(access_token)
        return HttpResponse('Contacts: {0}'.format(contacts)) 
Example 38
Project: django-hide-herokuapp   Author: isms   File: tests.py    MIT License 5 votes vote down vote up
def test_process_non_herokuapp_response(self):
        request = Mock(path='/')
        request.get_host = lambda: 'drivendata.org'
        response = HttpResponse()
        response = self.middleware.process_response(request, response)

        self.assertIsInstance(response, HttpResponse)
        self.assertNotIn('X-Robots-Tag', response) 
Example 39
Project: django-hide-herokuapp   Author: isms   File: tests.py    MIT License 5 votes vote down vote up
def test_process_herokuapp_response(self):
        request = Mock(path='/')
        request.get_host = lambda: 'phoney-baloney-1337.herokuapp.org'
        response = HttpResponse()
        response = self.middleware.process_response(request, response)

        self.assertIsInstance(response, HttpResponse)
        self.assertIn('X-Robots-Tag', response)
        self.assertEqual(response['X-Robots-Tag'], 'noindex, nofollow') 
Example 40
Project: django-hide-herokuapp   Author: isms   File: views.py    MIT License 5 votes vote down vote up
def herokuapp_robots_view(request):
    """
    Add restrictive robots.txt to prevent sites under *.herokuapp.com from being indexed.
    """

    response_text = ""
    http_host = request.get_host()

    if http_host and 'herokuapp' in http_host:
        response_text = "User-agent: *\nDisallow: /"

    return HttpResponse(response_text, content_type="text/plain") 
Example 41
Project: Crop-Watch   Author: objectsyndicate   File: views.py    Apache License 2.0 5 votes vote down vote up
def status():
    stat = '{ "status": "OK" }'
    return HttpResponse(stat, content_type='application/json') 
Example 42
Project: django-route   Author: vinayinvicible   File: urls.py    MIT License 5 votes vote down vote up
def test_view(request, response):
    return HttpResponse(response) 
Example 43
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def json_validate_rfc(request, rfc):
    url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
    results = create_output(url)
    results = json.dumps(results, cls=DjangoJSONEncoder)
    return HttpResponse(results, content_type='application/json') 
Example 44
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def json_validate_draft(request, draft):
    url = 'http://tools.ietf.org/id/{!s}'.format(draft)
    results = create_output(url)
    results = json.dumps(results, cls=DjangoJSONEncoder)
    return HttpResponse(results, content_type='application/json') 
Example 45
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datatracker_rfc(request):
    documents = []
    rfcs = request.GET.getlist('doc')
    for doc in rfcs:
        url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(doc)
        results = create_output(url, for_datatracker=True)
        results["name"] = doc
        documents.append(results)
    result = {"yangvalidator-version": versions['validator_version'],
              "documents": documents}
    results = json.dumps(result, cls=DjangoJSONEncoder)
    return HttpResponse(results, content_type='application/json') 
Example 46
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datatracker_draft(request):
    documents = []
    drafts = request.GET.getlist('doc')
    for doc in drafts:
        url = 'http://tools.ietf.org/id/{!s}'.format(doc)
        results = create_output(url, for_datatracker=True)
        results["name"] = doc
        documents.append(results)
    result = {"yangvalidator-version": versions['validator_version'],
              "documents": documents}
    results = json.dumps(result, cls=DjangoJSONEncoder)
    return HttpResponse(results, content_type='application/json') 
Example 47
Project: SunshineCTF-2019-Public   Author: HackUCF   File: views.py    MIT License 5 votes vote down vote up
def document_view(request, filename):
    user = request.user
    document = images.objects.get(user=user, ifile__endswith=filename)
    response = HttpResponse()
    response["Content-Disposition"] = "inline"
    response["Content-Type"] = "image/jpeg"
    response['X-Accel-Redirect'] = "/protected/user-{0}/{1}".format(str(user.id),document.get_upldName())
    return response 
Example 48
Project: SunshineCTF-2019-Public   Author: HackUCF   File: views.py    MIT License 5 votes vote down vote up
def vic_document_view(request, **kwargs):
    userid = kwargs.get('userid')
    filename = kwargs.get('filename')
    document = images.objects.get(user=userid, ifile__endswith=filename)
    response = HttpResponse()
    response["Content-Disposition"] = "inline"
    response["Content-Type"] = "image/jpeg"
    response['X-Accel-Redirect'] = "/protected/user-{0}/{1}".format(str(userid),document.get_upldName())
    return response 
Example 49
Project: cfbets   Author: joshpelkey   File: views.py    Apache License 2.0 5 votes vote down vote up
def check_duplicate_bet(request):

    if request.method == 'POST':
        # get the id in the post
        prop_id = request.POST.get('id')
        response_data = {}
        # check and see if this user has already accepted this bet at least
        # once
        prop_bet = ProposedBet.objects.get(id=prop_id)
        accepted_bets = AcceptedBet.objects.filter(
            accepted_prop=prop_bet, accepted_user=request.user)
        if accepted_bets:
            response_data['is_duplicate'] = 'True'
        else:
            response_data['is_duplicate'] = 'False'

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )

    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this should not happen"}),
            content_type="application/json"
        ) 
Example 50
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def verification(request, url):
    content = str(LetsEncrypt.objects.get(url=url).text)

    response = HttpResponse(content, content_type='text/plain')
    response['Content-Length'] = len(content)

    return response 
Example 51
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def CSV_view_participants(request, pk):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="participants.txt"'

    writer = csv.writer(response)
    writer.writerow(['These are your participants:'])

    event = get_object_or_404(Event, pk=pk)
    participants = event.participants

    for user in participants:
        writer.writerow([user.username, user.first_name, user.last_name, user.email])

    return response 
Example 52
Project: i-portalen   Author: I-sektionen   File: views.py    MIT License 5 votes vote down vote up
def CSV_view_preregistrations(request, pk):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="preregistrations.txt"'

    writer = csv.writer(response)
    writer.writerow(['These are your preregistrations:'])

    event = get_object_or_404(Event, pk=pk)
    preregistrations = event.preregistrations

    for user in preregistrations:
        writer.writerow([user.username, user.first_name, user.last_name, user.email])

    return response 
Example 53
Project: Servo   Author: fpsw   File: customer.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def download(request, format='csv', group='all'):
    """
    Downloads all customers or search results
    """
    filename = 'customers'
    results = Customer.objects.all()
    query = request.session.get('customer_query')

    response = HttpResponse(content_type="text/plain; charset=utf-8")
    response['Content-Disposition'] = 'attachment; filename="%s.txt"' % filename
    response.write(u"ID\tNAME\tEMAIL\tPHONE\tADDRESS\tPOSTAL CODE\tCITY\tCOUNTRY\tNOTES\n")

    if group != 'all':
        results = results.filter(groups__slug=group)

    if query:
        results = Customer.objects.filter(**query).distinct()

    for c in results:
        row = u"%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (c.pk,
                                                         c.name,
                                                         c.email,
                                                         c.phone,
                                                         c.street_address,
                                                         c.zip_code,
                                                         c.city,
                                                         c.country,
                                                         c.notes,)
        response.write(row)

    return response 
Example 54
Project: Servo   Author: fpsw   File: tags.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clear(request, pk):
    TaggedItem.objects.get(pk=pk).delete()
    return HttpResponse("") 
Example 55
Project: Servo   Author: fpsw   File: files.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def view_file(request, pk):
    doc = Attachment.objects.get(pk=pk)
    return HttpResponse(doc.content.read(), content_type=doc.mime_type) 
Example 56
Project: Servo   Author: fpsw   File: account.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def download_calendar(request, pk, view):
    calendar = get_object_or_404(Calendar, pk=pk)

    response = HttpResponse(content_type="text/csv")
    response['Content-Disposition'] = 'attachment; filename="%s.csv"' % calendar.title
    writer = csv.writer(response)
    writer.writerow(['START', 'FINISH', 'HOURS', 'NOTES'])

    for e in calendar.calendarevent_set.all():
        writer.writerow([e.started_at, e.finished_at, e.get_hours(), e.notes])

    return response 
Example 57
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, *args):
        args = self.request.GET
        if not args.get('q'):
            error = {'error': 'Need parameter for query'}
            return HttpResponse(json.dumps(error),
                                status=400,
                                content_type='application/json')

        self.code = args.get('q')
        self.object = get_object_or_404(Order, code=self.code)
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context) 
Example 58
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def tags(request):
    results = Tag.objects.filter(**request.GET.dict())
    data = results.distinct().values_list("title", flat=True)
    return HttpResponse(json.dumps(list(data)), content_type='application/json') 
Example 59
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def statuses(request):
    from servo.models import Status
    results = Status.objects.all()
    data = serialize('json', results)
    return HttpResponse(data, content_type='application/json') 
Example 60
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def users(request):
    query = request.GET.dict()
    queryset = User.active.filter(**query)
    data = list(queryset.values_list("full_name", flat=True))
    return HttpResponse(json.dumps(data), content_type='application/json') 
Example 61
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def places(request):
    places = Order.objects.exclude(place=None)
    places = places.order_by("place").distinct("place").values_list('place', flat=True)
    return HttpResponse(json.dumps(list(places)), content_type='application/json') 
Example 62
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def queues(request):
    queryset = Queue.objects.all()
    data = serialize('json', queryset, fields=('pk', 'title'))
    return HttpResponse(data, content_type='application/json') 
Example 63
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def json_response(data):
    return HttpResponse(json.dumps(data), content_type='application/json') 
Example 64
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ok(message):
    msg = json.dumps(dict(ok=message))
    return HttpResponse(msg, content_type='application/json') 
Example 65
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def client_error(message):
    msg = json.dumps(dict(error=str(message)))
    return HttpResponse(msg, content_type='application/json', status=400) 
Example 66
Project: Servo   Author: fpsw   File: api.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def messages(request):
    """
    Responds to SMS status updates
    """
    from servo.messaging.sms import SMSJazzProvider, HQSMSProvider

    if not request.GET.get('id'):
        return HttpResponse('Thanks, but no thanks')

    m = get_object_or_404(Message, code=request.GET['id'])
    gw = Configuration.conf('sms_gateway')
    statusmap = HQSMSProvider.STATUSES

    if gw == 'jazz':
        statusmap = SMSJazzProvider.STATUSES

    status = statusmap[request.GET['status']]
    m.status = status[0]
    m.error = status[1]

    if m.status == 'DELIVERED':
        m.received_at = timezone.now()

    if m.status == 'FAILED':
        if m.note.order:
            uid = Configuration.conf('imap_act')
            if uid:
                user = User.objects.get(pk=uid)
                m.note.order.notify('sms_failed', m.error, user)

    m.save()

    return HttpResponse('OK') 
Example 67
Project: Servo   Author: fpsw   File: order.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def toggle_tag(request, order_id, tag_id):
    tag = get_object_or_404(Tag, pk=tag_id)
    order = get_object_or_404(Order, pk=order_id)

    if tag not in order.tags.all():
        order.add_tag(tag)
    else:
        order.tags.remove(tag)

    return HttpResponse(tag.title) 
Example 68
Project: Servo   Author: fpsw   File: order.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def toggle_task(request, order_id, item_id):
    """Toggle a given Check List item in this order."""
    checklist_item = get_object_or_404(ChecklistItem, pk=item_id)
    try:
        item = ChecklistItemValue.objects.get(order_id=order_id,
                                              item=checklist_item)
        item.delete()
    except ChecklistItemValue.DoesNotExist:
        item = ChecklistItemValue()
        item.item = checklist_item
        item.order_id = order_id
        item.checked_by = request.user
        item.save()

    return HttpResponse(checklist_item.title) 
Example 69
Project: Servo   Author: fpsw   File: order.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def report_product(request, pk, item_id):
    product = ServiceOrderItem.objects.get(pk=item_id)
    product.should_report = not product.should_report
    product.save()

    if product.should_report:
        return HttpResponse('<i class="icon-ok"></i>')

    return HttpResponse('<i class="icon-ok icon-white"></i>') 
Example 70
Project: Servo   Author: fpsw   File: note.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def show_barcode(request, text):
    """Return text as a barcode."""
    if request.GET.get('f') == 'svg':
        import barcode
        output = StringIO.StringIO()
        code = barcode.Code39(text, add_checksum=False)
        code.write(output)
        contents = output.getvalue()
        output.close()
        return HttpResponse(contents, content_type="image/svg+xml")

    d = BarcodeDrawing(text)
    return HttpResponse(d.asString("png"), content_type="image/png") 
Example 71
Project: Servo   Author: fpsw   File: note.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def render_template(request, order_id=None):
    """
    Renders the template with this title with the current
    Service Order as the context
    """
    title = request.POST.get('title')
    tpl = get_object_or_404(Template, title=title)
    content = tpl.content

    if order_id:
        order = get_object_or_404(Order, pk=order_id)
        content = tpl.render(order)

    return HttpResponse(content) 
Example 72
Project: Servo   Author: fpsw   File: note.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def templates(request, template_id=None):
    if template_id:
        tpl = get_object_or_404(Template, pk=template_id)
        content = tpl.content
        if request.session.get('current_order_id'):
            tpl = template.Template(content)
            order = Order.objects.get(pk=request.session['current_order_id'])
            content = tpl.render(template.Context({'order': order}))

        return HttpResponse(content)

    templates = Template.objects.all()
    return render(request, 'notes/templates.html', {'templates': templates}) 
Example 73
Project: Servo   Author: fpsw   File: gsx.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def return_label(request, repair, part):
    """
    Returns the return label PDF for this repair and part
    """
    repair = get_object_or_404(Repair, pk=repair)

    try:
        repair.connect_gsx(request.user)
        label_data = repair.get_return_label(part)
        return HttpResponse(label_data, content_type="application/pdf")
    except gsxws.GsxError as e:
        messages.error(request, e)
        return redirect(repair.order) 
Example 74
Project: Servo   Author: fpsw   File: queue.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def statuses(request, queue_id):
    """Lists available statuses for this queue"""
    queue = Queue.objects.get(pk=queue_id)
    
    class StatusForm(forms.Form):
        status = forms.ModelChoiceField(queryset=queue.queuestatus_set.all())

    form = StatusForm()
    return HttpResponse(str(form['status'])) 
Example 75
Project: xadmin_bugfix   Author: vip68   File: editable.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c)) 
Example 76
Project: xadmin_bugfix   Author: vip68   File: chart.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get(self, request, name):
        if name not in self.data_charts:
            return HttpResponseNotFound()

        self.chart = self.data_charts[name]

        self.x_field = self.chart['x-field']
        y_fields = self.chart['y-field']
        self.y_fields = (
            y_fields,) if type(y_fields) not in (list, tuple) else y_fields

        datas = [{"data":[], "label": force_text(label_for_field(
            i, self.model, model_admin=self))} for i in self.y_fields]

        self.make_result_list()

        for obj in self.result_list:
            xf, attrs, value = lookup_field(self.x_field, obj, self)
            for i, yfname in enumerate(self.y_fields):
                yf, yattrs, yv = lookup_field(yfname, obj, self)
                datas[i]["data"].append((value, yv))

        option = {'series': {'lines': {'show': True}, 'points': {'show': False}},
                  'grid': {'hoverable': True, 'clickable': True}}
        try:
            xfield = self.opts.get_field(self.x_field)
            if type(xfield) in (models.DateTimeField, models.DateField, models.TimeField):
                option['xaxis'] = {'mode': "time", 'tickLength': 5}
                if type(xfield) is models.DateField:
                    option['xaxis']['timeformat'] = "%y/%m/%d"
                elif type(xfield) is models.TimeField:
                    option['xaxis']['timeformat'] = "%H:%M:%S"
                else:
                    option['xaxis']['timeformat'] = "%y/%m/%d %H:%M:%S"
        except Exception:
            pass

        option.update(self.chart.get('option', {}))

        content = {'data': datas, 'option': option}
        result = json.dumps(content, cls=JSONEncoder, ensure_ascii=False)

        return HttpResponse(result) 
Example 77
Project: django-xadmin   Author: MarkHoo   File: chart.py    MIT License 4 votes vote down vote up
def get(self, request, name):
        if name not in self.data_charts:
            return HttpResponseNotFound()

        self.chart = self.data_charts[name]

        self.x_field = self.chart['x-field']
        y_fields = self.chart['y-field']
        self.y_fields = (
            y_fields,) if type(y_fields) not in (list, tuple) else y_fields

        datas = [{"data":[], "label": force_text(label_for_field(
            i, self.model, model_admin=self))} for i in self.y_fields]

        self.make_result_list()

        for obj in self.result_list:
            xf, attrs, value = lookup_field(self.x_field, obj, self)
            for i, yfname in enumerate(self.y_fields):
                yf, yattrs, yv = lookup_field(yfname, obj, self)
                datas[i]["data"].append((value, yv))

        option = {'series': {'lines': {'show': True}, 'points': {'show': False}},
                  'grid': {'hoverable': True, 'clickable': True}}
        try:
            xfield = self.opts.get_field(self.x_field)
            if type(xfield) in (models.DateTimeField, models.DateField, models.TimeField):
                option['xaxis'] = {'mode': "time", 'tickLength': 5}
                if type(xfield) is models.DateField:
                    option['xaxis']['timeformat'] = "%y/%m/%d"
                elif type(xfield) is models.TimeField:
                    option['xaxis']['timeformat'] = "%H:%M:%S"
                else:
                    option['xaxis']['timeformat'] = "%y/%m/%d %H:%M:%S"
        except Exception:
            pass

        option.update(self.chart.get('option', {}))

        content = {'data': datas, 'option': option}
        result = json.dumps(content, cls=JSONEncoder, ensure_ascii=False)

        return HttpResponse(result) 
Example 78
Project: Crop-Watch   Author: objectsyndicate   File: views.py    Apache License 2.0 4 votes vote down vote up
def flot_ajax(request, start, end, uuid):
    data = ""
    # check if the incoming values are integers,
    try:
        int(start) and int(end)
        # are they 13 digit integers, (are they timestamps)
        if len(start) == 13 and len(end) == 13:
            t1 = []
            t2 = []
            h = []
            uv = []
            l = []
            # does the user have an iotank?
            if not ioTank.objects.filter(owner=request.user):
                bots = None
            else:
                bots = ioTank.objects.get(owner=request.user, id=uuid)
                # Z for UTC %z for localtz
                start = time.strftime('%Y-%m-%d %H:%M:%SZ', time.gmtime(int(start) / 1000.))
                end = time.strftime('%Y-%m-%d %H:%M:%SZ', time.gmtime(int(end) / 1000.))
                readings = SensorReading.objects.filter(bot=bots, timestamp__range=(start, end)).order_by('timestamp')
                for i in readings:
                    if bots.u == 'F':
                        i.t1 = 9.0 / 5.0 * int(i.t1) + 32
                        i.t2 = 9.0 / 5.0 * int(i.t2) + 32
                    t1_list = []
                    t2_list = []
                    h_list = []
                    uv_list = []
                    l_list = []

                    unixtime = int(time.mktime(i.timestamp.timetuple()) * 1000)

                    t1_list.append(unixtime)
                    t1_list.append(float(i.t1))
                    t1.append(t1_list)

                    t2_list.append(unixtime)
                    t2_list.append(int(i.t2))
                    t2.append(t2_list)

                    h_list.append(unixtime)
                    h_list.append(int(i.h))
                    h.append(h_list)

                    uv_list.append(unixtime)
                    uv_list.append(float(i.uv))
                    uv.append(uv_list)

                    l_list.append(unixtime)
                    l_list.append(float(i.l))
                    l.append(l_list)

            data = '{"data":{"t1":' + str(t1) + ',"t2":' + str(t2) + ',"h":' + str(h) + ',"uv":' + str(
                uv) + ',"l":' + str(l) + '}}'
    except ValueError:
        return HttpResponse(start + end, content_type='application/json')
    return HttpResponse(data, content_type='application/json')


# List all devices 
Example 79
Project: cfbets   Author: joshpelkey   File: views.py    Apache License 2.0 4 votes vote down vote up
def place_bets_form_process(request, next_url):

    if request.method == 'POST':
        form = PlaceBetsForm(request.POST)

        if form.is_valid():
            # gather form entries and save to DB
            new_bet = ProposedBet(
                user=request.user,
                prop_text=form.cleaned_data['bet'],
                prop_wager=form.cleaned_data['bet_amount'],
                max_wagers=form.cleaned_data['qty_allowed'],
                remaining_wagers=form.cleaned_data['qty_allowed'],
                end_date=form.cleaned_data['bet_expiration_date'],
                created_on=timezone.now(),
                modified_on=timezone.now())
            # save to the db
            new_bet.save()

            # post to slack
            slack_webhook_url = settings.SLACK_WEBHOOK_URL
            slack_data = {"attachments":[{"fallback":"A new bet was posted.", \
                "color":"#36a64f", \
                "pretext":"A new bet was posted, <!here>:", \
                "author_name":request.user.get_full_name(), \
                "title":"($" + str(form.cleaned_data['bet_amount']) + ") " \
                + form.cleaned_data['bet'],"title_link":"https://cfbets.us/bets/open_bets/"}]}

            slack_response = requests.post(slack_webhook_url, json=slack_data)

            # save the url to know where to redirect
            response = {'url': next_url}

            # send a message over that the bet is complete
            messages.success(request, 'Bet submitted succesfully.')

            return HttpResponse(
                json.dumps(response),
                content_type='application/json')
        else:
            # form isn't valid, return to ajax call with error and form with
            # errors
            return render(request, 'bets/place_bets.html',
                          {'place_bets_form': form}, status=400)

    return HttpResponseRedirect('/bets/my_bets') 
Example 80
Project: Servo   Author: fpsw   File: product.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def get_inventory_report(request):
    """
    Returns stocked amount of products at each location
    """
    import re
    from django.db import connection
    cursor = connection.cursor()
    location_map = {}

    for l in Location.objects.filter(enabled=True):
         location_map[str(l.pk)] = l.title

    # @TODO this should be rewritten as a pivot query
    # but this will have to do for now. This is still much
    # faster than using the ORM.
    query = """SELECT p.id, p.code, l.id, i.amount_stocked 
    FROM servo_product p, servo_inventory i, servo_location l
        WHERE p.id = i.product_id AND l.id = i.location_id
        ORDER BY p.id ASC"""
    cursor.execute(query)

    response = HttpResponse(content_type="text/plain; charset=utf-8")
    filename = 'servo_inventory_report.txt'
    #response['Content-Disposition'] = 'attachment; filename="%s"' % filename
    header = ['ID', 'CODE'] + location_map.values()
    response.write("\t".join(header) + "\n")
    inventory, codemap = {}, {}

    for k in cursor.fetchall():
        product_id = unicode(k[0])
        codemap[product_id] = k[1] # map product IDs to product codes
        inv_slot = {k[2]: k[3]}

        try:
            inventory[product_id].append(inv_slot)
        except KeyError:
            inventory[product_id] = [inv_slot]

    for k, v in inventory.iteritems():
        inventory_cols = []
        for i, x in location_map.iteritems():
            for p in v:
                amount = p.get(i, '0') # fill empty inventory slots with zeros
                inventory_cols.append(amount)

        code = unicode(codemap[k])
        row = [k, code] + inventory_cols
        response.write("\t".join(row) + "\n")

    return response