当前位置: 首页>>代码示例>>Python>>正文


Python shortcuts.HttpResponse类代码示例

本文整理汇总了Python中django.shortcuts.HttpResponse的典型用法代码示例。如果您正苦于以下问题:Python HttpResponse类的具体用法?Python HttpResponse怎么用?Python HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: watch

def watch(request):
    response = HttpResponse(status=200)
    session = request.COOKIES.get('_sc', None)

    if not session:
        session = uuid.uuid4().hex
        response.set_cookie('_sc', session, max_age=60 * 60 * 24 * 365)

    http_referer = request.META.get('HTTP_REFERER', None)
    if not http_referer:
        return response

    url_parts = urlparse(http_referer)
    path_parts = utils.strip_path(url_parts.path)
    if len(path_parts) > 1:
        path = path_parts[1]
    else:
        path = path_parts[0]
    ignore = False

    query = url_parts.query

    url_hash = hashlib.md5((path + query).encode('utf-8')).hexdigest()

    before = (datetime.datetime.now() - datetime.timedelta(minutes=URL_TIMEOUT))
    # if models.PageView.objects.filter(datetime__gt=before, session=session, url_hash=url_hash).exists():
    #     ignore = True

    user = None
    if request.user.is_authenticated():
        user = request.user
    if session and not ignore:
        models.log_page_view(path=path, query=query, url_hash=url_hash, session=session, user=user)

    return response
开发者ID:isergey,项目名称:libcms,代码行数:35,代码来源:views.py

示例2: bounce_csv

 def bounce_csv(self, request, queryset):
     # PREPARE
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = 'attachment; filename=bounces.csv'
     writer = csv.writer(response, csv.excel)
     # PROCESS
     response.write(u'\ufeff'.encode('utf8'))  # BOM (optional...Excel needs it to open UTF-8 file properly)
     writer.writerow([
         smart_str(u"ID"),
         smart_str(u"MESSAGE ID"),
         smart_str(u"TIMESTAMP"),
         smart_str(u"MAIL FROM"),
         smart_str(u"MAIL TO"),
         smart_str(u"BOUNCE TYPE"),
         smart_str(u"BOUNCE SUBTYPE"),
         smart_str(u"REPORTING MTA"),
         smart_str(u"ACTION"),
         smart_str(u"STATUS"),
         smart_str(u"DIAGNOSTIC CODE")])
     for obj in queryset:
         writer.writerow([
             smart_str(obj.pk or ''),
             smart_str(obj.sns_messageid or ''),
             smart_str(obj.mail_timestamp or ''),
             smart_str(obj.mail_from or ''),
             smart_str(obj.address or ''),
             smart_str(obj.bounce_type or ''),
             smart_str(obj.bounce_subtype or ''),
             smart_str(obj.reporting_mta or ''),
             smart_str(obj.action or ''),
             smart_str(obj.status or ''),
             smart_str(obj.diagnostic_code or '')])
     # CONCLUDE
     return response
开发者ID:GheloAce,项目名称:django_aws_tools,代码行数:34,代码来源:admin.py

示例3: add_to_cart

def add_to_cart(request, tmplate_name = "index22.html"):
    if request.user.is_authenticated():
        postdata = request.POST.copy()
        prod_name = postdata.get('prod_name', '')
        power = float(postdata.get('opt_power','').replace(',','.'))
        rad = float(postdata.get('radius','').replace(',','.'))
        queryset = Linses.objects.all()
        queryset = queryset.filter(fk_product__product_name__exact = prod_name)
        queryset = queryset.filter(optical_power__exact = power)
        queryset = queryset.filter(radius_of_cutvature__exact = rad)
        qr = Product.objects.get(product_name = prod_name)
        qs = qr.pk_product_id
        request.session.__setitem__('cart', False)
#        qs = qr.fk_product.pk_product_id
        response = HttpResponse()
        response.set_cookie('cart', value=False)


        if request.session['cart'] == False:
            us = request.user.id
            aus = AuthUser.objects.get(id = us)
            order1 = Order(order_status = 5, order_date = datetime.date.today(), fk_user = aus )
            order1.save()
            i = order1.pk_order_id
            request.session["cart"] = True
            request.session.__setitem__('cart_id', i)
        order_prod1 = OrderProduct(fk_order = Order.objects.get(pk_order_id = i), fk_product = qr)
        product_for_saving = Product.objects.get(pk_product_id = qs)
        product_for_saving.balance = F('balance') - 1
        product_for_saving.save()
        order_prod1.save()
        return render_to_response(template_name="index22.html")


    return render_to_response()
