Exemplo n.º 1
0
    def whitenoise_tween(request):
        whn = request.registry.whitenoise

        if whn.autorefresh:
            static_file = whn.find_file(request.path_info)
        else:
            static_file = whn.files.get(request.path_info)

        # We could not find a static file, so we'll just continue processing
        # this as normal.
        if static_file is None:
            return handler(request)

        request_headers = dict(kv for kv in request.environ.items() if kv[0].startswith("HTTP_"))

        if request.method not in {"GET", "HEAD"}:
            return HTTPMethodNotAllowed()
        else:
            path, headers = static_file.get_path_and_headers(request_headers)
            headers = MultiDict(headers)

            resp = FileResponse(
                path,
                request=request,
                content_type=headers.pop("Content-Type", None),
                content_encoding=headers.pop("Content-Encoding", None),
            )
            resp.md5_etag()
            resp.headers.update(headers)

            return resp
Exemplo n.º 2
0
 def photo_view(self):
     # Check agreements
     if not self.user.purchase_agreement:
         return HTTPFound(location=self.request.route_path("purchase_agreement_act"))
     elif not self.user.privacy_agreement:
         return HTTPFound(location=self.request.route_path("privacy_policy_act"))
     base_path = self.request.registry._settings["base_dir"]
     if "tick_id" in self.request.matchdict:
         tick_id = self.request.matchdict["tick_id"]
         ticket = None
         # Find ticket
         for tick in self.user.tickets:
             if tick.__name__ == tick_id:
                 ticket = tick
                 break
         # Safety
         if ticket == None:
             return FileResponse(os.path.join(base_path, "data/profile_images", "blank.png"), request=self.request)
         else:
             file_name = ticket.guest_info.photo_file
             if os.path.isfile(os.path.join(base_path, "data/profile_images", file_name)):
                 return FileResponse(os.path.join(base_path, "data/profile_images", file_name), request=self.request)
             else:
                 return FileResponse(os.path.join(base_path, "data/profile_images", "blank.png"), request=self.request)
     else:
         file_name = self.user.profile.photo_file
         if os.path.isfile(os.path.join(base_path, "data/profile_images", file_name)):
             return FileResponse(os.path.join(base_path, "data/profile_images", file_name), request=self.request)
         else:
             return FileResponse(os.path.join(base_path, "data/profile_images", "blank.png"), request=self.request)
Exemplo n.º 3
0
def monitor(request):
    pagename = request.matchdict['id']
    page = Page.select(request, pagename)
    response_settings = {'project': 'Michelanglo', 'user': request.user,
                         'page': pagename,
                         'custom_messages': json.dumps(custom_messages),
                         'meta_title': 'Michelaɴɢʟo: sculpting protein views on webpages without coding.',
                         'meta_description': 'Convert PyMOL files, upload PDB files or submit PDB codes and ' + \
                                             'create a webpage to edit, share or implement standalone on your site',
                         'meta_image': '/static/tim_barrel.png',
                         'meta_url': 'https://michelanglo.sgc.ox.ac.uk/'
                         }
    verdict = permission(request, page, 'view', key_label='key')
    if verdict['status'] != 'OK':
        request.response.status_int = 400
        return render_to_response("../templates/404.mako", response_settings,
                                  request)
    elif 'image' in request.params:
        if 'current' in request.params and is_js_true(
                request.params['current']):
            file = os.path.join(
                'michelanglo_app', 'user-data-monitor',
                f"tmp_{page.identifier}-{request.params['image']}.png")
        else:
            file = os.path.join(
                'michelanglo_app', 'user-data-monitor',
                f"{page.identifier}-{request.params['image']}.png")
        if page.protected and os.path.exists(file):
            return FileResponse(file)
        else:
            print(file, os.path.exists(file))
            return FileResponse(
                os.path.join('michelanglo_app', 'static', 'broken.gif'))
    elif not page.protected:
        return {'status': 'unprotected', **response_settings}
    else:
        labelfile = os.path.join(
            'michelanglo_app', 'user-data-monitor', page.identifier +
            '.json')  ## this is not within hth pickle as nodejs makes it.
        verdictfile = os.path.join('michelanglo_app', 'user-data-monitor',
                                   'verdict_' + page.identifier + '.p')
        if os.path.exists(labelfile):
            labels = json.load(open(labelfile))
            if os.path.exists(verdictfile):
                validity = pickle.load(open(verdictfile, 'rb'))
                return {
                    'status': 'monitoring',
                    'labels': labels,
                    'validity': validity,
                    **response_settings
                }
            else:
                return {
                    'status': 'monitoring',
                    'labels': labels,
                    'validity': [None for l in labels],
                    **response_settings
                }
        else:
            return {'status': 'generating', **response_settings}
Exemplo n.º 4
0
def cards_table(request):
    if not security.authenticated_userid(request):
        raise exc.HTTPForbidden()

    output_format = request.GET['format']

    result = cards_jtable_browse(request)

    if output_format not in _get_formats():
        raise exc.HTTPException('Format "' + output_format + '" not supported')

    file_object = NamedTemporaryFile(suffix='.' + output_format)
    content_type = ''
    content_disposition = ''

    if output_format == 'pdf':
        _make_pdf(result, file_object, request)
        content_type = 'application/pdf'
        content_disposition = 'attachment; filename="{}"'.format('cards.pdf')

    if output_format == 'csv':
        _make_csv(result, file_object)
        content_type = 'text/csv'
        content_disposition = 'attachment; filename="{}"'.format('cards.csv')

    if output_format == 'docx':
        _make_docx(result, file_object)
        content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        content_disposition = 'attachment; filename="{}"'.format('cards.docx')

    file_response = FileResponse(os.path.abspath(file_object.name), content_type=content_type)
    file_response.content_disposition = content_disposition
    return file_response
