示例#1
0
文件: themes.py 项目: Readon/cydra
    def themed_send_static_file(self, filename):
        # do we have an active theme?
        theme = None
        if hasattr(flask.g, 'theme'):
            theme = flask.g.theme
        if theme is not None:
            try:
                return send_from_directory(os.path.join(theme.static_path, blueprint_name), filename)
            except NotFound:
                pass

        if not self.has_static_folder:
            raise RuntimeError('No static folder for this object')
        return send_from_directory(self.static_folder, filename)
示例#2
0
def download():
    """GET /download/ConPaaS.tar.gz

    Returns ConPaaS tarball.
    """
    return helpers.send_from_directory(common.config_parser.get('conpaas', 'CONF_DIR'),
        "ConPaaS.tar.gz")
示例#3
0
def download():
    """GET /download/ConPaaS.tar.gz

    Returns ConPaaS tarball.
    """
    return helpers.send_from_directory(os.path.dirname(__file__), 
        "ConPaaS.tar.gz")
示例#4
0
    def showCacheFile(self, filename = ''):

        cache_dir = Env.get('cache_dir')
        filename = os.path.basename(filename)

        from flask.helpers import send_from_directory
        return send_from_directory(cache_dir, filename)
示例#5
0
def static_file(path=None):
    if not path:
        path = 'index.html'
    try:
        return send_from_directory('webroot', path)
    except NotFound:
        return static_file()
示例#6
0
def worksheed_data_folder(worksheet, filename):
    dir = os.path.abspath(worksheet.data_directory())
    if not os.path.exists(dir):
        return make_response(_('No data file'), 404)
    else:
        from flask.helpers import send_from_directory
        return send_from_directory(worksheet.data_directory(), filename)
示例#7
0
def read(p="."):
    if not os.path.exists(p):
        return make_response(jsonify(description="The path does not exists."), 404)
    if fs.is_dir(p) or "*" in p:
        return jsonify(content=fs.ls(p))
    else:
        return send_from_directory(fs.split(p)[0], fs.split(p)[1])
示例#8
0
 def send_media_file(self, filename):
     """
     Function used to send media files from the media folder to the browser.
     """
     cache_timeout = self.get_send_file_max_age(filename)
     return send_from_directory(self.config['MEDIA_FOLDER'], filename,
                                cache_timeout=cache_timeout)
示例#9
0
 def send_theme_file(self, filename):
     """
     Function used to send static theme files from the theme folder to the browser.
     """
     cache_timeout = self.get_send_file_max_age(filename)
     return send_from_directory(self.config['THEME_STATIC_FOLDER'], filename,
                                cache_timeout=cache_timeout)
示例#10
0
def base_static(filename):
    return send_from_directory(
        os.path.dirname(
            os.path.abspath(__file__)
        ) + '/../bower_components/',
        filename
    )
示例#11
0
 def send_root_file(self, filename):
     """
     Function used to send static files from the root of the domain.
     """
     cache_timeout = self.get_send_file_max_age(filename)
     return send_from_directory(self.config['ROOT_FOLDER'], filename,
                                cache_timeout=cache_timeout)
示例#12
0
def worksheet_data(worksheet, filename):
    dir = os.path.abspath(worksheet.data_directory())
    if not os.path.exists(dir):
        return current_app.message(_('No data files'))
    else:
        from flask.helpers import send_from_directory
        return send_from_directory(worksheet.data_directory(), filename)
示例#13
0
def static_noise_proxy(path):
    global curNoisePreviewDir
    if curNoisePreviewDir != "" and os.path.exists(curNoisePreviewDir):
        print "img", os.path.join(curNoisePreviewDir, path)
        return send_from_directory(curNoisePreviewDir, path)

    abort(500)