开发者ID:Hed1n,项目名称:Diptest,代码行数:35,代码来源:views.py

示例4: complaint_csv

 def complaint_csv(self, request, queryset):
     # PREPARE
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = 'attachment; filename=complaints.csv'
     writer = csv.writer(response, csv.excel)
     response.write(u'\ufeff'.encode('utf8'))  # BOM (optional...Excel needs it to open UTF-8 file properly)
     # PROCESS
     writer.writerow([
         smart_str(u"ID"),
         smart_str(u"MESSAGE ID"),
         smart_str(u"TIMESTAMP"),
         smart_str(u"MAIL FROM"),
         smart_str(u"MAIL TO"),
         smart_str(u"USERAGENT"),
         smart_str(u"COMPLAINT TYPE"),
         smart_str(u"ARRIVAL DATE")])
     for obj in queryset:
         writer.writerow([
             smart_str(obj.pk or ''),
             smart_str(obj.sns_messageid or ''),
             smart_str(obj.mail_timestamp or ''),
             smart_str(obj.mail_from or ''),
             smart_str(obj.address or ''),
             smart_str(obj.useragent or ''),
             smart_str(obj.feedback_type or ''),
             smart_str(obj.arrival_date or '')])
     # CONCLUDE
     return response
开发者ID:GheloAce,项目名称:django_aws_tools,代码行数:28,代码来源:admin.py

示例5: save_workspace

def save_workspace(request):
    data = request.POST["my_data"]
    response = HttpResponse(mimetype="text/plain")
    response.write(data)
    date = datetime.datetime.now().strftime("%Y-%m-%d-T-%H-%M-%S")
    response["Content-Disposition"] = "attachment; filename=%s-%s.cdOnline" % ("workspace", date)
    return response
开发者ID:biomunky,项目名称:spectrum_viewer,代码行数:7,代码来源:views.py

示例6: new_venue_image

def new_venue_image(request,idnum):
	try:
		venue = Venue.objects.get(id=idnum)
		form = VenueImageForm(request.POST,request.FILES)
		if form.is_valid():
			new = VenueImage()
			new.image = form.cleaned_data["new_image"]
			new.caption = form.cleaned_data["caption"]
			new.venue = venue
			new.user = request.user
			new.save()
			images = squares(new.image,new)
			new.small_square.save(new.image.name,images[0],save=True)
			new.square.save(new.image.name,images[1],save=True)
			new.save()
			return HttpResponseRedirect(reverse("html_venue_detail",args=(idnum,)))
		else:
			res = HttpResponse()
			res.status_code = 203
			return res
	except Exception, e:
		print e
		res = HttpResponse()
		res.status_code = 500
		return res
开发者ID:michaelgiba,项目名称:JustOpenedDjango,代码行数:25,代码来源:views.py

示例7: export_student_list

def export_student_list(modeladmin, request, queryset):
    import csv
    from django.utils.encoding import smart_str
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=nexteria_zoznam_studentov.csv'
    writer = csv.writer(response, csv.excel)
    response.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)
    writer.writerow([
        smart_str(u"Meno"),
        smart_str(u"Priezvisko"),
        smart_str(u"Email"),
        smart_str(u"Telefon"),
        smart_str(u"Datum nar."),
        smart_str(u"Fakulta"),
        smart_str(u"Rok zaciatku"),
        smart_str(u"Level"),
        smart_str(u"Skolne"),
    ])

    for obj in queryset:
        writer.writerow([
            smart_str(obj.clovek.meno),
            smart_str(obj.clovek.priezvisko),
            smart_str(obj.clovek.email),
            smart_str(obj.clovek.telefon_cislo),
            smart_str(obj.datum_nar),
            smart_str(obj.fakulta),
            smart_str(obj.rok_zaciatku),
            smart_str(obj.level),
            smart_str(obj.skolne),
        ])
    return response
开发者ID:vacuumlabs,项目名称:NexteriaCRM,代码行数:32,代码来源:admin.py

示例8: book