Exemplo n.º 5
0
def artifact_download(request, inline):
    af = get_artifact(request)

    if af.is_bundle:
        if inline:
            raise HTTPBadRequest("Inline view not supported for bundles")
        # We have a bundle. So we need to prepare a zip (unless we already have one)
        disk_name = af.file
        # Locking on a separate file since zipfile did not want to write to the
        # same file we are locking on. It just means that we need to clean up
        # that file at the same time as the main cache file.
        with portalocker.Lock(disk_name + ".lock", timeout=300, check_interval=1):
            if not os.path.exists(disk_name):
                with zipfile.ZipFile(disk_name, 'w', compression=zipfile.ZIP_BZIP2) as _zip:
                    for cf in af.artifacts:
                        _zip.write(cf.file, arcname=cf.bundle_filename(af))
        file_name = af.name + ".zip"
    else:
        disk_name = af.file
        file_name = af.filename

    mime, encoding = mimetypes.guess_type(file_name)
    if mime is None:
        mime = ('text/plain' if inline else 'application/octet-stream')
    # If the current simple approach proves to be a problem the discussion
    # at http://stackoverflow.com/q/93551/11722 can be considered.
    response = FileResponse(disk_name, request=request, content_type=mime)
    response.content_disposition = '{}; filename="{}"'.format('inline' if inline else 'attachment', file_name)
    # Specifically needed for jquery.fileDownload
    response.set_cookie('fileDownload', 'true')
    return response
Exemplo n.º 6
0
Arquivo: vfs.py Projeto: ableeb/WebOOT
 def content(self):
     filename = abspath(self.format)
     response = FileResponse(filename)
     response.headers['Content-type'] = 'application/octet-stream'
     response.headers['Content-Disposition'] = 'attachment; filename="{0}";'.format(
         basename(filename))
     return response
Exemplo n.º 7
0
def download_log(request):
    sys_mgr = sysinfo.sys_mgr()      # get sys manager
    sys_mgr.rm_sys_log()   # rm the exist tar log file
    log_tar_file = sys_mgr.tar_sys_log()
    response = FileResponse(log_tar_file, request=request, content_type='application/force-download')
    response.headers['Content-Disposition'] = 'attachment; filename=%s' % (os.path.basename(log_tar_file))
    return response
Exemplo n.º 8
0
def download(context, request):
    path = open_file(context.filesystem_path).name
    response = FileResponse(path=path, request=request,
        content_type=context.mimetype)
    response.headers['Content-Disposition'] = ('attachment; filename="%s"' %
        context.filename)
    return response
Exemplo n.º 9
0
    def whitenoise_tween(request):
        whn = request.registry.whitenoise

        if whn.autorefresh:
            static_file = whn.find_file(request.path_info)
        else:
            static_file = whn.files.get(request.path_info)

        # We could not find a static file, so we'll just continue processing
        # this as normal.
        if static_file is None:
            return handler(request)

        request_headers = dict(kv for kv in request.environ.items()
                               if kv[0].startswith("HTTP_"))

        if request.method not in {"GET", "HEAD"}:
            return HTTPMethodNotAllowed()
        else:
            path, headers = static_file.get_path_and_headers(request_headers)
            headers = MultiDict(headers)

            resp = FileResponse(
                path,
                request=request,
                content_type=headers.pop("Content-Type", None),
                content_encoding=headers.pop("Content-Encoding", None),
            )
            resp.md5_etag()
            resp.headers.update(headers)

            return resp
Exemplo n.º 10
0
def download_file(context, request):
    registration_info = FileRegistry.get_registration_info(
        request.matchdict['reg_id'])
    file_path = registration_info[
        HPZ.FILE_PATH] if registration_info is not None else None
    file_name = registration_info[
        HPZ.FILE_NAME] if registration_info is not None else None

    is_valid_file = validate_file(request)
    dev_mode = request.registry.settings['mode'] == 'dev'
    if is_valid_file and dev_mode:
        response = FileResponse(file_path, request=request)
        response.content_disposition = 'attachment; filename={}'.format(
            file_name)
        logger.info('File %s was successfully served in local environment',
                    file_path)
    elif is_valid_file:
        response = Response(
            headers={
                'X-Sendfile': file_path,
                'Content-Type': '',
                'Content-Disposition': 'attachment; filename={}'.format(
                    file_name),
            })
        logger.info('File %s was successfully downloaded', file_path)
    else:
        response = Response(status_code=404)
    return response
Exemplo n.º 11
0
 def proxy_or_redirect_download(self):
     request = self.request
     item_id = request.matchdict['id']
     item_table = request.matchdict['table']
     switcher = {
         "cia": CIA,
         "tdsx": TDSX,
         "arm9": ARM9,
         "smdh": SMDH,
         "xml": XML
     }
     item = DBSession.query(switcher.get(item_table, None)).get(item_id)
     if item:
         if item.path:
             # Verify cache file is there and valid.
             if verify_cache(item, settings=request.registry.settings):
                 filename = item.path.split('/')[-1]
                 response = FileResponse(
                     os.path.join(
                         url_to_cache_path(
                             item.url.url,
                             request.registry.settings['titledb.cache']),
                         'archive_root', item.path),
                     request=request,
                     content_type=mimetypes.guess_type(filename)[0])
                 response.content_disposition = 'attachment; filename="%s"' % filename
                 return response
             else:
                 return Response('404 Not Found', status='404 Not Found')
         else:
             return HTTPFound(location=item.url.url)
     return Response('404 Not Found', status='404 Not Found')
