Python django.http.HttpResponse() Examples

The following are 30 code examples for showing how to use django.http.HttpResponse(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: pinax-documents   Author: pinax   File: views.py    License: 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 2
Project: pinax-documents   Author: pinax   File: test_views.py    License: 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 3
Project: Servo   Author: fpsw   File: customer.py    License: 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 4
Project: Servo   Author: fpsw   File: api.py    License: 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 5
Project: Servo   Author: fpsw   File: order.py    License: 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 6
Project: Servo   Author: fpsw   File: note.py    License: 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 7
Project: puput   Author: APSL   File: views.py    License: MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        site = Site.find_for_request(request)
        if not site:
            raise Http404
        if request.resolver_match.url_name == 'entry_page_serve_slug':
            # Splitting the request path and obtaining the path_components
            # this way allows you to place the blog at the level you want on
            # your sitemap.
            # Example:
            # splited_path =  ['es', 'blog', '2016', '06', '23', 'blog-entry']
            # slicing this way you obtain:
            # path_components =  ['es', 'blog', 'blog-entry']
            # with the oldest solution you'll get ['es', 'blog-entry']
            # and a 404 will be raised
            splited_path = strip_prefix_and_ending_slash(request.path).split("/")
            path_components = splited_path[:-4] + splited_path[-1:]
        else:
            path_components = [strip_prefix_and_ending_slash(request.path).split('/')[-1]]
        page, args, kwargs = site.root_page.specific.route(request, path_components)

        for fn in hooks.get_hooks('before_serve_page'):
            result = fn(page, request, args, kwargs)
            if isinstance(result, HttpResponse):
                return result
        return page.serve(request, *args, **kwargs) 
Example 8
Project: iHealth_site   Author: iHealth-ecnu   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
def doUpvote(request):
    '''点赞接口'''
    try:
        id=request.GET.get('id',None)
        userID = request.GET.get('userID', None)
        if id == None:
            return HttpResponse('请提供 id 参数!')

        Articles().updateUpvote(id=id)
        res = {
            'msg' : '点赞成功!',
            'result' : True,
        }
        article = Articles().find_one(id=id)
        # 更新用户label,个性化推荐用 点赞暂定+10
        if userID != None:
            Users().update_label(userID, article['category'], 10)
    except Exception,e:
        res = {
            'msg' : '点赞失败!',
            'reason' : str(e),
            'result' : False,
        } 
Example 9
Project: polls-api   Author: apiaryio   File: resource.py    License: MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        content_type = self.determine_content_type(request)
        handlers = self.content_handlers()
        handler = handlers[str(content_type)]
        response = HttpResponse(json.dumps(handler(self)), content_type)
        patch_vary_headers(response, ['Accept'])
        if self.cache_max_age is not None:
            patch_cache_control(response, max_age=self.cache_max_age)

        if str(content_type) == 'application/json':
            # Add a Link header
            can_embed_relation = lambda relation: not self.can_embed(relation[0])
            relations = filter(can_embed_relation, self.get_relations().items())
            relation_to_link = lambda relation: '<{}>; rel="{}"'.format(relation[1].get_uri(), relation[0])
            links = list(map(relation_to_link, relations))
            if len(links) > 0:
                response['Link'] = ', '.join(links)

        if str(content_type) != 'application/vnd.siren+json':
            # Add an Allow header
            methods = ['HEAD', 'GET'] + list(map(lambda a: a.method, self.get_actions().values()))
            response['allow'] = ', '.join(methods)

        return response 
Example 10
Project: yang-explorer   Author: CiscoDevNet   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def admin_handler(request):
    """ HTTP Request handler function to handle actions on yang modules """

    if not request.user.is_authenticated():
        return HttpResponse(Response.error(None, 'User must be logged in'))

    if request.method != 'GET':
        return HttpResponse(Response.error(None, 'Invalid admin Request'))

    action = request.GET.get('action', '')
    logger.info('Received admin request %s for user %s' % (action, request.user.username))

    if action in ['subscribe', 'unsubscribe', 'delete', 'graph']:
        payload = request.GET.get('payload', None)
        print(str(payload))
        (rc, msg) = ModuleAdmin.admin_action(request.user.username, payload, action)
        if not rc:
            return HttpResponse(Response.error(action, msg))

    if action == 'graph':
        return HttpResponse(Response.success(action, msg))

    modules = ModuleAdmin.get_modules(request.user.username)
    return HttpResponse(Response.success(action, 'ok', xml=modules)) 
Example 11
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def cif(request, sid):
    client = Client(headers=get_consumer(request))  # sets/returns global variable
    cif = client.structures.get_entry(pk=sid, _fields=["cif"]).result()["cif"]
    if cif:
        response = HttpResponse(cif, content_type="text/plain")
        response["Content-Disposition"] = "attachment; filename={}.cif".format(sid)
        return response
    return HttpResponse(status=404) 
Example 12
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def download_json(request, cid):
    client = Client(headers=get_consumer(request))  # sets/returns global variable
    contrib = client.contributions.get_entry(pk=cid, fields=["_all"]).result()
    if contrib:
        jcontrib = json.dumps(contrib)
        response = HttpResponse(jcontrib, content_type="application/json")
        response["Content-Disposition"] = "attachment; filename={}.json".format(cid)
        return response
    return HttpResponse(status=404) 
Example 13
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def csv(request, project):
    from pandas import DataFrame
    from pandas.io.json._normalize import nested_to_record

    client = Client(headers=get_consumer(request))  # sets/returns global variable
    contribs = client.contributions.get_entries(
        project=project, _fields=["identifier", "id", "formula", "data"]
    ).result()[
        "data"
    ]  # first 20 only

    data = []
    for contrib in contribs:
        data.append({})
        for k, v in nested_to_record(contrib, sep=".").items():
            if v is not None and not k.endswith(".value") and not k.endswith(".unit"):
                vs = v.split(" ")
                if k.endswith(".display") and len(vs) > 1:
                    key = k.replace("data.", "").replace(".display", "") + f" [{vs[1]}]"
                    data[-1][key] = vs[0]
                else:
                    data[-1][k] = v

    df = DataFrame(data)
    response = HttpResponse(df.to_csv(), content_type="text/csv")
    response["Content-Disposition"] = "attachment; filename={}.csv".format(project)
    return response 
Example 14
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def download(request, project):
    cname = os.environ["PORTAL_CNAME"]
    s3obj = f"{S3_DOWNLOAD_URL}{cname}/{project}.json.gz"
    return redirect(s3obj)
    # TODO check if exists, generate if not, progressbar...
    # return HttpResponse(status=404) 
Example 15
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def rest_submission(request):
    if request.method == "POST":
        serializer = QMCDBSetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response([serializer.errors], status=status.HTTP_400_BAD_REQUEST)
    return HttpResponse(status=400) 
Example 16
Project: python-panavatar   Author: ondergetekende   File: djangoview.py    License: MIT License 5 votes vote down vote up
def generate_image_svg(request, width, height, seed=None):
    width = int(width)
    height = int(height)

    parameters = dict(request.GET.items())

    if seed:
        parameters['seed'] = seed

    response = HttpResponse(get_svg(width, height, parameters),
                            content_type="image/svg+xml")

    return response 
Example 17
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    License: 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 18
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    License: 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 19
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    License: 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 20
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    License: 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 21
Project: Servo   Author: fpsw   File: customer.py    License: 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 22
Project: Servo   Author: fpsw   File: tags.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clear(request, pk):
    TaggedItem.objects.get(pk=pk).delete()
    return HttpResponse("") 
Example 23
Project: Servo   Author: fpsw   File: files.py    License: 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 24
Project: Servo   Author: fpsw   File: account.py    License: 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 25
Project: Servo   Author: fpsw   File: api.py    License: 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 26
Project: Servo   Author: fpsw   File: api.py    License: 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 27
Project: Servo   Author: fpsw   File: api.py    License: 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 28
Project: Servo   Author: fpsw   File: api.py    License: 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 29
Project: Servo   Author: fpsw   File: api.py    License: 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 30
Project: Servo   Author: fpsw   File: api.py    License: 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')