示例#14
0
文件: static.py 项目: dropbox/changes
    def get(self, filename):
        root = self.root

        if filename.startswith("vendor/") and self.hacky_vendor_root:
            root = self.hacky_vendor_root

        # We do this in debug to work around http://stackoverflow.com/q/17460463/871202
        # By reading the file into memory ourselves, we seem to avoid hitting that
        # VirtualBox issue in dev. In prod, it's unchanged and we just send_from_directory
        if app.debug:
            full_name = root + "/" + filename

            if filename:
                mimetype = mimetypes.guess_type(filename)[0]
            else:
                mimetype = 'application/octet-stream'
            return Response(
                open(full_name),
                mimetype=mimetype,
                headers={
                    "Content-Disposition": "filename=" + filename
                }
            )
        else:
            return send_from_directory(
                root, filename, cache_timeout=self.cache_timeout)
示例#15
0
def public_worksheet_cells(id, filename):
    worksheet_filename =  "pub" + "/" + id
    try:
        worksheet = g.notebook.get_worksheet_with_filename(worksheet_filename)
    except KeyError:
        return current_app.message("You do not have permission to access this worksheet") #XXX: i18n
    from flask.helpers import send_from_directory
    return send_from_directory(worksheet.cells_directory(), filename)
示例#16
0
文件: __init__.py 项目: garribas/isi
def page(path):
    #as werkzeug uses unordered dictionary for url mapping, let's hack for static files
    try:
        return send_from_directory(os.path.join(app.root_path,"static"), path, as_attachment=True)
    except NotFound:
        pass
    page = pages.get_or_404(path)
    template = page.content.get('template', 'default.html')
    return render_template(template, **page.content)
示例#17
0
 def send_static_file(self, filename):
     """Function used internally to send static files from the static
     folder to the browser.
     """
     cache_timeout = current_app.get_send_file_max_age(filename)
     return send_from_directory(
         STATIC_FOLDER, filename,
         cache_timeout=cache_timeout
     )
示例#18
0
	def send_storage_file(self, filename):
		if not self.has_static_folder:
			raise RuntimeError('No static folder for this object')
		from flask.helpers import send_from_directory
		# Ensure get_send_file_max_age is called in all cases.
		# Here, we ensure get_send_file_max_age is called for Blueprints.
		cache_timeout = self.get_send_file_max_age(filename)
		return send_from_directory('storage', filename,
			cache_timeout=cache_timeout)
示例#19
0
文件: views.py 项目: Theer108/invenio
 def send_static_file(self, filename):
     """Return static file."""
     try:
         return super(self.__class__, self).send_static_file(filename)
     except:
         cache_timeout = self.get_send_file_max_age(filename)
         return send_from_directory(
             os.path.join(current_app.instance_path, "docs", "static"),
             filename,
             cache_timeout=cache_timeout)
示例#20
0
文件: misc.py 项目: elidaian/sudoku
def get_font(filename):
    """
    Get a file from the fonts directory.

    :param filename: The filename.
    :type filename: str
    :return: The font file.
    :rtype: flask.Response
    """
    return send_from_directory(join(dirname(__file__), "fonts"), filename)
示例#21
0
    def static(filename, version = None):
        from flask.helpers import send_from_directory
        r = send_from_directory(app.config['STATIC_DIR'], filename)

        if version and version != app.config['STATIC_VERSION']:
            return redirect(static_url(url_for('static', filename = filename, version = app.config['STATIC_VERSION'])))

        r.headers['Access-Control-Allow-Origin'] = '*'

        return r
示例#22
0
def send_static_file(self, filename):
    """Function used internally to send static files from the static
    folder to the browser.

    .. versionadded:: 0.5
    """
    if not self.has_static_folder:
        raise RuntimeError('No static folder for this object')
    # Ensure get_send_file_max_age is called in all cases.
    # Here, we ensure get_send_file_max_age is called for Blueprints.
    cache_timeout = self.get_send_file_max_age(filename)
    return send_from_directory(self.static_folder, filename,
                               cache_timeout=1)
示例#23
0
文件: app.py 项目: jameysharp/dcon
    def send_static_file(self, filename):
        cache_timeout = self.get_send_file_max_age(filename)

        l = self.static_paths[:]
        if self.has_static_folder:
            l.append(self.static_folder)

        for path in l:
            try:
                return send_from_directory(path, filename,
                        cache_timeout=cache_timeout)
            except NotFound:
                continue

        raise NotFound()