def book(request, book):
    try:
        book_path = get_book_path(book, request.META.get('REMOTE_ADDR', '0.0.0.0'))
    except AccessDenied as e:
        return HttpResponse(e.message + u' Ваш ip адрес: ' + request.META.get('REMOTE_ADDR', '0.0.0.0'))
    if not book_path or not os.path.isfile(book_path):
        raise Http404(u'Книга не найдена')
    token1 = request.GET.get('token1')
    xml = """\
<Document Version="1.0">\
<Source File="source.xml" URL="http://%s/dl/%s/draw/?part=Part0.zip&amp;book=%s&amp;version=1285566137"/>\
<FileURL>http://%s/dl/%s/draw/?part={part}&amp;book=%s</FileURL>\
<Token1>%s</Token1>\
<Permissions><AllowCopyToClipboard>true</AllowCopyToClipboard><AllowPrint>true</AllowPrint></Permissions>\
</Document>""" % (request.META['HTTP_HOST'],book, book, request.META['HTTP_HOST'], book, book, token1)

    zip_file_content = cStringIO.StringIO()

    zip_file = ZipFile(zip_file_content, 'w')
    zip_file.writestr('doc.xml', xml)
    zip_file.close()

    response = HttpResponse(content_type="application/zip")
    response["Content-Disposition"] = "attachment; filename=%s.zip" % book
    zip_file_content.seek(0)
    response.write(zip_file_content.read())

    return response
开发者ID:isergey,项目名称:chel,代码行数:28,代码来源:views.py

示例9: new_venue_ajax_image

def new_venue_ajax_image(request,idnum):
	try:
		venue = Venue.objects.get(id=idnum)
		form = VenueImageForm(request.POST,request.FILES)
		if form.is_valid():
			new = VenueImage()
			new.image = form.cleaned_data["new_image"]
			new.caption = form.cleaned_data["caption"]
			new.venue = venue
			new.user = request.user
			new.save()
			images = squares(new.image,new)
			new.small_square.save(new.image.name,images[0],save=True)
			new.square.save(new.image.name,images[1],save=True)
			new.save()
			info = { "status": "success",
					 "image" : new.small_square.url,
					 "id" : new.id,
					 "caption" : new.caption }
			return HttpResponse(dumps(info),content_type="application/json")
		else:
			res = HttpResponse()
			res.status_code = 203
			print form.errors
			return res
	except Exception, e:
		print e
		res = HttpResponse()
		res.status_code = 500
		return res
开发者ID:michaelgiba,项目名称:JustOpenedDjango,代码行数:30,代码来源:views.py

示例10: delivery_csv

 def delivery_csv(self, request, queryset):
     # PREPARE
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = 'attachment; filename=deliveries.csv'
     writer = csv.writer(response, csv.excel)
     # PROCESS
     response.write(u'\ufeff'.encode('utf8'))  # BOM (optional...Excel needs it to open UTF-8 file properly)
     writer.writerow([
         smart_str(u"ID"),
         smart_str(u"MESSAGE ID"),
         smart_str(u"TIMESTAMP"),
         smart_str(u"MAIL FROM"),
         smart_str(u"MAIL TO"),
         smart_str(u"SMTP RESPONSE"),
         smart_str(u"REPORTIN MTA")])
     for obj in queryset:
         writer.writerow([
             smart_str(obj.pk or ''),
             smart_str(obj.sns_messageid or ''),
             smart_str(obj.mail_timestamp or ''),
             smart_str(obj.mail_from or ''),
             smart_str(obj.address or ''),
             smart_str(obj.smtp_response or ''),
             smart_str(obj.reporting_mta or '')])
     # CONCLUDE
     return response
开发者ID:GheloAce,项目名称:django_aws_tools,代码行数:26,代码来源:admin.py

示例11: preview

    def preview(module_factory, conf_factory, dbm_factory, params):
        # 1. 通过参数解析配置
        preview_conf = params.get(ModuleCommon.p_preview_conf)
        if not preview_conf:
            return HttpResponse(u"参数错误")
        conf_dict = preview_conf.get(ModuleCommon.k_conf_dict)
        if not conf_dict:
            return HttpResponse(u"参数错误")
        params[ModuleCommon.k_conf_dict] = conf_dict

        path_route = preview_conf.get(ModuleCommon.p_path_route)
        if not path_route:
            return HttpResponse(u"参数错误")
        params[ModuleCommon.p_path_route] = path_route
        params["db_id"] = preview_conf.get("db_id")
        params["baike_id"] = preview_conf.get("baike_id")
        params["section"] = preview_conf.get("section")
        # 2. 跟view调用一致
        try:
            html_render = module_factory.base_loader.loader(module_factory, params)
            http_response = HttpResponse()
            html = module_factory.base_render.render(params.get(ModuleCommon.k_request), html_render)
            http_response.write(html)
            return http_response
        except Exception as info:
            return HttpResponse(u"参数错误")