Exemplo n.º 12
0
    def handleReq(self, session):
        full_share_uuid = self.req.matchdict["id"]

        if "-" in full_share_uuid:
            try:
                share_uuid, share_index = full_share_uuid.split("-")
                share_index = int(share_index)
            except Exception:
                raise NotFound(f"Invalid share id: {full_share_uuid}")
        else:
            share_uuid = full_share_uuid
            share_index = 0

        row = session.query(ShareEntry).\
              filter(ShareEntry.uuid == share_uuid).one_or_none()
        if not row:
            raise NotFound(f"Invalid share id: {full_share_uuid}")

        if row.album_id:
            if share_index < len(row.album.tracks):
                path = row.album.tracks[share_index].path
        elif row.track_id:
            path = row.track.path
        elif row.playlist_id:
            if share_index < len(row.playlist.tracks):
                path = row.playlist.tracks[share_index].path
        else:
            raise NotFound(f"Invalid share id: {full_share_uuid}")

        resp = FileResponse(path)
        resp.content_type = "audio/mp3"
        return resp
Exemplo n.º 13
0
def export_to_moe_view(request):
    import io, re
    from tempfile import NamedTemporaryFile
    import xlwt
    from pyramid_sqlalchemy import Session
    from ..models import NewStudentModel
    from pyramid.response import FileResponse

    with NamedTemporaryFile(delete=True) as f:
        
        wb = xlwt.Workbook()
        ws = wb.add_sheet('sheet1')
        ws.write(0, 0, '姓名')
        ws.write(0, 1, '身分證號')

        regex = re.compile(r'^[A-Z]\d{9}$') # 比對是否為身分證號
        
        counter = 1
        for each_new_student in Session.query(NewStudentModel).filter(NewStudentModel.status==1):
            if regex.match(each_new_student.id_number):
                ws.write(counter, 0, each_new_student.name)
                ws.write(counter, 1, each_new_student.id_number)
                counter += 1

        wb.save(f.name)

        f.flush()
        f.seek(0)

        response = FileResponse(f.name)
        response.content_type = 'application/octet-stream'
        response.content_disposition = 'attachment; filename="moe.xls"'
        
        return response
Exemplo n.º 14
0
def download_view(request):
    session = request.session
    set_language(request)
    lang = get_language(request)
    if "fileName" in request.params or "filename" in request.params:
        if "fileName" in request.params:
            filename = request.params['fileName']
        else:
            filename = request.params['filename']
        if "results" in request.params:
            response = FileResponse(os.path.join(config['homepath'],
                                                 'documents/download/results',
                                                 filename),
                                    request=request)
        else:
            try:
                dir_file = os.path.join(config['homepath'],
                                        'documents/download', filename)
                response = FileResponse(dir_file, request=request)
            except FileNotFoundError as e:
                log.error('File not found: {}'.format(dir_file))
                result = render('templates/%s/error.pt' % lang, {
                    'err_title':
                    messages['errors']['file_not_found'][lang]['err_title'],
                    'err_text':
                    messages['errors']['file_not_found'][lang]
                    ['err_text'].format(filename)
                },
                                request=request)
                return Response(result)
    response.headers['Content-Disposition'] = ('attachment; filename=' +
                                               filename)
    return response
Exemplo n.º 15
0
def zip_response_adv(request, filename, files):
    """Return a Response object that is a zipfile with name filename.

    :param request: The request object.
    :param filename: The filename the browser should save the file as.
    :param files: A list of tupples mapping 
        (type, name in zip, filepath or content) 
        i.e.
        ('file', name in zip, './myfile.txt')
        ('text', name in zip, 'a.out foo bar baz the quick fox jumps over the lazy dog')
        only supported types are 'file' and 'text'
    """
    tmp_file = NamedTemporaryFile()
    try:
        with ZipFile(tmp_file, 'w') as zip_file:
            for type, zip_path, actual in files:
                if type == "file":
                    zip_file.write(actual, zip_path)
                else:
                    zip_file.writestr(zip_path, actual)
        tmp_file.flush()  # Just in case
        response = FileResponse(tmp_file.name, request=request,
                                content_type=str('application/zip'))
        response.headers['Content-disposition'] = ('attachment; filename="{0}"'
                                                   .format(filename))
        return response
    finally:
        tmp_file.close() 
Exemplo n.º 16
0
def file_serve(request):
    serve_engine = request.registry.settings.get('serve_engine', 'local')

    try:
        t = Token.get_by_urlid(request.matchdict.get('token'))
    except NoResultFound:
        return HTTPNotFound()

    f = t.upload.file

    if serve_engine == 'nginx':
        print(f.get_file_path())
        headers = request.response.headers
        headers['Content-Disposition'] = str(f.filename)
        headers['Content-Type'] = 'application/force-download'
        headers['Accept-Ranges'] = 'bytes'
        headers['X-Accel-Redirect'] = '/getfile/'+f.hash+';'
        return request.response
    else:
        fr = FileResponse(
            f.get_file_path(),
            request=request,
            content_type=str(f.mime)
            )

        fr.content_disposition = 'filename="{0}"'.format(str(f.filename))

        return fr
