Пример #1
0
def download(request):
    suid = request.matchdict['suid']
    rev = request.matchdict.get('rev')
    root = get_root()
    config = solr_config(root)
    query = Term('suid', suid)
    if rev:
        query = query & Term('revision', rev)
    else:
        query = query & Term('state', 'active')
    query = query & Term('visibility', 'anonymous')
    md = Metadata(config, SOLR_FIELDS)
    fl = 'effective,expires,physical_path,mimetype,filename'
    result = md.query(q=query, fl=fl)
    if len(result) != 1:
        raise MDBError(u'Dataset not found in SOLR. Query: %s' % query)
    md = result[0]
    if not chk_publication(md):
        raise MDBError(u'Item not effective or already expired')
    physical_path = u'/xsendfile%s.binary' % md['physical_path']
    response = Response()
    response.content_type = md['mimetype']
    response.content_disposition = \
        'attachment; filename=%s' % md['filename']
    response.headers.add('X-Accel-Redirect', physical_path)
    return response
Пример #2
0
def xls_response(rows, encoding='ISO-8859-1', filename='response.xls', num_formats=(), col_widths=()):
    """Creates a downloadable webob.Response instance with the given row data
    as an XLS (Excel) file.

    :param rows: The spreadsheet data as rows.
    :type rows: iterable

    :param encoding: The character encoding for the data in the spreadsheet.
    :type encoding: str

    :param filename: The suggested filename for the user to save the file as.
    :type filename: str

    :param num_formats: A tuple of Excel format strings for numeric values.
    :type num_formats: tuple
    """
    stream = StringIO()

    wb = xlwt.Workbook(encoding=encoding)
    ws = wb.add_sheet('Nuorisovaalit 2011')

    # Compile the style objects
    styles = []
    for fmt in num_formats:
        if fmt is None:
            styles.append(None)
        else:
            styles.append(xlwt.easyxf(num_format_str=fmt))

    # Set column formatting styles.
    if len(rows) > 0 and len(num_formats) == len(rows[0]):
        for c in xrange(len(rows[0])):
            if styles[c] is not None:
                ws.col(c).set_style(styles[c])

    # Set column widths.
    if len(rows) > 0 and len(col_widths) == len(rows[0]):
        for c in xrange(len(rows[0])):
            if col_widths[c] is not None:
                ws.col(c).width = col_widths[c]

    for r, row in enumerate(rows):
        for c, item in enumerate(row):
            if len(styles) == len(row) and styles[c] is not None:
                ws.write(r, c, item, styles[c])
            else:
                ws.write(r, c, item)

    wb.save(stream)

    response = Response()
    response.body = stream.getvalue()
    stream.close()

    # Set Response headers.
    response.content_type = 'application/vnd.ms-excel'
    response.content_type_params = {}
    response.content_disposition = 'attachment; filename={0}'.format(filename)

    return response
Пример #3
0
def download_png(environ, *args, **kwargs):
    """ """
    required = ['datasets', 'x1', 'y1', 'x2', 'y2', 'resolution']
    missing = [x for x in required if x not in kwargs or 0 >= len(x)]
    if 0 < len(missing):
        msg = '{}  parameter(s) must be present in the request'
        msg = msg.format(', '.join(missing))
        return {'ok': False, 'details': msg}

    if 'SERVER_HOST' not in environ:
        msg = 'Webserver misconfigured: missing SERVER_HOST environment variable'
        return {'ok': False, 'details': msg}

    with storage_type.get_session() as storage:
        results = syntool_metadata.extract.get(root_dir,
                                               kwargs['datasets'].split(','),
                                               float(kwargs['x1']),
                                               float(kwargs['y1']),
                                               float(kwargs['x2']),
                                               float(kwargs['y2']),
                                               float(kwargs['resolution']),
                                               'PNG', environ['SERVER_HOST'],
                                               download_dir, storage)
    with open(results, 'r') as f:
        content = f.read()

    n = datetime.datetime.now()
    default_filename = 'syntool-archive-{}.tgz'.format(
        n.strftime('%Y%m%d_%H%M%S'))
    r = Response()
    r.body = content
    r.content_type = 'application/octet-stream'
    r.content_disposition = 'attachement; filename={}'.format(default_filename)
    r.content_description = 'File transfer'
    return r
Пример #4
0
 def do_download(self, req):
     """
     Send the library as a .zip archive
     """
     archive = self.library.archive()
     size = archive.seek(0, io.SEEK_END)
     archive.seek(0)
     resp = Response()
     resp.content_type = 'application/zip'
     resp.content_length = size
     resp.content_disposition = 'attachment; filename=images.zip'
     resp.app_iter = FileWrapper(archive)
     return resp
Пример #5
0
 def do_download(self, req):
     """
     Send the library as a .zip archive
     """
     archive = self.library.archive()
     size = archive.seek(0, io.SEEK_END)
     archive.seek(0)
     resp = Response()
     resp.content_type = 'application/zip'
     resp.content_length = size
     resp.content_disposition = 'attachment; filename=images.zip'
     resp.app_iter = FileWrapper(archive)
     return resp