示例#24
0
文件: app.py 项目: no8ter/Diplome
def render_claim_pdf():
    '''
    Маршрутизация страницы печати заявления
    '''
    if auth_request():

        import pythoncom
        pythoncom.CoInitializeEx(0)

        name = renderDocxTemplate(session.get('userLogin'))
        waybase = os.getcwd() + '\\static'
        temp = send_from_directory(waybase, name)
        return temp
    else:
        return redirect(url_for('login'))
示例#25
0
    def getUserScript(self, filename = ''):

        params = {
            'includes': fireEvent('userscript.get_includes', merge = True),
            'excludes': fireEvent('userscript.get_excludes', merge = True),
            'version': self.getVersion(),
            'api': '%suserscript/' % url_for('api.index').lstrip('/'),
            'host': request.host_url,
        }

        script = self.renderTemplate(__file__, 'template.js', **params)
        self.createFile(os.path.join(Env.get('cache_dir'), 'couchpotato.user.js'), script)

        from flask.helpers import send_from_directory
        return send_from_directory(Env.get('cache_dir'), 'couchpotato.user.js')
示例#26
0
文件: flask.py 项目: mikeboers/Spoon
    def send_static_file(self, filename):

        # Ensure get_send_file_max_age is called in all cases.
        # Here, we ensure get_send_file_max_age is called for Blueprints.
        cache_timeout = self.get_send_file_max_age(filename)

        # Serve out of 'static' and 'var/static'.
        for dir_name in 'static', 'var/static':
            dir_path = os.path.join(self.root_path, dir_name)
            file_path = os.path.join(dir_path, filename)
            if os.path.exists(file_path):
                break
        
        return send_from_directory(dir_path, filename,
                                   cache_timeout=cache_timeout)
def download_file():
    try:
        # Absolute Path
        directory = '/mnt/shared/Past/'
        # File Name StudentId_MemberName.zip
        filename = session[SessionResources().const.MEMBER_ID] + '_'\
        + session[SessionResources().const.MEMBER_NAME] + '.zip'
        
        Log.info(session[SessionResources().const.MEMBER_ID] \
                 + ' download '\
                 + directory\
                 + '/'  + filename)
        
        return send_from_directory(directory = directory, filename = filename)
    except Exception:
        pass
示例#28
0
def download(username,filename):
    # os.path.realpath(__file__)打印出来的是当前路径/soft/flask/day1/wenwen.py
    # os.path.dirname(os.path.realpath(__file__))打印出来的是/soft/flask/day1/
    username=username
    filename=filename
    user_=db.query_zipfile(username,filename)
    
    # current_dir = os.path.dirname(os.path.realpath(__file__))
    path='E:/python_code/Baiyinyun'+user_.filepath[1:]
    path=path.split('/')[:-1]
    path='/'.join(path)
    # print(current_dir)
    # return jsonify({'code':1})
    # print(username,filename)

    return send_from_directory(path, user_.filename,as_attachment=True)
示例#29
0
def download_file():
    try:
        # Absolute Path
        directory = '/mnt/shared/Past/'
        # File Name StudentId_MemberName.zip
        filename = session[SessionResources().const.MEMBER_ID] + '_'\
        + session[SessionResources().const.MEMBER_NAME] + '.zip'

        Log.info(session[SessionResources().const.MEMBER_ID] \
                 + ' download '\
                 + directory\
                 + '/'  + filename)

        return send_from_directory(directory=directory, filename=filename)
    except Exception:
        pass
