Python django.http.HttpResponse() Examples

The following are 30 code examples of django.http.HttpResponse(). 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 also want to check out all available functions/classes of the module django.http , or try the search function .
Example #1
Source File: views.py    From pinax-documents with MIT License 8 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
Source File: views.py    From yang-explorer with 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 #3
Source File: api.py    From Servo with 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 #4
Source File: views.py    From iHealth_site with 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 #5
Source File: resource.py    From polls-api with 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 #6
Source File: customer.py    From Servo with 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 #7
Source File: order.py    From Servo with 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 #8
Source File: views.py    From puput with 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 #9
Source File: test_views.py    From pinax-documents with 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 #10
Source File: note.py    From Servo with 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 #11
Source File: urls.py    From django-oauth-toolkit-jwt with MIT License 5 votes vote down vote up
def post(self, request):
        response = json.dumps({"username": request.user.username})
        return HttpResponse(response) 
Example #12
Source File: views.py    From TwitterFriends with GNU General Public License v3.0 5 votes vote down vote up
def netgml(request):
    global whole_net
    net = generate_net_gml(whole_net)
    return HttpResponse(net, content_type='text/plain') 
Example #13
Source File: urls.py    From django-oauth-toolkit-jwt with MIT License 5 votes vote down vote up
def get(self, _request):
        return HttpResponse('mockforauthscopeview-get') 
Example #14
Source File: views.py    From botbuilder-python with MIT License 5 votes vote down vote up
def home(request):
    # Basic request, no logging.  Check BOT properties added.
    return HttpResponse("Welcome home") 
Example #15
Source File: views.py    From TwitterFriends with GNU General Public License v3.0 5 votes vote down vote up
def netgdf(request):
    global whole_net
    net = generate_net_gdf(whole_net)
    return HttpResponse(net, content_type='text/plain') 
Example #16
Source File: views.py    From django-payfast with MIT License 5 votes vote down vote up
def notify_handler(request):
    """
    Notify URL handler.

    On successful access 'payfast.signals.notify' signal is sent.
    Orders should be processed in signal handler.
    """
    m_payment_id = request.POST.get('m_payment_id', None)
    order = get_object_or_404(PayFastOrder, m_payment_id=m_payment_id)

    form = NotifyForm(request, request.POST, instance=order)
    if not form.is_valid():
        errors = form.plain_errors()[:255]
        order.request_ip = form.ip
        order.debug_info = errors
        order.trusted = False
        order.save()

        # XXX: Any possible data leakage here?
        return HttpResponseBadRequest(
            content_type='application/json',
            content=form.errors.as_json(),
        )

    order = form.save()
    signals.notify.send(sender=notify_handler, order=order)
    return HttpResponse() 
Example #17
Source File: views.py    From TwitterFriends with GNU General Public License v3.0 5 votes vote down vote up
def netnet(request):
    global whole_net
    net = generate_net_net(whole_net)
    return HttpResponse(net, content_type='text/plain') 
Example #18
Source File: views.py    From iHealth_site with GNU General Public License v2.0 5 votes vote down vote up
def userList(request):
    '''获取用户列表'''
    try:
        # 提取参数
        name = request.GET.get('name','')
        selfname = request.GET.get('selfname','')
        limit = int(request.GET.get('limit',25))
        # 获取数据
        user_list = Users().find_many_by_name(name)
        # 截取数据
        user_list = user_list[:limit]
        res_list = []
        for user in user_list:
            # 将对象中不是字符串的变量值转换为字符串
            user['_id'] = user['_id'].__str__()
            # 排除掉自身
            if user['name']==selfname:
                continue
            del user['password']
            res_list.append(user)
        # 转换为JSON
        res = json.dumps(res_list, indent=4)
        return HttpResponse(res, content_type='application/json')
    except Exception,e:
        res = {
            'msg' : '模糊匹配失败指定用户名失败!',
            'reason' : str(e),
        }
        res = json.dumps(res, indent=4)
        return HttpResponse(res, content_type='application/json') 
Example #19
Source File: admin.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_response(self):
        from django.http import HttpResponse
        wrapper = self.get_wrapper()
        response = HttpResponse(wrapper, content_type='application/force-download')
        response['Content-Disposition'] = 'attachment; filename=%s' % self.filename
        response['Content-Length'] = self.filesize
        return response 
Example #20
Source File: views.py    From yang-explorer with Apache License 2.0 5 votes vote down vote up
def login_handler(request):
    """ HTTP Request handler function for user login / logout requests """
    if request.POST:
        action = request.POST['action']
        if action == 'login':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # Correct password, and the user is marked "active"
                login(request, user)
            else:
                return HttpResponse(Response.error('login', 'Authentication Failed'))
        else:
            username = ''
            try:
                if request.session.session_key is not None and request.session.session_key != '':
                    session_dir = ServerSettings.session_path(request.session.session_key)
                    if os.path.exists(session_dir):
                        logger.debug('Cleaning ' + session_dir)
                        shutil.rmtree(session_dir)
                logout(request)
            except:
                logger.exception("Failed")
            else:
                logger.debug('Logout success!!')
        session = get_session_config(username)
        return HttpResponse(Response.success(action, 'ok', session))
    return HttpResponse(Response.error('unknown', 'Invalid request!!')) 