Exemplo n.º 17
0
def download_amendements(context: LectureResource, request: Request) -> Response:
    fmt: str = request.params.get("format", "")
    if fmt not in DOWNLOAD_FORMATS.keys():
        raise HTTPBadRequest(f'Invalid value "{fmt}" for "format" param')

    if fmt == "pdf":
        options = PDF_OPTIONS
    else:
        options = EXPORT_OPTIONS

    lecture = context.model(*options)

    with NamedTemporaryFile() as file_:

        tmp_file_path = os.path.abspath(file_.name)

        write_func, content_type = DOWNLOAD_FORMATS[fmt]
        write_func(lecture, tmp_file_path, request)  # type: ignore

        response = FileResponse(tmp_file_path)
        attach_name = (
            f"lecture-{lecture.chambre}-{lecture.texte.numero}-"
            f"{lecture.organe}.{fmt}"
        )
        response.content_type = content_type
        response.headers["Content-Disposition"] = f"attachment; filename={attach_name}"
        return response
Exemplo n.º 18
0
def get_movie(request):
    movie = session.query(Movie).filter(Movie.movie_id == request.matchdict['movie_id']).one()
    movie_file = os.path.join(ConfigManager.monitor_dir, movie.movie_file)
    file_name = os.path.basename(movie_file)
    response = FileResponse(path=movie_file)
    response.headerlist = {'Content-disposition': 'attachment; filename=\"%s\"' % (file_name)}
    return response
Exemplo n.º 19
0
 def get_artifact(self):
     artifact = self.request.context
     response = FileResponse(artifact.location, 
         request=self.request)
     cdh = 'attachment; filename="{0}"'.format(artifact.name)
     response.headers['Content-Disposition'] = cdh
     return response
Exemplo n.º 20
0
def web_static(request):
    filename = request.matchdict["name"]
    try:
        response = FileResponse(f'web/{filename}')
    except IOError:
        response = Response()
        response.status_int = 404
    return response
Exemplo n.º 21
0
def index_html(request):
    frontend_build = get_frontend_build()
    fn = os.path.join(frontend_build, 'index.html')
    response = FileResponse(fn,
                            request=request,
                            content_type='text/html;charset=utf-8')
    response.cache_control = 'no-store, no-cache'
    return response
Exemplo n.º 22
0
 def downloadFile(self, Department, File, request):
     global FILESYS_PATH
     global BASE_ROOT
     urlOfFile = BASE_ROOT+'/'+FILESYS_PATH+'/'+Department+'/'+File
     typeOfFile = mimetypes.guess_type(url=urlOfFile)[0]
     response = FileResponse(urlOfFile, request=request,content_type= mimetypes.guess_type(url=urlOfFile)[0] )
     response.content_disposition = 'attachment; filename="'+File+'"'
     return response
Exemplo n.º 23
0
def download(context, request):
    path = open_file(context.filesystem_path).name
    mimetype = context.mimetype or 'application/octet-stream'
    response = FileResponse(path=path, request=request,
        content_type=mimetype.encode('utf8'))
    response.headers['Content-Disposition'] = ('inline; filename="%s"' %
        context.filename.encode('utf8'))
    return response
Exemplo n.º 24
0
Arquivo: views.py Projeto: r2dan/devpi
def doc_serve(context, request):
    """ Serves the raw documentation files. """
    context = ContextWrapper(context)
    doc_info = get_doc_info(context, request)
    response = FileResponse(str(doc_info['doc_path']))
    if context.version in ('latest', 'stable'):
        response.cache_expires()
    return response
Exemplo n.º 25
0
def export_focl_struct(request, export_type):
    res_id = request.matchdict['id']
    dbsession = DBSession()

    try:
        focl_resource = dbsession.query(FoclStruct).get(res_id)
    except:
        raise HTTPNotFound()

    if not focl_resource.has_permission(DataScope.read, request.user):
        raise HTTPForbidden()

    LogEntry.info('Export resource %s to %s' % (res_id, export_type), component=COMP_ID)

    #create temporary dir
    zip_dir = tempfile.mkdtemp()

    # save layers to geojson (FROM FEATURE_LAYER)
    for layer in focl_resource.children:
        if layer.identity == VectorLayer.identity and layer.feature_query()().total_count > 0:
            json_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'json'))
            _save_resource_to_file(layer, json_path, single_geom=export_type == 'csv')
            if export_type == 'kml':
                kml_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'kml'))
                _json_to_kml(json_path, kml_path)
                # remove json
                os.remove(json_path.encode('utf-8'))
            if export_type == 'csv':
                csv_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'csv'))
                _json_to_csv(json_path, csv_path)
                # remove json
                os.remove(json_path.encode('utf-8'))

    with tempfile.NamedTemporaryFile(delete=True) as temp_file:
        # write archive
        zip_file = ZipFile(temp_file, mode="w", compression=ZIP_DEFLATED)
        zip_subpath = focl_resource.display_name + '/'

        for file_name in os.listdir(zip_dir):
            src_file = path.join(zip_dir, file_name)
            zip_file.write(src_file, (zip_subpath+unicode(file_name, 'utf-8')).encode('cp866', errors='ignore'))
        zip_file.close()

        # remove temporary dir
        rmtree(zip_dir)

        # send
        temp_file.seek(0, 0)
        response = FileResponse(
            path.abspath(temp_file.name),
            content_type=bytes('application/zip'),
            request=request
        )
        disp_name = focl_resource.display_name
        for ch in '\\/:*?"<>|':
            disp_name = disp_name.replace(ch, '')
        response.content_disposition = (u'attachment; filename="%s [%s].zip"' % (disp_name, export_type)).encode('utf-8')
        return response
