def __init__(self, status, data={}): HttpResponse.__init__( self, content=simplejson.dumps(data, cls=LazyEncoder), mimetype="application/json", status=status, )
def __init__(self, detail=None, body_template=None, comment=None, **kw): HttpResponse.__init__( self, status = '%s %s' % (self.code, self.title), **kw) Exception.__init__(self, detail) if comment is not None: self.comment = comment if body_template is not None: self.body_template = body_template if isinstance(self.explanation, (list, tuple)): self.explanation = "<p>%s</p>" % "<br>".join(self.explanation) if not self.empty_body: t = template.Template(self.body_template) c = template.Context(dict( detail=detail, explanation=self.explanation, comment=comment)) self._container = [t.render(c)] else: self._container = [''] self._is_string = True
def __init__(self, data={}, stat=0, msg='ok', errcode=200, mimetype=None, status=None, content_type=None): self.redict['stat']=stat self.redict['msg']=msg self.redict['errcode']=errcode self.redict['data']=data content=json.dumps(self.redict) HttpResponse.__init__(self, content=content, mimetype=mimetype, status=status, content_type=content_type)
def __init__(self, request, *args, **kwargs): """Instantiate a ``Resource`` instance. This method overrides ``HttpResponse.__init__``, providing an alternative way of serving views. It calls the overridden method first, to handle the initialization, and then performs a dispatch on the HTTP request method. The return values of these methods are then merged back into the current ``HttpResponse`` instance. Because this is called like a view function, this method accepts a request object and any other positional and/or keyword arguments, These will be passed to the methods defined on a subclass, so those methods should support any arguments given. If the given HTTP request method is not defined for a subclass, then a 405 'Method Not Allowed' response is returned, along with a list of allowed methods (obtained via introspection).""" HttpResponse.__init__(self) if hasattr(self, request.method.lower()): value = getattr(self, request.method.lower())(request,*args, **kwargs) if isinstance(value, HttpResponse): self._update(value) elif hasattr(self, 'run'): value = self.run(request, *args, **kwargs) if isinstance(value, HttpResponse): self._update(value) else: allowed_methods = [] for attr in dir(self): if set(attr).issubset(set(string.lowercase)): allowed_methods.append(attr.upper()) self._update(HttpResponseNotAllowed(sorted(allowed_methods)))
def __init__(self, request, redirect_to): if 'HTTP_X_HASHSIGNAL' in request.META: content = simplejson.dumps({'redirectLocation': redirect_to}) HttpResponse.__init__(self, content=content, mimetype='application/json', status=200) else: super(AjaxResponseRedirect, self).__init__(redirect_to)
def __init__(self, content='', status=None, filename=None): content_type = mimetypes.guess_type(content.name)[0] filename = filename or content.name HttpResponse.__init__(self, content = content, status = status, content_type = content_type,) self['Content-Disposition'] = 'attachment; filename=' + filename
def __init__(self, path, mimetype, offset=0, length=-1): HttpResponse.__init__(self, '', mimetype) try: file_size = os.path.getsize(path) if offset < 0 or offset >= file_size: self.status_code = 416 if length < 0 or file_size - offset < length: length = file_size - offset finally: if self.status_code != 416 and length > 0: self['Content-Length'] = str(length) if length < file_size: self['Content-Range'] = 'bytes %d-%d/%d' % ( offset, offset + length - 1, file_size) self.status_code = 206 self.path = path self.offset = offset self.length = length if self.length >= 0: self.end = self.offset + self.length else: self.end = -1 self.filelike = None self.blksize = 65536
def __init__(self, data, extra=None): data = self.notty % (data) if extra: data = "%s %s" % (data, extra) HttpResponse.__init__( self, data, mimetype='application/json' )
def __init__(self, title, queryset, fields, headers=None): HttpResponse.__init__(self, mimetype="application/ms-excel") self['Content-Disposition'] = 'attachment; filename=%s.xlsx' % title.encode('utf8') workbook = openpyxl.workbook.Workbook(optimized_write=True) worksheet = workbook.create_sheet() worksheet.title = title if headers: worksheet.append(headers) else: worksheet.append(fields) for model in queryset: result = [] for field in fields: value = getattr(model, field) value = value.strftime('%Y.%m.%d %H:%M:%S') if type(value) == datetime else value value = '' if value is None else value value = '%s' % (value) result.append(value) worksheet.append(result) f = tempfile.NamedTemporaryFile(delete=True) workbook.save(f) f.seek(0, os.SEEK_SET) self.write(f.read()) f.close()
def __init__(self, file_path): content = open(file_path, 'r+b') HttpResponse.__init__(self, content=content, content_type='application/zip') self['Content-Disposition'] = 'attachment; filename={}'.format( to_ascii(file_path.split(os.sep)[-1]))
def __init__(self, redirect_to): """ __init__ """ HttpResponse.__init__(self) str_authenticate = 'Basic realm="%s"' % Site.objects.get_current().name self['WWW-Authenticate'] = str_authenticate
def __init__(self, redirect_to): """ __init__ """ HttpResponse.__init__(self) str_authenticate = 'Basic realm="%s"' % Site.objects.get_current().name self["WWW-Authenticate"] = str_authenticate
def __init__(self, data, callback): _json = json.dumps(data) jsonp = "%s(%s)" % (callback, _json) HttpResponse.__init__( self, jsonp, content_type='application/json' )
def __init__(self, data): dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None HttpResponse.__init__(self, content=simplejson.dumps(data, default=dthandler), mimetype='application/json', )
def __init__(self, file_path): content = open(file_path) HttpResponse.__init__(self, content=content, content_type='application/zip') self[ 'Content-Disposition'] = 'attachment; filename=%s' % file_path.split( os.sep)[-1]
def __init__(self, realm: str, www_authenticate: Optional[str] = None) -> None: HttpResponse.__init__(self) if www_authenticate is None: self["WWW-Authenticate"] = f'Basic realm="{realm}"' elif www_authenticate == "session": self["WWW-Authenticate"] = f'Session realm="{realm}"' else: raise AssertionError("Invalid www_authenticate value!")
def __init__(self, dict, status=200): mimetype = 'application/json' if (settings.DEBUG): mimetype = 'text/html' HttpResponse.__init__(self, content=json_encode(dict), mimetype=mimetype, status=status)
def __init__(self, realm: Text, www_authenticate: Optional[Text]=None) -> None: HttpResponse.__init__(self) if www_authenticate is None: self["WWW-Authenticate"] = 'Basic realm="%s"' % (realm,) elif www_authenticate == "session": self["WWW-Authenticate"] = 'Session realm="%s"' % (realm,) else: raise AssertionError("Invalid www_authenticate value!")
def __init__(self, obj): self.original_obj = obj #if not obj: # self.original_obj = list(obj) #else: # self.original_obj = None HttpResponse.__init__(self, self.serialize()) self["Content-Type"] = "text/javascript; charset=utf-8"
def __init__(self, content, content_type='application/json; charset=utf-8', status=200, encoder=JSONEncoder): if isinstance(content, QuerySet): temp = serializers.serialize('python', content) data = json.dumps(temp, indent=3, cls=DjangoJSONEncoder) else: data = json.dumps(content, indent=3, cls=encoder) HttpResponse.__init__(self, data, content_type, status)
def __init__(self, retry_after = None): """ Constructor """ HttpResponse.__init__(self) if retry_after: self['Retry-After'] = retry_after
def __init__(self, retry_after=None): """ Constructor """ HttpResponse.__init__(self) if retry_after: self['Retry-After'] = retry_after
def __init__(self, content='', status=None, callback='callback', basic=BASIC_SERIALIZATION): content_type = 'application/javascript; charset=utf-8' if basic: content = json.dumps( content, default=basic_serialization, ensure_ascii=False ) else: content = json.dumps( content, default=careful_serialization, ensure_ascii=False ) HttpResponse.__init__(self, content = "%s(%s)" %(callback, content), status = status, content_type = content_type,)
def __init__(self, rows, name='Listagem'): import csv file_name = mktemp() with open(file_name, 'w', encoding='iso8859-1') as output: writer = csv.writer(output) for row in rows: writer.writerow([col for col in row]) # .encode('iso8859-1') HttpResponse.__init__(self, content=open(file_name, 'r').read(), content_type='application/csv') self['Content-Disposition'] = 'attachment; filename={}.xls'.format(to_ascii(name))
def __init__(self, location=None): """ Constructor """ HttpResponse.__init__(self) if location: self['Location'] = iri_to_uri(location)
def __init__(self, content="", status=None, content_type=None): HttpResponse.__init__( self, content=content, mimetype=mimetypes.guess_type(content.name)[0], status=status, content_type=content_type, ) self["Content-Disposition"] = "attachment; filename=" + content.name
def __init__(self, realm, www_authenticate=None): # type: (Text, Optional[Text]) -> None HttpResponse.__init__(self) if www_authenticate is None: self["WWW-Authenticate"] = 'Basic realm="%s"' % (realm, ) elif www_authenticate == "session": self["WWW-Authenticate"] = 'Session realm="%s"' % (realm, ) else: raise Exception("Invalid www_authenticate value!")
def __init__(self,status_code,error_code): ''' Constructor ''' error=Error.objects.filter(error_code=error_code) json=serializers.serialize('json', error) Response.__init__(self,json,mimetype='application/json') self.status_code=status_code
def __init__(self, code=None, data=None): ret = {} if code: ret["code"] = code else: ret["code"] = 0 if data: ret["data"] = data HttpResponse.__init__(self, json.dumps(ret))
def __init__(self, content, mimetype=None, status=None, content_type=None, **kwargs): if mimetype is None: mimetype = "application/json" content = render_to_json(content, **kwargs) HttpResponse.__init__(self, content=content, mimetype=mimetype, status=status, content_type=content_type)
def __init__(self, realm, www_authenticate=None): # type (text_type, Optional[text_type]) -> None HttpResponse.__init__(self) if www_authenticate is None: self["WWW-Authenticate"] = 'Basic realm="%s"' % (realm,) elif www_authenticate == "session": self["WWW-Authenticate"] = 'Session realm="%s"' % (realm,) else: raise Exception("Invalid www_authenticate value!")
def __init__(self, content="", mimetype=None, status=None, param="callback"): content = simplejson.dumps(content or [], indent=INDENT, ensure_ascii=False) HttpResponse.__init__( self, content="%s(%s)" % (param, content), mimetype=mimetype, status=status, content_type="application/javascript; charset=utf-8", )
def __init__(self, script): HttpResponse.__init__( self, content=""" <html> <head> <script type="text/javascript">%s</script> </head> </html> """ % script, mimetype="text/html", )
def delete(request, qr_id): item = QR.objects.get(id=qr_id) if item.owner == request.user: item.delete() res = HttpResponse() c = '{"status":"success", "id":"%s"}' % str(qr_id) res.__init__(content=c, content_type='application/json', reason=None) return res else: raise PermissionDenied
def __init__(self, redirect_to, paras=None, mimetype=None, charset=None): context = Context({ 'redirect_to': redirect_to, }) extra_context = { 'paras': paras, } context.update(extra_context) t = loader.get_template('http/post_redirect.html') HttpResponse.__init__(self, t.render(context), mimetype, charset)
def __init__(self, location = None): """ Constructor """ HttpResponse.__init__(self) if location: self['Location'] = iri_to_uri(location)
def __init__(self, message, *args, **kwargs): message = """ <html> <body> <h2>%s</h2> <p>%s</p> </body> </html> """ % (_('No way to get in!'), _(message)) HttpResponse.__init__(self, message, *args, **kwargs)
def __init__(self, request, version, entries): data = [ "CACHE MANIFEST", "# v%s" % version ] for entry in entries: data.append(entry['url']) HttpResponse.__init__(self, "\n".join(data), mimetype="text/cache-manifest")
def __init__(self,*args,**kw): self.setDefaults(self.defaultVals,kw) if not kw.has_key("entity"): raise KeyError("ResponseObjects require an entity") if not kw.has_key("content"): encoderName = "%sEncoder"%kw["encoder"] e = Encoder() data = getattr(e,encoderName)(kw["entity"]) kw["content"] = data del kw["encoder"] del kw["entity"] HttpResponse.__init__(self,*args,**kw)
def __init__(self, data, name='Listagem'): import xlwt wb = xlwt.Workbook(encoding='iso8859-1') for title, rows in data: sheet = wb.add_sheet(title) for row_idx, row in enumerate(rows): for col_idx, label in enumerate(row): sheet.write(row_idx, col_idx, label=label) file_name = mktemp() wb.save(file_name) HttpResponse.__init__(self, content=open(file_name, 'rb').read(), content_type='application/vnd.ms-excel') self['Content-Disposition'] = 'attachment; filename={}.xls'.format(to_ascii(name))
def __init__ (self , data=None,error=None): if error: self.stat = "fail" else: self.stat = "ok" self.data = data self.error = error text = self.to_json() HttpResponse.__init__(self,text)
def __init__(self, data, pretty=False, content_type="application/json"): if pretty: HttpResponse.__init__(self, content=json.dumps(data, cls=JSONEncoder), content_type=content_type) else: HttpResponse.__init__(self, content=json.dumps(data, cls=JSONEncoder, indent=4, sort_keys=True), content_type=content_type)
def __init__(self, *, content=None, headers=None, **kwargs): HttpResponse.__init__(self, content or "", status=self.status_code, **kwargs) headers = headers or {} for key, value in headers.items(): self[key] = value self._reason_phrase = self._reason_phrase or self.reason if not (self.content or self.empty_body): self.content = "{}: {}".format( self.status_code, self.reason_phrase).encode(self.charset) Exception.__init__(self, self.reason_phrase)
def __init__(self, rows, name='Listagem'): import unicodecsv import StringIO output = StringIO.StringIO() delimiter = os.sep == '/' and ',' or ';' writer = unicodecsv.writer(output, delimiter=delimiter, encoding='iso8859-1') for row in rows: writer.writerow(row) HttpResponse.__init__(self, content=output.getvalue(), content_type='application/csv') self['Content-Disposition'] = 'attachment; filename=%s.xls' % name
def __init__(self, content=None, verbose = False, **kwargs): if content is None: content = self.default_content elif isinstance( content, dict): c = {} c.update(self.default_dict) c.update(content) content = JSONDict(c).out() elif isinstance( content, JSONDict ): content = content.out() if verbose: print content HttpResponse.__init__( self, content, content_type = 'text/plain', **kwargs )
def __init__(self, content='', mimetype='application/json', charset=settings.DEFAULT_CHARSET, ensure_ascii=False, indent=None): self._json_ensure_ascii = ensure_ascii self._json_indent = indent if isinstance(content, basestring): HttpResponse.__init__(self, content, content_type='%s; charset=%s' % (mimetype, charset)) else: HttpResponse.__init__(self, simplejson.dumps(content, ensure_ascii=self._json_ensure_ascii, indent=self._json_indent), content_type='%s; charset=%s' % (mimetype, charset))
def __init__(self, data, name='Listagem'): import xlwt import StringIO output = StringIO.StringIO() wb = xlwt.Workbook(encoding='iso8859-1') for title, rows in data: sheet = wb.add_sheet(title) for row_idx, row in enumerate(rows): for col_idx, label in enumerate(row): sheet.write(row_idx, col_idx, label=label) wb.save(output) HttpResponse.__init__(self, content=output.getvalue(), content_type='application/vnd.ms-excel') self['Content-Disposition'] = 'attachment; filename=%s.xls' % name
def __init__(self, html, landscape=False): import pdfkit file_name = tempfile.mktemp('.pdf') if landscape: html = html.replace('logo_if_portrait', 'logo_if_landscape') html = html.replace('content="Portrait"', 'content="Landscape"') html = html.replace('/media', settings.MEDIA_ROOT) html = html.replace( '/static', '{}/{}/static'.format(settings.BASE_DIR, settings.PROJECT_NAME)) pdfkit.from_string(html, file_name) #from weasyprint import HTML, CSS #HTML(string=html).write_pdf(file_name) str_bytes = open(file_name, "rb").read() os.unlink(file_name) HttpResponse.__init__(self, str_bytes, content_type='application/pdf')
def __init__(self, html, landscape=False): from xhtml2pdf import pisa def link_callback(uri, rel): s = '{}/{}'.format(settings.MEDIA_ROOT, uri.replace('/media', '')) return s tmp = tempfile.NamedTemporaryFile(mode='w+b', delete=False) file_name = tmp.name if landscape: html = html.replace('a4 portrait', 'a4 landscape') html = html.replace('logo_if_portrait', 'logo_if_landscape') out = pisa.CreatePDF(html, tmp, link_callback=link_callback) out.dest.close() tmp = open(file_name, "rb") str_bytes = tmp.read() os.unlink(file_name) HttpResponse.__init__(self, str_bytes, content_type='application/pdf')
def post(self, request): jsonData = request.read() data = json.loads(jsonData) barcodeNumber = data['barcodeNumber'] vendorNameIn = data['vendorName'] if barcodevalidator.validateBarcode(barcodeNumber): barcodevalidator.insertToken(barcodeNumber, vendorNameIn) return HttpResponse.__init__(content='success', content_type=text, status=200, reason=None, charset=None) else: return HttpResponse.__init__(content='failure', content_type=text, status=401, reason=None, charset=None)
def get(self, request): try: numberOfTokens = barcodevalidator.countToken( startDateIn, endDateIn, barcodeIn) tokenCount = {'tokencount': numberOfTokens} jsonTokenCount = json.dumps(tokenCount) return JsonResponse(jsonTokenCount) except ValueError: return HttpResponse.__init__(content='failure', content_type=text, status=400, reason=None, charset=None)
def __init__(self, content='', mimetype=None, status=None, content_type=None, request=None): if isinstance(status, basestring): (status_code, status_reason) = status.split(" ", 1) status_code = int(status_code) self.status_reason = status_reason or None else: status_code = status self.status_reason = None self.request = request self._headerlist = [] HttpResponse.__init__(self, content=content, mimetype=mimetype, status=status_code, content_type=content_type)
def __init__(self, dictonary): if dictonary is None: HttpResponse.__init__(self, status=500) return if dictonary['success']: HttpResponse.__init__(self, status=200) return # TODO: Find smarter way to just define a parameter, if an expression is true. if dictonary['error'] is not None: HttpResponse.__init__(self, status=dictonary['http_status'], reason = dictonary['error']) return else: HttpResponse.__init__(self, status=dictonary['http_status']) return
def __init__(self): HttpResponse.__init__(self) self['WWW-Authenticate'] =\ 'Basic realm="%s"' % Site.objects.get_current().name