Example #21
Source File: views.py    From iHealth_site with GNU General Public License v2.0 5 votes vote down vote up
def userCheck(request):
    '''检查用户是否可以登录'''
    try:
        # 获取post提交的数据
        user = request.POST
        print user
        real_user = Users().find_one_by_email(user['email'])
        if real_user == None:
            res = {
                'msg' : '用户登陆验证未通过!',
                'reason' : 'User is not found.',
                'result' : False,
            }
        elif user['password'] == real_user['password']:     #取消MD5再次加密
            real_user['_id'] = str(real_user['_id'])
            # del real_user['password']
            res = {
                'msg' : '用户登陆验证通过!',
                'data' : real_user,
                'result' : True,
            }
        else:
            res = {
                'msg' : '用户登陆验证未通过!',
                'reason' : 'Password error.',
                'result' : False,
            }
        res = json.dumps(res, indent=4)
        return HttpResponse(res, content_type='application/json')
    except Exception,e:
        res = {
            'msg' : '用户登陆验证过程失败!',
            'reason' : str(e),
            'result' : False,
        }
        res = json.dumps(res, indent=4)
        return HttpResponse(res, content_type='application/json') 
Example #22
Source File: views.py    From iHealth_site with GNU General Public License v2.0 5 votes vote down vote up
def articleDetail(request):
    '''文章详情接口'''
    try:
        # 提取参数
        id = request.GET.get('id',None)
        userID = request.GET.get('userID', None)

        if id == None:
            return HttpResponse('请提供 id 参数!')
        # 更新文章阅读量
        Articles().updateRead(id=id,cnt=1)
        # 获取数据
        article = Articles().find_one(id=id)
        # 更新用户label,个性化推荐用 阅读暂定+1
        if userID != None:
            Users().update_label(userID, article['category'], 1)
        # 准备文章数据,转换为 JSON
        del article['_id']
        del article['intro']
        article['pubdate'] = article['pubdate'].__str__()
        article['content'] = article['content'].strip()
        res = json.dumps(article, indent=4)
        return HttpResponse(res, content_type='application/json')
    except Exception,e:
        res = {
            'msg' : '文章详情获取失败!',
            'reason' : str(e),
        }
        res = json.dumps(res, indent=4)
        return HttpResponse(res, content_type='application/json') 
Example #23
Source File: views.py    From iHealth_site with GNU General Public License v2.0 5 votes vote down vote up
def hello(request):
    '''测试接口'''
    return HttpResponse("Hello, I am iHealth ' backend!") 
Example #24
Source File: views.py    From puput with MIT License 5 votes vote down vote up
def post(self, request, entry_page_id, *args, **kwargs):
        try:
            entry_page = EntryPage.objects.get(pk=entry_page_id)
            blog_page = entry_page.blog_page
            comment_class = import_model(settings.PUPUT_COMMENTS_PROVIDER)(blog_page, entry_page)
            num_comments = comment_class.get_num_comments()
            entry_page.num_comments = num_comments
            entry_page.save(update_fields=('num_comments',))
            return HttpResponse()
        except EntryPage.DoesNotExist:
            raise Http404 
Example #25
Source File: views.py    From controller with MIT License 5 votes vote down vote up
def logs(self, request, **kwargs):
        app = self.get_object()
        try:
            logs = app.logs(request.query_params.get('log_lines', str(settings.LOG_LINES)))
            return HttpResponse(logs, status=status.HTTP_200_OK, content_type='text/plain')
        except NotFound:
            return HttpResponse(status=status.HTTP_204_NO_CONTENT)
        except ServiceUnavailable:
            # TODO make 503
            return HttpResponse("Error accessing logs for {}".format(app.id),
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                content_type='text/plain') 
Example #26
Source File: views.py    From controller with MIT License 5 votes vote down vote up
def get(self, request):
        return HttpResponse("OK") 
Example #27
Source File: views.py    From controller with MIT License 5 votes vote down vote up
def get(self, request):
        try:
            import django.db
            with django.db.connection.cursor() as c:
                c.execute("SELECT 0")
        except django.db.Error as e:
            raise ServiceUnavailable("Database health check failed") from e

        return HttpResponse("OK") 
Example #28
Source File: utils.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def json_response(data):
    """
    Shortcut for sending a JSON response
    """
    return HttpResponse(json.dumps(data), content_type='application/json') 
Example #29
Source File: utils.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def csv_response(data):
    """
    Shortcut for sending a CSV response
    """
    return HttpResponse(data, content_type='text/csv') 
Example #30
Source File: views.py    From MPContribs with 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)