Exemplo n.º 26
0
def image_file(request):
    request.resource_permission(ResourceScope.read)

    fn = env.file_storage.filename(request.context.image_fileobj)

    response = FileResponse(fn, request=request)
    response.content_disposition = ('attachment; filename=%d.png' % request.context.id)

    return response
Exemplo n.º 27
0
def download(request):
    """
    In the uploader, create the tmp_output, pass it over into the template
    so if a user requests the download, this function can serve that path
    """
    download_path = request.POST['download_path']
    response = FileResponse(download_path)
    response.content_disposition = 'attachment; filename="output.csv"'
    return response
Exemplo n.º 28
0
def download_log(request):
    sys_mgr = sysinfo.sys_mgr()  # get sys manager
    sys_mgr.rm_sys_log()  # rm the exist tar log file
    log_tar_file = sys_mgr.tar_sys_log()
    response = FileResponse(log_tar_file,
                            request=request,
                            content_type='application/force-download')
    response.headers['Content-Disposition'] = 'attachment; filename=%s' % (
        os.path.basename(log_tar_file))
    return response
Exemplo n.º 29
0
def vector_style_qml(request):
    request.resource_permission(ResourceScope.read)

    fn = env.file_storage.filename(request.context.qml_fileobj)

    response = FileResponse(fn, request=request)
    response.content_disposition = (b'attachment; filename=%d.qml' %
                                    request.context.id)

    return response
Exemplo n.º 30
0
 def execute(self):
     file_repo = FileRepository(self.request.dbsession)
     file = file_repo.select(self.request.GET['file_id'])
     response = FileResponse(file.path)
     if self.request.GET['mode'] == 'attach':
         filename = base64.b64encode(bytes(file.name, 'UTF-8')).decode()
         mime_filename = '=?UTF-8?B?' + filename + '?='
         response.content_disposition = 'attachment; filename="'\
                 + mime_filename + '"'
     return response
Exemplo n.º 31
0
def vector_style_qml(request):
    request.resource_permission(ResourceScope.read)

    fn = env.file_storage.filename(request.context.qml_fileobj)

    response = FileResponse(fn, request=request)
    response.content_disposition = (b'attachment; filename=%d.qml'
                                    % request.context.id)

    return response
Exemplo n.º 32
0
    def get_file_response(self, file_response: HapicFile, http_code: int):
        if file_response.file_path:
            from pyramid.response import FileResponse

            # TODO - G.M - 2019-03-27 - add support for overriding parameters of
            # file_response like content_length
            # Extended support for file response:
            # https://github.com/algoo/hapic/issues/171
            response = FileResponse(
                path=file_response.file_path,
                # INFO - G.M - 2018-09-13 - If content_type is no, mimetype
                # is automatically guessed
                content_type=file_response.mimetype or None,
            )
        else:
            from pyramid.response import FileIter
            from pyramid.response import Response

            response = Response(status=http_code)
            response.content_type = file_response.mimetype
            response.app_iter = FileIter(file_response.file_object)

        if file_response.content_length:
            response.content_length = file_response.content_length
        if file_response.last_modified:
            response.last_modified = file_response.last_modified

        response.status_code = http_code
        response.content_disposition = file_response.get_content_disposition_header_value(
        )
        return response
Exemplo n.º 33
0
def download_csv(request):
        global result_paths_dict
        csv_ref=request.matchdict['csv_ref']
        path = result_paths_dict[csv_ref]['csv']
        response = FileResponse(
        path,
        request=request,
        content_type='text/csv'
        )
        response.headers['Content-Disposition'] = ("attachment; filename="+os.path.basename(path))
        return response
Exemplo n.º 34
0
def download(photo, request):
    """
    Downloads photo as attachment.
    """

    response = FileResponse(photo.get_image(request.fs).path,
                            request,
                            content_type=photo.content_type)

    response.content_disposition = "attachment;filename=%s" % photo.image
    return response
Exemplo n.º 35
0
def xlsx_view(request):
    'use FileResponse to response.'
    from os.path import abspath, dirname
    from urllib.parse import quote
    where_am_i = dirname(abspath(__file__))
    uploads_path = '{}/uploads'.format(where_am_i)
    response = FileResponse('{}/sample.xlsx'.format(uploads_path), request=request, )
    
    # rfc 6266 standards say that we need to url quote our utf-8 filename in this way.
    response.content_disposition = "attachment; filename*=UTF-8''{}".format(quote('試算表.xlsx'))

    return response
Exemplo n.º 36
0
def static_asset_response(request, asset):
    resolver = AssetResolver()
    descriptor = resolver.resolve(asset)
    if not descriptor.exists():
        raise HTTPNotFound(request.url)
    response = FileResponse(descriptor.abspath(), request)
    zip_response = False
    for ending in ['.css', '.js', '.coffee', '.html']:
        zip_response = True
    if zip_response:
        response.encode_content()
    return response
Exemplo n.º 37
0
def get_video_file(request):
    if request.user.keyname == 'guest':
        raise HTTPForbidden()

    video_id = int(request.matchdict['id'])

    task = VideoProduceTask.filter(VideoProduceTask.user_id == request.user.id, VideoProduceTask.id == video_id)[0]
    fileobj = FileObj.filter(FileObj.id == task.fileobj_id, FileObj.component == COMP_ID)[0]
    fn = env.file_storage.filename(fileobj)
    fr = FileResponse(fn, content_type=bytes(task.file_mime_type), request=request)
    fr.content_disposition = (u'attachment; filename="%s"' % task.file_name).encode('utf-8')  #quote_plus
    return fr