Пример #6
0
    def csv_export_handler(self, request, suffix=''):  # pylint: disable=unused-argument
        """
        Endpoint that handles CSV downloads.
        """
        if not self.runtime.user_is_staff:
            return Response('not allowed', status_code=403)

        track = request.GET.get('track', None)
        cohort = request.GET.get('cohort', None)

        buf = io.StringIO()
        ScoreCSVProcessor(block_id=str(self.location),
                          max_points=self.weight,
                          display_name=self.display_name,
                          track=track,
                          cohort=cohort).write_file(buf)
        resp = Response(buf.getvalue())
        resp.content_type = 'text/csv'
        resp.content_disposition = 'attachment; filename="%s.csv"' % self.location
        return resp
Пример #7
0
def csv_response(rows, encoding='ISO-8859-1', filename='response.csv'):
    """Create a downloadable webob.Response instance with the given
    row data as a CSV file.
    """
    stream = StringIO()
    writer = csv.writer(stream, dialect='excel')
    for row in rows:
        # Encode all columns in the row since the csv.writer cannot
        # handle Unicode objects.
        writer.writerow([unicode(s).encode(encoding) for s in row])

    response = Response()
    response.body = stream.getvalue()
    stream.close()

    # Set Response headers.
    response.charset = encoding
    response.content_type = 'text/csv'
    response.content_disposition = 'attachment; filename={0}'.format(filename)

    return response
    def getResponse(self):
        rspD = self.__getD()
        #
        #  Build the WebOb response -
        #
        myResponse = Response()
        myResponse.status = rspD["STATUS_CODE"]
        myResponse.content_type = rspD["CONTENT_TYPE"]

        if isinstance(rspD["RETURN_STRING"], text_type):
            myResponse.text = rspD["RETURN_STRING"]
        else:
            myResponse.body = rspD["RETURN_STRING"]

        if "ENCODING" in rspD:
            myResponse.content_encoding = rspD["ENCODING"]
        if "DISPOSITION" in rspD:
            myResponse.content_disposition = rspD["DISPOSITION"]
        if "CHECKSUM_MD5" in rspD:
            myResponse.headers.add("CHECKSUM_MD5", rspD["CHECKSUM_MD5"])
        #
        return myResponse
Пример #9
0
 def download_csv(self, request, suffix=''):
     response = Response(content_type='text/csv')
     response.app_iter = self.get_csv()
     response.content_disposition = 'attachment; filename=course_data.csv'
     return response
Пример #10
0
 def download_csv(self, request, suffix=''):
     response = Response(content_type='text/csv')
     response.app_iter = self.get_csv()
     response.content_disposition = 'attachment; filename=course_data.csv'
     return response
Пример #11
0
def xls_response_multiple(sheets, encoding='ISO-8859-1', filename='response.xls', num_formats=(), col_widths=()):
    """Creates a downloadable webob.Response instance with the given row data
    as an XLS (Excel) file.

    :param sheets: The spreadsheet data as an iterable of (sheet_name,
                   rows) tuples with the row data of a sheet in the
                   rows iterable.
    :type sheets: iterable

    :param encoding: The character encoding for the data in the spreadsheet.
    :type encoding: str

    :param filename: The suggested filename for the user to save the file as.
    :type filename: str

    :param num_formats: A tuple of Excel format strings for numeric values.
    :type num_formats: tuple
    """
    wb = xlwt.Workbook(encoding=encoding)

    # Compile the style objects
    styles = []
    for fmt in num_formats:
        if fmt is None:
            styles.append(None)
        else:
            styles.append(xlwt.easyxf(num_format_str=fmt))

    if not sheets:
        wb.add_sheet(u'Tyhjä taulukko')

    for sheet_name, rows in sheets:

        # Worksheet name must not be longer than 31 characters.
        if len(sheet_name) > 31:
            sheet_name = sheet_name[:31]

        # Create a new sheet and write to it.
        ws = wb.add_sheet(sheet_name)

        # Set column widths.
        if len(rows) > 0 and len(col_widths) == len(rows[0]):
            for c in xrange(len(rows[0])):
                if col_widths[c] is not None:
                    ws.col(c).width = col_widths[c]

        for r, row in enumerate(rows):
            for c, item in enumerate(row):
                if len(styles) == len(row) and styles[c] is not None:
                    ws.write(r, c, item, styles[c])
                else:
                    ws.write(r, c, item)

    stream = StringIO()
    wb.save(stream)

    response = Response()
    response.body = stream.getvalue()
    stream.close()

    # Set Response headers.
    response.content_type = 'application/vnd.ms-excel'
    response.content_type_params = {}
    response.content_disposition = 'attachment; filename={0}'.format(filename)

    return response