本文整理汇总了Python中django.http.response.HttpResponse.write方法的典型用法代码示例。如果您正苦于以下问题:Python HttpResponse.write方法的具体用法?Python HttpResponse.write怎么用?Python HttpResponse.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.response.HttpResponse
的用法示例。
在下文中一共展示了HttpResponse.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: some_view
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例2: healthcheck
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
def healthcheck(request):
"""Simple view to display the result of defined
healthchecks
:param request: django request
:return: Django response containing text/plain
"""
# dictionary containing functions to be called
checks = {'DB': _test_db_connection,
'Topics': _test_topics_connection,
'Events search': _test_events_search}
response = HttpResponse()
overall_ok = True
for name, service in checks.iteritems():
try:
# run the healthcheck function
ok, message = service()
except Exception as e:
ok = False
message = e
logger.error('Error in healthcheck {name}'.format(name=name), exc_info=True)
if not ok:
overall_ok = False
response.write('* !! {service}: {text}\n'.format(service=name, text=message))
else:
response.write('* {service}: {text}\n'.format(service=name, text=message.replace('\n', '')))
response['Content-Type'] = "text/plain; charset=utf-8"
response['Cache-Control'] = "must-revalidate,no-cache,no-store"
if overall_ok:
response.status_code = 200
else:
response.status_code = 500
return response
示例3: exportCSV
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例4: render_data_to_response
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例5: download_theme
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例6: log_in
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
def log_in(request):
'''View function corresponding to url /login.
The purpose of this function vary with http method. If method is GET it
behaves as unauthorize redirect destination; If method is POST it accepts
request's form data, validates it and adds session to authorize the user.
Args:
request: Incoming request
Returns:
When GET, indicate the page has been redirected here; When POST,
return either message that user is logged in or error that form invalid
or user name/password error.
'''
response = HttpResponse()
if request.method == 'GET':
info(request, 'Indicator')
else:
form = UserForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['name'],
password=form.cleaned_data['passwd'])
if user != None:
login(request, user)
success(request, 'User exists.')
else:
error(request, 'User does not exist.')
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
示例7: register
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例8: get
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例9: export
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
def export(request):
'''
导出巡检报告
'''
response = HttpResponse(content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=data.txt'
report_list = Report.objects.all()
logger.info(u'获得所有报告')
parser = Parser(logger)
i = 1
seperator = '#'
for report in report_list:
pass_rate = float(report.pass_num) / float(report.total_num)
str_pass_rate = str(int(pass_rate * 100)) + '%'
#获得巡检报告在服务器的目录
report_dir = settings.MEDIA_ROOT + report.system + os.path.sep + report.province + os.path.sep + report.reporter
time_str = os.path.dirname(report.report_path)[-17:]
time_str.replace('\\',os.path.sep)
report_dir = report_dir + os.path.sep + time_str
detail_info = parser.parse_outputxml(report_dir + os.path.sep + 'output.xml')
if detail_info == '':
#确少详细信息的记录不导出
continue
response.write(str(i) + seperator + report.system + seperator \
+ report.province + seperator + report.city + seperator \
+ str(report.total_num) + seperator + str(report.pass_num) + seperator \
+ str_pass_rate + seperator + report.sub_time.strftime("%Y-%m-%d") \
+ seperator + report.reporter + seperator + ' ' + seperator + ' ' + detail_info + seperator)
i += 1
return response
示例10: export_csv_photo
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例11: get
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例12: attach
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例13: generar_pdf
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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
示例14: response_for_download
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
def response_for_download(report, cd_value='attachment'):
"""
Preparing response for downloading file
Content-Disposition header field from http://tools.ietf.org/html/rfc2183
:param: report - instance of Report model
:param: cd_value - Content Disposition Value:
"attachment" - for download
"inline" - for preview
:return: HttpResponse with report.file and some parameters
"""
path = report.file.path
fileExt = os.path.splitext(report.filename)[1] # [0] returns path+filename
ct = get_mimeType().get(fileExt.lower(), "application/octet-stream")
filename = report.filename
cdv = '%s; ' % cd_value
fn = 'filename="%s"; ' % transliterate(filename)
fns = "filename*=utf-8''%s; " % urlquote(filename)
md = 'modification-date="%s"; ' % report.uploaded_on
response = HttpResponse(content_type=ct)
# content = report.file.read()
with open(path, 'rb') as file:
content = file.read() # читаємо файл незалежно від report
# (інакше при тестуванні не завжди
# вдається видалити тимчасовий файл)
response.write(content)
response['Content-Disposition'] = cdv + fn + fns + md
response['Content-Length'] = report.file.size
return response
示例15: export_response
# 需要导入模块: from django.http.response import HttpResponse [as 别名]
# 或者: from django.http.response.HttpResponse import write [as 别名]
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