示例#30
0
文件: main.py 项目: babbel4ever/PBI
    def getUserScript(self, random='', filename=''):

        params = {
            'includes': fireEvent('userscript.get_includes', merge=True),
            'excludes': fireEvent('userscript.get_excludes', merge=True),
            'version': self.getVersion(),
            'api': '%suserscript/' % url_for('api.index').lstrip('/'),
            'host': request.host_url,
        }

        script = self.renderTemplate(__file__, 'template.js', **params)
        self.createFile(
            os.path.join(Env.get('cache_dir'), 'couchpotato.user.js'), script)

        from flask.helpers import send_from_directory
        return send_from_directory(Env.get('cache_dir'), 'couchpotato.user.js')
    def send_static_file(self, filename):

        if not self.has_static_folder:
            raise RuntimeError('No static folder defined')

        cache_timeout = self.get_send_file_max_age(filename)
        folders = [self.static_folder] + self.static_folders

        for folder in folders:
            try:
                return send_from_directory(folder,
                                           filename,
                                           cache_timeout=cache_timeout)
            except NotFound:
                pass

        raise NotFound()
示例#32
0
def send_file_from_directory(filename, directory, app=None):
  """
  Helper to add static rules, like in `abilian.app`.app

  Example use::

       app.add_url_rule(
          app.static_url_path + '/abilian/<path:filename>',
          endpoint='abilian_static',
          view_func=partial(send_file_from_directory,
                            directory='/path/to/static/files/dir'))
  """
  if app is None:
    app = current_app
  cache_timeout = app.get_send_file_max_age(filename)
  return send_from_directory(directory, filename,
                             cache_timeout=cache_timeout)
示例#33
0
def send_file_from_directory(filename, directory, app=None):
    """Helper to add static rules, like in `abilian.app`.app.

    Example use::

       app.add_url_rule(
          app.static_url_path + '/abilian/<path:filename>',
          endpoint='abilian_static',
          view_func=partial(send_file_from_directory,
                            directory='/path/to/static/files/dir'))
    """
    if app is None:
        app = current_app
    cache_timeout = app.get_send_file_max_age(filename)
    return send_from_directory(directory,
                               filename,
                               cache_timeout=cache_timeout)
示例#34
0
 def files(self,path="."):
     '''
     show the files in the given path
     
     Args:
         path(str): the path to render
     '''
     template="scan2wiki/datatable.html"
     title="Scans"
     activeItem=title
     fullpath=f"{self.scandir}/{path}"
     if os.path.isdir(fullpath):
         # https://stackoverflow.com/questions/57073384/how-to-add-flask-autoindex-in-an-html-page
         # return files_index.render_autoindex(path,template="scans.html")
         dictList,lodKeys,tableHeaders=self.getScanFiles()
         return self.render_template(templateName=template,title=title,activeItem=activeItem,dictList=dictList,lodKeys=lodKeys,tableHeaders=tableHeaders)
     else:
         return send_from_directory(self.scandir,path)
示例#35
0
def ticket_attendee_pdf(attendee_id):
    ticket_holder = TicketHolder.query.get(attendee_id)
    if ticket_holder is None:
        raise NotFoundError({'source': ''},
                            'This attendee is not associated with any ticket')

    if not (current_user.is_staff
            or ticket_holder.order.user_id == current_user.id
            or ticket_holder.user == current_user or has_access(
                'is_coorganizer_or_user_itself',
                event_id=ticket_holder.event_id,
                user_id=ticket_holder.user.id,
            )):
        raise ForbiddenError({'source': ''}, 'Unauthorized Access')
    file_path = ticket_holder.pdf_url_path
    if not os.path.isfile(file_path):
        create_pdf_tickets_for_holder(ticket_holder.order)
    return send_from_directory('../', file_path, as_attachment=True)
示例#36
0
def docs(ref, path):
    if ref == 'head':
        ref = get_head()
        if ref is None:
            abort(404)
    elif not re.match(r'^[A-Fa-f0-9]{7,40}$', ref):
        abort(404)
    redirect = ensure_login()
    if redirect:
        return redirect
    save_dir = current_app.config['SAVE_DIRECTORY']
    if len(ref) < 40:
        for candi in os.listdir(save_dir):
            if (os.path.isdir(os.path.join(save_dir, candi))
                    and candi.startswith(ref)):
                return redirect(url_for('docs', ref=candi, path=path))
        abort(404)
    return send_from_directory(save_dir, os.path.join(ref, path))
