本文整理汇总了Python中django.http.response.HttpResponse类的典型用法代码示例。如果您正苦于以下问题:Python HttpResponse类的具体用法?Python HttpResponse怎么用?Python HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: exportCSV
def exportCSV(request):
customer_ids = Reservation.objects.filter(service_provider=request.user.service_provider).exclude(customer__isnull=True).values_list('customer_id', flat=True).distinct();
# Find customers who have not reserved anything yet and were added by service provider
customers_nonr = Customer.objects.filter(service_provider=request.user.service_provider)
customers = Customer.objects.filter(pk__in=customer_ids)
# Merge two QuerySets together
customers = customers | customers_nonr
qc = request.GET.get('qc', '')
# Search by name
if qc:
customers = customers.filter(full_name__contains=qc)
customers = customers.order_by('last_name')
# Construct HTTP response
response = HttpResponse(content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename="customers.csv"'
writer = csv.writer(response, csv.excel)
response.write(u'\ufeff'.encode('utf8')) # for excel
writer.writerow([
smart_str(u"First_Name"),
smart_str(u"Last_Name"),
smart_str(u"Phone"),
smart_str(u"Email"),
])
for customer in customers:
writer.writerow([
smart_str(customer.name),
smart_str(customer.last_name),
smart_str(customer.phone),
smart_str(customer.email),
])
return response
示例2: export_response
def export_response(self):
response = HttpResponse(content_type=self.export.get_content_type())
response['Content-Disposition'] = 'attachment; filename="{0}"'.format(
self.filename
)
response.write(self.export_bytes())
return response
示例3: _http_auth_helper
def _http_auth_helper(self, request):
# At this point, the user is either not logged in, or must log
# in using http auth. If they have a header that indicates a
# login attempt, then use this to try to login.
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
if auth[0].lower() == 'basic':
# Currently, only basic http auth is used.
uname, passwd = base64.b64decode(auth[1]).split(':')
user = authenticate(username=uname, password=passwd)
if user and user.is_staff:
request.session['moat_username'] = uname
return
# The username/password combo was incorrect, or not provided.
# Challenge the user for a username/password.
resp = HttpResponse()
resp.status_code = 401
try:
# If we have a realm in our settings, use this for the
# challenge.
realm = settings.HTTP_AUTH_REALM
except AttributeError:
realm = ""
resp['WWW-Authenticate'] = 'Basic realm="%s"' % realm
return resp
示例4: download_theme
def download_theme(self, request, pk):
theme = Theme.objects.get(pk=pk)
s = io.BytesIO()
with zipfile.ZipFile(s, 'w', compression=zipfile.ZIP_DEFLATED) as z:
templates = []
for template in theme.template_set.filter(enabled=True):
filename = "templates/{path}".format(
path=template.path,
pk=template.pk,
position=template.position,
enabled=template.enabled)
if template not in templates:
z.writestr(filename, template.source.encode(settings.FILE_CHARSET))
templates.append(template)
static_files = []
for static_file in theme.staticfile_set.filter(enabled=True):
filename = "static/{path}".format(
path=static_file.path,
pk=static_file.pk,
enabled=static_file.enabled)
content = static_file.file.read()
if static_file not in static_files:
z.writestr(filename, content)
static_files.append(static_file)
response = HttpResponse(content_type="application/x-zip-compressed")
response['Content-Disposition'] = 'attachment; filename=%s_theme.zip' % theme.name.lower()
response.write(s.getvalue())
return response
示例5: render_pdf
def render_pdf( self, html, filename = None ):
response = HttpResponse( content_type = self.PDF_CNT_TYPE )
w = Watch( "BaseView.render_pdf" )
w.start()
if filename == None:
filename = datetime.now().strftime( "%Y%m%d" ) + '-export.pdf'
pdf_path = settings.MEDIA_ROOT + '/pdf/contracts/' + filename
pdf_file = open( pdf_path, "w+b" )
try:
pisa.CreatePDF( html, dest = pdf_file )
except Exception as e :
print ( traceback.format_exc() )
pdf_file.seek( 0 )
pdf = pdf_file.read()
pdf_file.close()
response['Content-Disposition'] = filename
response["Cache-Control"] = "max-age=0"
response["Accept-Ranges"] = "none"
response.content = pdf
print( "Rendering PDF took :" )
print( w.display() )
return response
示例6: export_csv_photo
def export_csv_photo(modeladmin, request, queryset):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=tigatrapp_photos.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"url"),
smart_str(u"user"),
smart_str(u"report"),
smart_str(u"date"),
smart_str(u"report_lat"),
smart_str(u"report_lon"),
smart_str(u"report_note"),
smart_str(u"report_type"),
smart_str(u"report_responses"),
])
for obj in queryset:
writer.writerow([
smart_str(obj.id),
smart_str("http://%s%s" % (request.get_host(), obj.photo.url)),
smart_str(obj.user),
smart_str(obj.report),
smart_str(obj.date),
smart_str(obj.report.lat),
smart_str(obj.report.lon),
smart_str(obj.report.note),
smart_str(obj.report.type),
smart_str(obj.report.response_string),
])
return response
示例7: get
def get(self, request, *args, **kwargs):
importer = request.GET.get("importer")
file_name = request.GET.get("file_name")
if not importer or not file_name:
return HttpResponseBadRequest(_("Invalid parameters"))
importer_cls = get_importer(importer)
if not importer_cls or not importer_cls.has_example_file():
raise Http404(_("Invalid importer"))
example_file = importer_cls.get_example_file(file_name)
if not example_file:
raise Http404(_("Invalid file name"))
response = HttpResponse(content_type=example_file.content_type)
response['Content-Disposition'] = 'attachment; filename=%s' % example_file.file_name
data = importer_cls.get_example_file_content(example_file, request)
if not data:
raise Http404(_("File not found"))
data.seek(0)
response.write(data.getvalue())
return response
示例8: generar_pdf
def generar_pdf(request, message):
# message = ''
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
buffer = BytesIO()
# Create the PDF object, using the BytesIO object as its "file."
p = canvas.Canvas(buffer, pagesize=A4)
p.setLineWidth(.30)
p.setFont('Helvetica', 22)
# Draw things on the PDF. Here's where the PDF generation happens.
# See the ReportLab documentation for the full list of functionality.
p.drawString(30, 750, "Hello world. " + message)
p.drawImage('static/nao.png',440,720,100,100)
# Close the PDF object cleanly.
p.showPage()
p.save()
# Get the value of the BytesIO buffer and write it to the response.
pdf = buffer.getvalue()
buffer.close()
#startfile(pdf)
response.write(pdf)
# context = {'message' : message}
#render(request , 'prueba.html',context)
return response
示例9: postImageContent
def postImageContent(request):
userId = request.session.get(KEY_USER_ID, '')
if not userId:
return HttpResponse('你还未登录或登录已过期')
print(str(request.POST))
images = request.POST.getlist('images[]')
texts = request.POST.getlist('texts[]')
title = request.POST.get('title')
category = request.POST.get('category')
author = request.POST.get('author')
print("分类:", category)
articleType = 3 # 图文
contentType = 3 # 图文
if articleService.addImageArticle(userId, title, category, contentType, articleType, images, texts, author):
return HttpResponse(SUCCESS)
else:
response = HttpResponse(ERROR)
response.status_code = 500
return response
示例10: process_cache_response
def process_cache_response(self,
view_instance,
view_method,
request,
args,
kwargs):
key = self.calculate_key(
view_instance=view_instance,
view_method=view_method,
request=request,
args=args,
kwargs=kwargs
)
response = self.cache.get(key)
if not response:
response = view_method(view_instance, request, *args, **kwargs)
response = view_instance.finalize_response(request, response, *args, **kwargs)
response.render() # should be rendered, before picklining while storing to cache
if not response.status_code >= 400 or self.cache_errors:
response_dict = (
response.rendered_content,
response.status_code,
response._headers
)
self.cache.set(key, response_dict, self.timeout)
else:
content, status, headers = response
response = HttpResponse(content=content, status=status)
response._headers = headers
if not hasattr(response, '_closable_objects'):
response._closable_objects = []
return response
示例11: get
def get(self, request, *args, **kwargs):
response = HttpResponse(content_type="application/svg")
response['Content-Disposition'] = 'attachment; filename="planner2015.pdf"'
svg = output_svg_planner(output_format="buffer", file_format="pdf")
response.write(svg)
return response
示例12: some_view
def some_view(request,id):
envio=Envio.objects.get(pk=id)
if envio.distribuidor_id == None:
query_cliente="select c.nombre from cliente c join envio_producto ep on ep.cliente_id = c.id_cliente "\
" join envio e on e.id_envio = ep.envio_id where e.id_envio="+str(id)
cliente_nombre=execute_query(query_cliente)[0]
else:
cliente_nombre=Distribuidor.objects.get(pk=envio.distribuidor_id).nombre
query_ep="select count(*),p.codigo,ep.lote, p.nombre,p.precio from envio_producto ep"\
" join producto p on p.id_producto = ep.producto_id where ep.envio_id= "+str(id)+""\
" group by p.codigo,ep.lote,p.nombre, p.precio"
envios_productos=execute_all_query(query_ep)
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="Nota de Envio Nro. '+str(envio.nro_talonario)+'.pdf"'
buffer = BytesIO()
# Create the PDF object, using the BytesIO object as its "file."
p = canvas.Canvas(buffer,pagesize=A4)
encabezado(p,envio.nro_talonario)
cuerpo(p=p,envio=envio,envios_productos=envios_productos,cliente_nombre=cliente_nombre)
encabezado(canvas=p, nro=envio.nro_talonario, copia=True)
cuerpo(p=p, envio=envio, envios_productos=envios_productos, copia=True, cliente_nombre=cliente_nombre)
# Get the value of the BytesIO buffer and write it to the response.
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response
示例13: register
def register(request):
'''View function handling user registration.
This function parse and validate incoming request's form data and check
table auth_user for authenticity before storing user record in table or
output error message.
Args:
request: Incoming request.
Returns:
Indicator that user is successfully created or error message that either
form data is invalid or user exists.
'''
form = UserForm(request.POST)
response = HttpResponse()
if form.is_valid():
try:
user = User.objects.create_user(form.cleaned_data['name'],
password=form.cleaned_data['passwd'])
success(request, 'Successfully create user.')
except IntegrityError:
error(request, 'User name exists.')
response.status_code = 400
else:
error(request, 'Invalid input data')
response.status_code = 400
response.write(''.join([item.message for item in get_messages(request)]))
return response
示例14: attach
def attach(request, app_name):
'''View function to attach facebook/twitter account to user.
If a twitter account is to be attached, the incoming request is simply an
indicator. This function then call twitter request_token api to ask for a
temporary twitter token and twitter secret token, save it to database and
send back to the client.
Args:
request: Incoming request.
app_name: The name of social network to be attached.
Returns:
Token string if twitter token is successfully received. Error message
if network is not supported.
'''
response = HttpResponse()
if app_name == 'facebook':
success(request, 'facebook account attached')
elif app_name == 'twitter':
request_token_url = 'https://api.twitter.com/oauth/request_token'
oauth = OAuth1(client_key,
client_secret=client_secret)
r = requests.post(url=request_token_url,
auth=oauth,
data={'oauth_callback': 'http://ec2-54-173-9-169.compute-1.amazonaws.com:9090/twitter'})
twitter_query = QueryDict(r.content)
UserProfile.insert_twitter_token(twitter_query, request.user)
return HttpResponse(twitter_query['oauth_token'])
else:
error(request, 'Unsupported social network')
response.status_code = 400
response.write(''.join([item.message for item in get_messages(request)]))
return response
示例15: render_data_to_response
def render_data_to_response(self, table_data, **kwargs):
f = StringIO()
f.write(os.linesep.join([self.delimiter.join(map(str, row)) for row in table_data]))
response = HttpResponse(content_type="application/octet-stream")
response["Content-Disposition"] = "attachment; filename=%s" % urlquote(self.full_file_name)
response.write(f.getvalue())
return response