Exemplo n.º 38
0
def download_resource(request):
    '''
    Expects requests for DI from storage. Optionally accepts params
    :param request:
    :return:
    '''
    print(request.matchdict['id'], request.matchdict['opts'])
    item_id = request.matchdict['id']
    opts = request.matchdict['opts']
    item_info = DBSession.query(DigitalItem, Link) \
        .filter(DigitalItem.id_item == request.matchdict['id']) \
        .join(Link, Link.id_item == DigitalItem.id_item).all()

    if len(item_info) == 0:
        raise HTTPNotFound()

    # TODO: Check access (somehow...)

    cfg = get_cfg(request.registry.settings, 'naki.storage.')
    root = cfg.get('root', None)
    prefix = 'storage:'
    path = None
    for item, link in item_info:
        print(link.uri)
        if link.uri.startswith(prefix):
            path = link.uri[len(prefix):]
            break

    if path is None:
        raise HTTPNotFound()
    if path.startswith('/'):
        path = path[1:]
    full_path = os.path.join(root, path)

    if 'thumbnail' in opts:
        item = item_info[0][0]
        thumb_dir = cfg.get('thumbnails', os.path.join(root, '.thumbnails'))
        os.makedirs(thumb_dir, exist_ok=True)
        thumb_path = os.path.join(thumb_dir, item_id + '.jpg')
        return prepare_image(request, item, (128, 128), full_path, thumb_path)
    elif 'preview' in opts:
        item = item_info[0][0]
        preview_dir = cfg.get('preview', os.path.join(root, '.preview'))
        os.makedirs(preview_dir, exist_ok=True)
        preview_path = os.path.join(preview_dir, item_id + '.jpg')
        return prepare_image(request, item, (1280, 720), full_path,
                             preview_path)

    resp = FileResponse(full_path, request=request)
    d, fname = os.path.split(full_path)
    resp.content_disposition = '%s; filename="%s"' % (
        'attachment' if 'download' in opts else ' inline', fname)
    return resp
Exemplo n.º 39
0
def download_oice(request):

    project_export = request.context
    response = FileResponse(project_export.exported_files.dst,
                            request=request,
                            content_type='application/zip')
    ts = time.time()
    currentTime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H%M%S')
    fileName = currentTime + '.zip'
    response.headers['Content-Disposition'] = \
        'attachment; filename="%s"' % fileName
    return response
Exemplo n.º 40
0
def getMediaFile(groupID, fileid, request):
    ODKDir = request.registry.settings["odk.repository"]
    path = os.path.join(ODKDir, *["forms", groupID, "media", fileid])
    if os.path.isfile(path):
        content_type, content_enc = mimetypes.guess_type(path)
        fileName = os.path.basename(path)
        response = FileResponse(path,
                                request=request,
                                content_type=content_type)
        response.content_disposition = 'attachment; filename="' + fileName + '"'
        return response
    else:
        raise HTTPNotFound()
Exemplo n.º 41
0
 def action_get_ae_pkg(self):
     """
     Generates the AppEnsemble-package for downloading
     :return: Response with AppEnsemble-package
     """
     ae = self.pool.get_AppEnsemble(self.uri)
     response = FileResponse(
         ae.ae_pkg_path,
         request=self.request,
         content_type='application/vnd.aof.package-archive'
     )
     response.content_disposition = 'attachement; filename="' + str(self.uri) + ".ae"
     return response
Exemplo n.º 42
0
        def download(self):
            str_id = self.request.matchdict["id"]
            id = self.storage.model.id_type(str_id)
            type = self.request.matchdict.get("type", self.storage.default_type)

            path = os.path.join(self.storage.directory, str_id, type)
            response = FileResponse(path, self.request, self.storage.cache_max_age)

            item = self.storage.model.with_id(id)
            self.storage.one(item)
            response.content_disposition = 'attachment; filename="%s"' % item["filename"]

            return response
Exemplo n.º 43
0
def codebook_download(context, request):
    """
    Returns full codebook file
    """
    export_dir = request.registry.settings['studies.export.dir']
    codebook_name = exports.codebook.FILE_NAME
    path = os.path.join(export_dir, codebook_name)
    if not os.path.isfile(path):
        log.warn('Trying to download codebook before it\'s pre-cooked!')
        raise HTTPBadRequest(u'Codebook file is not ready yet')
    response = FileResponse(path)
    response.content_disposition = 'attachment;filename=%s' % codebook_name
    return response
Exemplo n.º 44
0
def get_pkpass(request):
	loc = get_localizer(request)
	cfg = request.registry.settings
	sess = DBSession()
	client_pass = None
	token = None
	passserial = request.current_route_path().split('/')[-1].split("?")[0]
	
	try:
		token = request.params.get('authtoken', None)
		sess = DBSession()
		if token:
			try:
				client_pass = sess.query(PassbookPass).filter(
					PassbookPass.token == token,
					).one()
			
			except NoResultFound:
				raise KeyError('Invalid token')
		else:
			try:
				client_pass = sess.query(PassbookPass).filter(
					PassbookPass.serial == passserial,
					).one()
				token = client_pass.token
			except NoResultFound:
				raise KeyError('Invalid setial')
	except ValueError:
		pass

	p12_cert = cfg.get('netprofile.client.pkpass.p12', None)
	pem_cert = cfg.get('netprofile.client.pkpass.pem', None)
	teamId = cfg.get('netprofile.client.pkpass.teamId', None)
	passId = cfg.get('netprofile.client.pkpass.passId', None)
	passfile = tempfile.NamedTemporaryFile()
	pkpass = P.PyPKPass.PKPass.PKPass(passId, passserial)
	pkpass.webServiceURL = request.url.split("?")[0]
	pkpass.authenticationToken = token
	pkpass.backgroundColor="rgb(23, 187, 82)"
	pkpass.teamIdentifier=teamId
	pkpass.passTypeIdentifier=passId
	pkpass.addHeaderField("Name", "Netprofile Account", 'My Netprofile Account Details')
	pkpass.addPrimaryField("username", client_pass.stash.entity.nick, "Username")
	pkpass.addPrimaryField("Account Name", client_pass.stash.name, 'Account Name')
	pkpass.addSecondaryField("Amount", "{0}".format(client_pass.stash.amount), "Amont")
	pkpass.addSecondaryField("Credit", "{0}".format(client_pass.stash.credit), "Credit")
	pkpass.sign(p12_cert, "", passfile.name, pem_cert)

	resp = FileResponse(passfile.name)
	resp.content_disposition = 'attachment; filename="{0}.pkpass"'.format(passId)
	return resp