示例#37
0
def docs(ref, path):
    if ref == 'head':
        ref = get_head()
        if ref is None:
            abort(404)
    elif not re.match(r'^[A-Fa-f0-9]{7,40}$', ref):
        abort(404)
    redirect = ensure_login()
    if redirect:
        return redirect
    save_dir = current_app.config['SAVE_DIRECTORY']
    if len(ref) < 40:
        for candi in os.listdir(save_dir):
            if (os.path.isdir(os.path.join(save_dir, candi)) and
                candi.startswith(ref)):
                return redirect(url_for('docs', ref=candi, path=path))
        abort(404)
    return send_from_directory(save_dir, os.path.join(ref, path))
示例#38
0
def export_email_addresses():
    email_addresses = [u.email for u in cdw.users.with_fields(origin='web')]

    tmpdir = current_app.config['TMP_DIR']

    fn = os.path.join(tmpdir, 'email_addresses.txt')
    f = open(fn, "w")
    for item in email_addresses:
        f.write("%s\n" % item)
    f.close()

    zfn = os.path.join(tmpdir, 'email_addresses.zip')
    zf = zipfile.ZipFile(zfn, mode='w', compression=zipfile.ZIP_DEFLATED)
    zf.write(fn, arcname='email_addresses.txt')
    zf.close()

    os.unlink(fn)

    return send_from_directory(tmpdir, 'email_addresses.zip')
示例#39
0
def receiveFromServer():
    passwdServer = request.headers.get('x-passwd')
    passwdClient = request.headers.get('x-auth')
    isValid = False
    if (passwdServer != None):
        if (master.passwordCorrect(request.headers.get('x-passwd'))):
            isValid = True
        else:
            return {"status": "incorrect password"}
    elif (passwdClient != None):
        uid, isValid = requireRegister()
    else:
        isValid = False
    if (isValid):
        cmd = request.json['sFile']
        return send_from_directory(directory=FOLDER,
                                   filename=cmd,
                                   as_attachment=True)
    else:
        return {'status': 'notValid'}, 200