开发者ID:lingerlover,项目名称:cml,代码行数:26,代码来源:module_loader.py

示例12: SettingsBackend

def SettingsBackend(request):

    if request.POST:
        print request.POST['password']

        user = authenticate(username=request.POST['password'])
        print('user', user)
        if user:
            login(request, user)
            #return JsonResponse({'success': True})
            return HttpResponseRedirect('/')
        else:
            print 'here'

            #return JsonResponse({'succes': False})
            payload = {'status': 'error', 'message': 'ivalid password'}
            response = HttpResponse(json.dumps(payload), content_type='application/json')
            response.status_code = 200
            return JsonResponse({'success': True})            
            #return JsonResponse({'succes': False})
            #return HttpResponse('USer Not found')
            #raise forms.ValidationError('Passwords do not match.')
            #return user_not_found_bad_hash_message
    else:
        return render(request, 'registration/login.html')
开发者ID:AnastasiaPetrovskaya,项目名称:wedday,代码行数:25,代码来源:views.py

示例13: login

def login(request):
    """
    用户登陆事件
    :param request:登陆请求
    :return:
        ①result: 返回码, '0'表示成功 '1'表示用户不存在 '2'表示用户密码错误 '3'表示未知错误
        ②info:dict数据,登陆成功返回的用户信息就保存在这个json里面了
    """
    response = HttpResponse()
    response['Content-Type'] = 'application/json'
    result = '3'

    if request.method == 'POST':
        # 获取客户端信息
        nickname = request.POST.get('userName', '')
        password = request.POST.get('password', '')
        if nickname and password:
            try:
                # 用户存在
                user = User.objects.get(nickname=nickname)
                if user.password == password:
                    # 用户密码正确
                    result = '0'
                else:
                    result = '-1'
            except ObjectDoesNotExist:
                result = '-1'
    response.write(result)
    response.write(fetch_recommend())
    return response
开发者ID:q7940,项目名称:sound,代码行数:30,代码来源:views.py

示例14: register

def register(request):
    """
    注册处理事件
    :param request:注册请求
    :return:
        ①result: '0'表示成功, '1'表示用户名重名, '2'表示未知错误,可能昵称/邮箱/密码为空,可能传输出错
        ②
    """
    # 回复
    response = HttpResponse()
    response['Content-Type'] = 'application/json'

    if request.method == 'POST':
        # 获取客户端信息
        nickname = request.POST.get('userName', '')
        password = request.POST.get('userCode', '')
        avatar = request.POST.get('avatar', '')

        if nickname and password:
            try:
                user = User.objects.get(nickname=nickname)
                result = '1'
            except ObjectDoesNotExist:
                user = User(nickname=nickname, mail='nomail', password=password, create_time=time.time(),
                            action_time=time.time())
                user.save()
                result = '0'
        else:
            result = '2'
    else:
        result = '-1'

    response.write(result)
    response.write(fetch_recommend())  # 返回首页信息
    return response
开发者ID:q7940,项目名称:sound,代码行数:35,代码来源:views.py

示例15: delivery_csv

def delivery_csv(modeladmin, request, queryset):
    response = HttpResponse(mimetype="text/csv")
    response["Content-Disposition"] = "attachment; filename=deliveries.csv"
    writer = csv.writer(response, csv.excel)
    response.write(u"\ufeff".encode("utf8"))  # BOM (optional...Excel needs it to open UTF-8 file properly)
    writer.writerow(
        [
            smart_str(u"ID"),
            smart_str(u"MESSAGE ID"),
            smart_str(u"TIMESTAMP"),
            smart_str(u"MAIL FROM"),
            smart_str(u"MAIL TO"),
            smart_str(u"SMTP RESPONSE"),
            smart_str(u"REPORTIN MTA"),
        ]
    )
    for obj in queryset:
        writer.writerow(
            [
                smart_str(obj.pk or ""),
                smart_str(obj.sns_messageid or ""),
                smart_str(obj.mail_timestamp or ""),
                smart_str(obj.mail_from or ""),
                smart_str(obj.address or ""),
                smart_str(obj.smtp_response or ""),
                smart_str(obj.reporting_mta or ""),
            ]
        )
    return response
开发者ID:makmac213,项目名称:django_aws_tools,代码行数:29,代码来源:admin.py


注:本文中的django.shortcuts.HttpResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。