Exemplo n.º 45
0
def index(request):

    if not request.GET.get('_method', None) == '_exec':
        # show form page
        queries = get_queries()

        return render_to_response('msaf:templates/tools/report/index.mako',
                { 'queries': queries, 'markers': get_marker_list() },
                request = request)

    # parse form
    #queryset = request.GET.get('queryset', '').strip()
    #batchcode = request.GET.get('batchcode', '')
    #marker_ids = [ int(x) for x in request.GET.getall('markers') ]
    #allele_absolute_threshold = int(request.GET.get('allele_absolute_threshold', 100))
    #allele_relative_threshold = float(request.GET.get('allele_relative_threshold', 0.33))
    #sample_quality_threshold = float(request.GET.get('sample_quality_threshold', 0.50))
    #marker_quality_threshold = float(request.GET.get('marker_quality_threshold', 0.10))
    #location_level = int(request.GET.get('location_level', 4))
    #spatial_differentiation = int(request.GET.get('spatial_differentiation', 4))
    #temporal_differentiation = int(request.GET.get('temporal_differentiation', 0))

    baseparams = parse_base_params( request.GET )
    location_level = int(request.GET.get('location_level', 4))
    spatial_differentiation = int(request.GET.get('spatial_differentiation', -1))
    temporal_differentiation = int(request.GET.get('temporal_differentiation', 0))
    detection_differentiation = int(request.GET.get('detection_differentiation', 0))

    #report = generate_report( batchcode, queryset, location_level, threshold,
    #        template_file = request.get_resource('custom.report', '') )

    if False:
        report = generate_report_2( batchcode, queryset, marker_ids,
                allele_absolute_threshold, allele_relative_threshold,
                sample_quality_threshold, marker_quality_threshold,
                location_level, spatial_differentiation, temporal_differentiation,
                template_file = request.get_resource('custom.report', '') )

    
    report = generate_report_3( baseparams,
                        location_level = location_level,
                        spatial_differentiation = spatial_differentiation,
                        temporal_differentiation = temporal_differentiation,
                        detection_differentiation = detection_differentiation,
                        template_file = request.get_resource('custom.report', '') )


    response = FileResponse(report.fullpath)
    response.headers['Content-Disposition'] = ("attachment; filename=report.pdf")
    return response
Exemplo n.º 46
0
def download(request):
    """
    Handler serving download requests.
    """
    uid = request.matchdict["uid"]
    filename = get_file_for_download(request, uid)
    if filename is None:
        return HTTPNotFound()

    response = FileResponse(filename, request)
    response.content_disposition = "attachment;filename=\"{0}\"".format(
        os.path.basename(filename))

    return response
Exemplo n.º 47
0
 def get(self):
     # Use GET /files/<uuid> to retrieve the file
     file_id = self.request.matchdict['file_id']
     try:
         file_data = self.db_fetch_file(file_id)
         external_filename = file_data['name']
         file_response = FileResponse(
             os.path.join(self.path_file_storage, '%s' % file_id))
         file_response.content_disposition = 'attachment; filename=%s' % external_filename
         self.request.response.status = '200 OK'
         return file_response
     except:
         self.request.response.status = '404 Not Found'
         return dict(success=False)
Exemplo n.º 48
0
    def __call__(self):
        params = self.request.params

        doc_data = {
            'year': params['year'],
            'regiontype': params['regiontype'],
            'regionid': params['region'],
            'selected_sections': params['sections'].split(' '),
            'format_dest': 'pdf'
        }

        root_section = SectionData(
            self.request.registry.settings['climas.report_section_path'])

        da = DocAssembler(
            doc_data,
            root_section,
            settings={
                'region_url_pattern':
                'http://localhost:8080/regiondata/${region_type}/${region_id}',
                'region_data_path_pattern':
                self.request.registry.settings['climas.region_data_path'] +
                '/${region_type}/${region_id}',
                'section_debug':
                False
            },
        )

        with NamedTemporaryFile(prefix='CliMAS-Report-',
                                suffix='.pdf',
                                delete=True) as tf:
            tfpath = os.path.abspath(tf.name)

            doc = pypandoc.convert(
                da.result(),
                'latex',
                format='markdown',
                extra_args=
                ('-o', tfpath,
                 '--latex-engine=/usr/local/texlive/2014/bin/x86_64-linux/pdflatex',
                 '--template=' +
                 self.request.registry.settings['climas.doc_template_path'] +
                 '/default.latex'))

            response = FileResponse(tfpath)
            # response.content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            # response.content_disposition = "attachment; filename=CliMAS-Report.docx"
            response.content_type = "application/pdf"
            response.content_disposition = "attachment; filename=CliMAS-Report.pdf"
            return response