示例#40
0
def upload_file():
    # check if the post request has the file part
    if 'file' not in request.files:
        print(request.files)
        resp = jsonify({'message': 'No file part in the request'})
        return resp, 400

    file = request.files['file']

    if file.filename == '':
        resp = jsonify({'message': 'No file selected for uploading'})
        return resp, 400
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        modify(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return send_from_directory(os.path.join(os.getcwd()), 'results.txt')
    else:
        resp = jsonify({'message': 'Allowed file types are pdf'})
        return resp, 400
示例#41
0
def show_image(entry_id, image_id):
    with app.test_request_context():
        entry = Entry.query.filter_by(id = entry_id).first()
        images = Images.query.filter_by(id = entry.imgs_id).first()
        print(entry_id, images)
        img = images.get_images()[image_id]
        filetype = 'JPEG' if images.get_filetypes()[image_id] == "jpg" else images.get_filetypes()[image_id].upper()
        
        img_id = 0 if session.get('img_id') is None else session.get('img_id')
        img_path = '{}\\{}.{}'.format(app.config['UPLOAD_FOLDER'], img_id, filetype.lower())
        try:
            img = Image.open(io.BytesIO(img))
            img.save(img_path, filetype)
        except UnidentifiedImageError as e:
            print(e)
        
        #deletion-handling
        session['img_id'] = img_id + 1
        session['imgs'] = [img_path] if session.get('imgs') is None else session.get('imgs').append(img_path)
        return send_from_directory(app.config['UPLOAD_FOLDER'], '{}.{}'.format(img_id, filetype.lower()))
示例#42
0
def order_invoices(order_identifier):
    if current_user:
        try:
            order = Order.query.filter_by(identifier=order_identifier).first()
        except NoResultFound:
            raise NotFoundError({'source': ''}, 'Order Invoice not found')
        if (has_access(
                'is_coorganizer_or_user_itself',
                event_id=order.event_id,
                user_id=order.user_id,
        ) or order.is_attendee(current_user)):
            file_path = order.invoice_pdf_path
            if not os.path.isfile(file_path):
                create_pdf_tickets_for_holder(order)
            return send_from_directory('../', file_path, as_attachment=True)
        else:
            raise ForbiddenError({'source': ''}, 'Unauthorized Access')
    else:
        raise ForbiddenError({'source': ''},
                             'Authentication Required to access Invoice')
示例#43
0
def get_outputs(location):
    """
    Get a outputs resource
    ---
    description: Gets a outputs resource, returning a compressed outputs tar file.
    produces:
    - application/json
    responses:
        200:
            description: A compressed tar of the outputs generated by an analysis.
        404:
            description: Resource not found.
    parameters:
    -   name: location
        in: path
        description: The location of the outputs resource to download.
        required: true
        type: string
    """
    logging.debug("Location: {}".format(location))
    return send_from_directory(settings.get('server', 'OUTPUTS_DATA_DIRECTORY'), location + TAR_FILE_SUFFIX)
示例#44
0
def get_exposure(location):
    """
    Get an exposure resource
    ---
    description: Returns an exposure resource.
    produces:
    - application/json
    responses:
        200:
            description: A compressed tar file containing the Oasis exposure files.
        404:
            description: Resource not found
    parameters:
    - name: location
      in: path
      description: The location of the exposure resource.
      required: true
      type: string
    """
    logging.debug("Location: {}".format(location))
    return send_from_directory(settings.get('server', 'INPUTS_DATA_DIRECTORY'), location + TAR_FILE_SUFFIX)
示例#45
0
def render_tile(hashId, zoom, tileId):
    print "Request for hash: {2} tile: {1} at zoom {0}".format(zoom, tileId, hashId)

    # Generate a consistent name based upon the tile request.
    # Identical future requests result in the same name.
    # This is the basis for the tile cache.
    col,row = tileId.split('.')[0].split('_')

    TILE_SIZE = 64
    x0 = (int(col)-1) * TILE_SIZE
    x1 = x0 + TILE_SIZE

    # y is inverted (the pano code assumes y is down...)
    row = 8 - int(row)
    y0 = (int(row)-1) * TILE_SIZE
    y1 = y0 + TILE_SIZE

    outDir = "assets/tiles/" + hashId
    if not os.path.exists(outDir):
        os.mkdir(outDir)

    outputName = "{}_{}-{}_{}-{}.png".format(zoom, x0, x1, y0, y1)
    outputFilepath = os.path.join(outDir, outputName)
    sendFile = False
    if os.path.exists(outputFilepath):
        print "Sending cached tile:", outputFilepath
        sendFile = True
    else:
        cmdLineArgs = "glow --input={0} --output={1} --imageArea={2},{3},{4},{5} --gamma={6} --verbose". \
            format(curSceneFile, outputFilepath, x0, x1, y0, y1, 1.25)

        print "Calling glow:", cmdLineArgs

        sendFile = glow.run(cmdLineArgs.split()) == 0

    if sendFile:
        print "sending {} {}".format(outDir, outputName)
        return send_from_directory(outDir, outputName)

    abort(500)
示例#46
0
文件: server.py 项目: GSng/Uber
def predict():
    #Redundant: start_data=first proceeding period of end of dataset    
    #start_date = request.args.get('start_date', '')
    end_date = request.args.get('end_date', '2012-05-05 23:00:00+00:00')  
    if end_date=='null':
        end_date = '2012-05-05 23:00:00+00:00'
    
    #Depending on output type perform the appropriate prediction action
    #timeser.get_prediction_for_daterange builds forecast    
    output_type = request.args.get('type', 'json')
    if output_type=='coords':
        #For visualization below methods are called        
        return dumps(get_coords(end_date))    
    elif output_type=='json':
        predicted_demand = timeser.get_prediction_for_daterange(end_date, asutc=True)
        return jsonify(predicted_demand.to_dict())
    else:
        predicted_demand = timeser.get_prediction_for_daterange(end_date, asutc=True)
        odir = './generated_csvs/'
        tfile =  'temp'+str(datetime.now())+'.csv'
        predicted_demand.to_csv(odir  + tfile)
        return send_from_directory(odir, tfile)
示例#47
0
    def get(self, filename):
        root = self.root

        if filename.startswith("vendor/") and self.hacky_vendor_root:
            root = self.hacky_vendor_root

        # We do this in debug to work around http://stackoverflow.com/q/17460463/871202
        # By reading the file into memory ourselves, we seem to avoid hitting that
        # VirtualBox issue in dev. In prod, it's unchanged and we just send_from_directory
        if app.debug:
            full_name = root + "/" + filename

            if filename:
                mimetype = mimetypes.guess_type(filename)[0]
            else:
                mimetype = 'application/octet-stream'
            return Response(
                open(full_name),
                mimetype=mimetype,
                headers={"Content-Disposition": "filename=" + filename})
        else:
            return send_from_directory(root,
                                       filename,
                                       cache_timeout=self.cache_timeout)
示例#48
0
def db():
    #Xlsxwrite
    date_string = datetime.now().strftime('%Y%m%d%H%M%S')
    workbook = xlsxwriter.Workbook('./resources/%s.xlsx' % date_string)
    worksheet = workbook.add_worksheet('book_data')

    s_row = 2
    s_col = 1

    # DB연결
    engine = create_engine("mysql+pymysql://root:rootroot@localhost/test")
    conn = engine.raw_connection()
    cursor = conn.cursor()

    cursor.callproc('select_all_books')
    data = cursor.fetchall()

    worksheet.write(s_row-1, 1, 'book id')
    worksheet.write(s_row-1, 2, 'book name')
    worksheet.write(s_row-1, 3, 'book price')
    worksheet.write(s_row-1, 4, 'book type')

    for row_data in data:
        for col_data in row_data:
            worksheet.write(s_row, s_col, col_data)
            s_col += 1
        s_col = 1
        s_row += 1

    worksheet.write(s_row, 2, 'Total')
    worksheet.write(s_row, 3, '=sum(D3:D12)')
    worksheet.write(s_row, 4, '=counta(E3:E12)')

    workbook.close()

    return send_from_directory('./resources', '%s.xlsx' % date_string, as_attachment=True)
示例#49
0
    def send_static_file(self, filename):
        """Function used internally to send static files from the static
        folder to the browser.

        .. versionadded:: 1.0.1
        """
        if not self.has_static_folder:
            raise RuntimeError('No static folder for this object')

        # Ensure get_send_file_max_age is called in all cases.
        # Here, we ensure get_send_file_max_age is called for Blueprints.
        cache_timeout = self.get_send_file_max_age(filename)

        folders = self.static_folder
        if isinstance(self.static_folder, string_types):
            folders = [self.static_folder]

        for directory in folders:
            try:
                return send_from_directory(
                    directory, filename, cache_timeout=cache_timeout)
            except NotFound:
                pass
        raise NotFound()
示例#50
0
def download(book_id):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               f'{book_id}.pdf',
                               as_attachment=True)
示例#51
0
 def send_static_file(filename):
     cache_timeout = flaskadminapp.get_send_file_max_age(filename)
     return send_from_directory(folder, filename, cache_timeout=cache_timeout)
示例#52
0
 def static_view_func(self, root_path, filename):
     from flask.helpers import send_from_directory
     return send_from_directory(root_path, filename)
def index():
    return send_from_directory(".", "index.html")
def view(path):
    return send_from_directory("./images", path)
def js(path):
    return send_from_directory("js", path)
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')
示例#57
0
def send_js(path):
    return send_from_directory('static', path)
示例#58
0
    def showStatic(self, filename):
        d = os.path.join(self.plugin_path, 'static')

        from flask.helpers import send_from_directory
        return send_from_directory(d, filename)
示例#59
0
def root():
    current_app.logger.debug("ROOT: return index.html")
    return send_from_directory(current_app.config["WEBAPP_SOURCE"],
                               "index.html")