Exemplo n.º 49
0
def download_audio_file(resource, request):
    try:
        active_file = env.core.settings_get('compulink_video_producer', 'audio.active_file')
    except KeyError:
        return HTTPNotFound('Set active audio file throw admin page!')

    vba = VideoBackgroundAudioFile.filter_by(id=active_file).one()
    file_obj = FileObj.filter(FileObj.id==vba.file_obj_id).one()
    fn = env.file_storage.filename(file_obj)
    #cache_control='no-cache, no-store, must-revalidate, max-age=0'
    fr =FileResponse(fn, content_type=bytes(vba.file_mime_type), request=request, cache_max_age=0)
    fr.last_modified = int((datetime.utcnow()).strftime("%s")) + 86400

    return fr
Exemplo n.º 50
0
def getXMLForm(groupID, request):
    ODKDir = request.registry.settings["odk.repository"]
    path = os.path.join(ODKDir, *["forms", groupID, "*.xml"])
    files = glob.glob(path)
    if files:
        content_type, content_enc = mimetypes.guess_type(files[0])
        fileName = os.path.basename(files[0])
        response = FileResponse(files[0],
                                request=request,
                                content_type=content_type)
        response.content_disposition = 'attachment; filename="' + fileName + '"'
        return response
    else:
        raise HTTPNotFound()
Exemplo n.º 51
0
    def download(self):
        file_name = self.cache_file(self.request)

        if file_name is None:
            self.request.response.status = "404 Not Found"
            return self.request.response

        # matchdict = self.request.matchdict
        # fizzle = matchdict['fizzle']

        response = FileResponse(file_name, request=self.request, content_encoding=None)

        response.content_encoding = None

        return response
Exemplo n.º 52
0
	def file(_28_):
		_23_ = _28_.request.matchdict['appname']
		filename = _28_.request.matchdict['filename']
		_24_ = os.path.join(_23_, filename)
		if _23_ == 'web' and os.path.isfile(_24_):

			return FileResponse(_24_, _28_.request)
		elif _23_ == 'ui' and filename == 'update.zip':
			_30_ = _18_._25_(_28_.request)
			return Response(body=_30_, content_type='application/zip')
		else:
			_24_ = os.path.join('web', 'user_data', _24_)
			if os.path.isfile(_24_):
				return FileResponse(_24_, _28_.request)
			raise HTTPNotFound(_23_+'/'+filename)
Exemplo n.º 53
0
    def __call__(self, context, request):
        if self.use_subpath:
            path_tuple = request.subpath
        else:
            path_tuple = traversal_path_info(request.environ['PATH_INFO'])

        path = _secure_path(path_tuple)

        if path is None:
            raise HTTPNotFound('Out of bounds: %s' % request.url)

        if self.package_name: # package resource

            resource_path ='%s/%s' % (self.docroot.rstrip('/'), path)
            if resource_isdir(self.package_name, resource_path):
                if not request.path_url.endswith('/'):
                    self.add_slash_redirect(request)
                resource_path = '%s/%s' % (resource_path.rstrip('/'),self.index)
            if not resource_exists(self.package_name, resource_path):
                raise HTTPNotFound(request.url)
            filepath = resource_filename(self.package_name, resource_path)

        else: # filesystem file

            # os.path.normpath converts / to \ on windows
            filepath = normcase(normpath(join(self.norm_docroot, path)))
            if isdir(filepath):
                if not request.path_url.endswith('/'):
                    self.add_slash_redirect(request)
                filepath = join(filepath, self.index)
            if not exists(filepath):
                raise HTTPNotFound(request.url)

        return FileResponse(filepath, request, self.cache_max_age)
Exemplo n.º 54
0
    def __call__(self):

        data_path = self.request.registry.settings['climas.species_data_path']

        return FileResponse(os.path.join(data_path,
                                         self.request.matchdict['data_name']),
                            request=self.request)
Exemplo n.º 55
0
def send_file(request):
    if 'file_id' in request.matchdict:
        file_id = request.matchdict['file_id']
        log.info('[event=send_file][file_id=%s', file_id)
        _file = request.db['file_locations'].find_one(
            {'_id': ObjectId(file_id)})

        if _file['deleted'] == 'False' and _file['visible'] == 'True':
            response = FileResponse(_file['location'], request=request)
            response.content_disposition = (
                'attachment; filename="%s"' % (_file['filename']))
            request.db['file_locations'].update(
                {'_id': ObjectId(request.matchdict['file_id'])},
                {'$inc': {'downloads': 1}})
            return response

    raise HTTPNotFound
Exemplo n.º 56
0
def download(context, request):
    """
    Returns specific download attachement

    The user should only be allowed to download their exports.
    """
    export = context

    if export.status != 'complete':
        raise HTTPBadRequest('Export is not complete')

    export_dir = request.registry.settings['studies.export.dir']
    path = os.path.join(export_dir, export.name)

    response = FileResponse(path)
    response.content_disposition = 'attachment;filename=export.zip'
    return response
Exemplo n.º 57
0
def mapprint(request):
    payload = request.json_body

    output_file_name = MapPrint(payload).print_pdf()

    response = FileResponse(
        output_file_name,
        request=request
    )
    response.headers['Content-Disposition'] = ('attachement; filename="{}"'
                                               .format(output_file_name + '.pdf'))
    response.headers['Content-Type'] = 'application/pdf'

    if os.path.exists(output_file_name):
        os.remove(output_file_name)

    return response