Example #1
0
def begin():
	if ('username' in session):
		if ((session['progress']) and (session['progress'] != '')):
			return send_from_directory('static', session['progress'])
		else:
			return send_from_directory('static', 'add.html')
	return redirect('/login')
Example #2
0
def download_files(type, timestamp):
    allowed_download_types = ['pdf', 'html', 'markdown', 'odt']
    timestamp = '%s' % timestamp
    if type not in allowed_download_types:
        return "No valid download type!"
    else:
        conv = Converter(session['title'], FOLDERS, timestamp)
        download_folder = os.path.join(FOLDERS['downloads'], timestamp)
        conv.prepare_xml()
        if type == 'pdf':
            conv.convert2markdown()
            try:
                conv.convert2pdf()
                filename = '%s.pdf' % timestamp
                return send_from_directory(download_folder,
                                           filename, as_attachment=True)
            except:
                return redirect(url_for('error'))
        elif type == 'html':
            conv.convert2markdown()
            conv.convert2html()
            filename = '%s.html' % timestamp
            return send_from_directory(download_folder,
                                       filename, as_attachment=True)
        elif type == 'odt':
            conv.convert2markdown()
            conv.convert2odt()
            filename = '%s.odt' % timestamp
            return send_from_directory(download_folder,
                                       filename, as_attachment=True)
        elif type == "markdown":
            conv.convert2markdown()
            filename = '%s.md' % timestamp
            return send_from_directory(download_folder,
                                       filename, as_attachment=True)
Example #3
0
def post_picture(name):
    f = os.path.join(PICTURES, "posts", name)
    fp = os.path.join(PICTURES, "posts")
    if os.path.isfile(f):
        return send_from_directory(fp, filename=name)
    else:
        return send_from_directory(fp, filename=NOTFOUND)
Example #4
0
def root():
	session_id = request.cookies.get('session_id')
	config = load_config('Server')
	db = Database(config['database_name'], ['users', 'sessions'])
	try:
		session_object_id = ObjectId(session_id)
	except:
		return remove_cookie()
	session = db.sessions.get({'_id': session_object_id})
	if session is None:
		return remove_cookie()
	user_id = session['user']
	try:
		user_object_id = ObjectId(user_id)
	except:
		return remove_session()
	user = db.users.get({'_id': user_object_id})
	if user is None:
		return remove_cookie()
	if user['priority'] == 'librarian':
		return send_from_directory('static', 'librarian.html')
	elif user['priority'] == 'student':
		return send_from_directory('static', 'student.html')
	elif user['priority'] == 'terminal':
		return send_from_directory('static', 'terminal.html')
Example #5
0
def index():
    if not app.config['DEBUG']:
        return __bad_request()

    if app.config['WEATHER_MODE']:
        return send_from_directory('public/weather', 'index.html')
    return send_from_directory('public', 'index.html')
Example #6
0
def retrieve(session_id, exp_id, filename):
    """ Retrieve the output file of an experiment.
    This method just returns you the direct file generated by our tool
    for a given experiment in a given session.

    @param session_id the session identifier uniquely identifying the
    MapQTL zip file and the JoinMap map file.
    @param exp_id the experiment identifier used to uniquely identify a
    run which may have specific parameters.
    @param filename the name of the file to retrieve within this session.
    """
    print 'mq2 %s -- %s -- %s' % (datetime.datetime.now(),
                                  request.remote_addr, request.url)
    if session_id == CONFIG.get('mq2', 'sample_session'):
        global UPLOAD_FOLDER
        UPLOAD_FOLDER = os.path.join(os.path.abspath(__file__),
                                     APP.static_folder)
    upload_folder = os.path.join(UPLOAD_FOLDER, session_id, exp_id)
    if filename != '%s.zip' % exp_id:
        return send_from_directory(upload_folder, filename)
    else:
        if os.path.exists(os.path.join(upload_folder, '%s.zip' % exp_id)):
            return send_from_directory(upload_folder, '%s.zip' % exp_id)
        zf = zipfile.ZipFile(os.path.join(upload_folder, '%s.zip' % exp_id),
                             mode='w')
        try:
            for filename in os.listdir(upload_folder):
                if not filename.endswith('.zip'):
                    zf.write(os.path.join(upload_folder, filename),
                             arcname=os.path.join(exp_id, filename),
                             compress_type=ZCOMPRESSION)
        except IOError, err:
            print 'ERROR while generating the zip file: %s' % err
        finally:
Example #7
0
def meta_router(route=''):
    print route
    try:
        env = get_env()
    except InvalidSite:
        return "404, not a real site."
    
    if env.globals['mode'] is None:
        if route == 'regenerate':
            if env.globals['authorized']:
                return regenerate_pages(env)
            else: return '', 403
        elif os.path.isfile('./designs/main/static/'+route):
            return send_from_directory('./designs/main/static', route)
        else:
            return main_env.get_template('editor.html').render(**env.globals)
        
    else:
        if env.globals['mode'] not in ['view', 'edit']: return "404, sorry bud (You're mode is wrong)", 404
        if route == 'login':
            if env.globals['context']['meta']['password'] == request.form.get('pwd'):
                resp = make_response(redirect('http://'+request.headers['Host']+'/'+request.args.get('target')))
                resp.set_cookie('pwd', hashlib.sha1(request.form.get('pwd')).hexdigest(), domain='.'+'.'.join(request.headers['Host'].split('.')[-3:]))
                return resp
            else:
                return env.get_template('login.html').render()
        elif os.path.isfile(env.globals['data_dir']+route) and route.startswith('ull/'):
            return send_from_directory(env.globals['data_dir'], route)
        elif os.path.isfile(env.globals['design_dir']+'static/'+route):
            return send_from_directory(env.globals['design_dir']+'static/', route)
        elif not env.globals['authorized']:
            return redirect('http://'+request.headers['Host']+'/login?target='+urlencode(route))
        else:
            return core_router(route, env) or ("404, Sorry dude", 404)
 def serve_roygbiv_html(path):
     try:
         return flask.send_from_directory('brain', path)
     except Exception as e:
         import roygbiv
         viz_dir = os.path.join(os.path.dirname(roygbiv.__file__), 'web')
         return flask.send_from_directory(viz_dir, path)
Example #9
0
def route_get_artist(name):
    """
    Search through our list of directories
    If match then return image from directory
    else return default image and fire google search
    """
    global image_download_thread
    name.replace("/", "")
    if name in image_scraper.get_directory_names():
        try:
            directory = "/Users/stevemurr/PycharmProjects/KCSMServer/images/" + name + "/"
            filename = name + "2.jpg_thumbnail.jpg"
            print(directory + filename)
            return send_from_directory(directory, filename, as_attachment=True)
        except:
            print("The image is probably being downloaded.")
            directory = "/Users/stevemurr/PycharmProjects/KCSMServer/images/KCSM/"
            filename = "KCSM2.jpg_thumbnail.jpg"
            print(directory + filename)
            return send_from_directory(directory, filename, as_attachment=True)
    else:
        directory = "/Users/stevemurr/PycharmProjects/KCSMServer/images/KCSM/"
        filename = "KCSM2.jpg_thumbnail.jpg"
        name = name.replace(' ', '%20')
        #urllib2.urlopen("http://localhost:5001/get_artist_images/" + name)
        return send_from_directory(directory, filename, as_attachment=True)
Example #10
0
def send_file():
    result = dict()
    fileName = request.json.get("filename")
    macAddress = request.json.get("macaddress")
    if not all([fileName, macAddress]):
        return sendfile_usage_error()
    html_root = app.instance_path
    fileName = fileName.encode('utf8')
    macAddress = macAddress.encode('utf8')
    macAddress = macAddress.replace(":", "")
    if fileName == "user-data.txt":
        if os.path.exists(html_root + "\\userdata\\" + macAddress + "\\" + fileName):
            return send_from_directory(html_root + "\\userdata\\" + macAddress + "\\", fileName)
        else:
            result["status"] = "Fail"
            result["status_code"] = 400
            result["message"] = "File does not exist"
            return send_response(result, result["status_code"])
    else:
        if fileName in ["availability-zone.txt", "cloud-identifier.txt", "instance-id.txt",
                        "local-hostname.txt", "local-ipv4.txt", "meta-data.txt", "public-hostname.txt",
                        "public-ipv4.txt", "public-keys.txt", "service-offering.txt", "vm-id.txt"]:
            return send_from_directory(html_root + "\\metadata\\" + macAddress + "\\", fileName)
        else:
            result["status"] = "Fail"
            result["status_code"] = 400
            result["message"] = "File does not exist"
            return send_response(result, result["status_code"])
Example #11
0
def export_script():
    global exportFile
    if request.method == 'POST':
        json_request = request.get_json(False, False, False)

        json_request['request'] = 'exportScript'

        daemon_response = send_request_to_daemon(json_request)

        if is_response_successful(daemon_response):
            fileName = json_request['model']['name'] + '.py'
            filePath = os.path.join(app.config['EXPORT_FOLDER'], fileName)

            with open(filePath, 'w') as fout:
                fout.write(daemon_response['script'])

            exportFile = fileName
            return send_from_directory(app.config['EXPORT_FOLDER'], fileName, as_attachment = True)

        else:
            return jsonify({'success' : False, 'reason' : daemon_response['reason']})

    elif request.method == 'GET':
        return send_from_directory(app.config['EXPORT_FOLDER'], exportFile, as_attachment = True)

    return jsonify({'success' : False, 'reason' : 'Non GET or POST'})
Example #12
0
def get_asset(path):
  try:
    b = Borg()
    web_image_dir = os.path.join(b.staticDir, 'assets')
    return send_from_directory(web_image_dir, path)
  except AttributeError:
    return send_from_directory('static/assets', path)
Example #13
0
def bootstrap_reroute(path):
  try:
    b = Borg()
    web_image_dir = os.path.join(b.staticDir, 'bootstrap')
    return send_from_directory(web_image_dir, path)
  except AttributeError:
    return send_from_directory('static/bootstrap', path)
Example #14
0
def dist_reroute(path):
  try:
    b = Borg()
    web_image_dir = os.path.join(b.staticDir, 'dist')
    return send_from_directory(web_image_dir, path)
  except AttributeError:
    return send_from_directory('static/dist', path)
Example #15
0
def fast_templates_reroute(path):
  try:
    b = Borg()
    web_image_dir = os.path.join(b.staticDir, 'fastTemplates')
    return send_from_directory(web_image_dir, path)
  except AttributeError:
    return send_from_directory('static/fastTemplates', path)
Example #16
0
def send_static_file(path, mimetype=None):
    static = os.path.join(app.root_path, 'static')

    if not mimetype:
        return send_from_directory(static, path)

    return send_from_directory(static, path, mimetype=None)
Example #17
0
    def test_send_from_directory_bad_request(self, app, req_ctx):
        app.testing = True
        app.root_path = os.path.join(os.path.dirname(__file__),
                                     'test_apps', 'subdomaintestmodule')

        with pytest.raises(BadRequest):
            flask.send_from_directory('static', 'bad\x00')
Example #18
0
def crushdata_withid(crush_id): 
	if request.method == "GET":
		if crush_id.endswith('.json'):
			return send_from_directory(filedir['json_maps'], crush_id)
		else:
			return send_from_directory(filedir['txt_maps'], crush_id + '.txt')

	if request.method == "PUT":
		try:
			inputdata = request.get_json()
		except:
			return "The given request is not valid JSON", 400

	
		if os.path.isfile(filedir['txt_maps'] + crush_id + ".metadata.json"):
			with open(filedir['txt_maps'] + crush_id + ".metadata.json") as mdfr:
				prevdata = json.loads(mdfr.read())
		else:
			prevdata = {}

		if "name" in inputdata:
			with open(filedir['txt_maps'] + crush_id + ".metadata.json", 'w') as mdfw:
				prevdata.update(inputdata)
				mdfw.write(json.dumps(prevdata))

		resp = make_response("It worked!")
		return resp
Example #19
0
def uploaded_file(filename):
    if filename.rsplit('-', 1)[0] == str(g.user.id):
        return send_from_directory(app.config['UPLOAD_FOLDER'],
                                   filename)
    else:
        return send_from_directory(app.config['UPLOAD_FOLDER'],
                                   '~Data.txt')  # fake file for the bots
Example #20
0
    def test_send_from_directory_bad_request(self, app, req_ctx):
        app.root_path = os.path.join(
            os.path.dirname(__file__), "test_apps", "subdomaintestmodule"
        )

        with pytest.raises(BadRequest):
            flask.send_from_directory("static", "bad\x00")
Example #21
0
def send_doc(path):
   siteURL = current_app.config.get('SITE_URL')

   location = current_app.config.get('DOCS')
   if location is None:
      abort(404)

   if location[0:4]=='http':
      url = location + path
      req = requests.get(url, stream = True,headers={'Connection' : 'close'})
      if req.headers['Content-Type'][0:9]=='text/html':
         return render_template_string(generate_template(current_app.config,'content.html'), siteURL=siteURL if siteURL is not None else request.url_root[0:-1], html=req.text, entry=None)
      else:
         return Response(stream_with_context(req.iter_content()), headers = dict(req.headers))

   else:

      dir = os.path.abspath(location)
      if path.endswith('.html'):

         glob = StringIO()
         try:
            with open(os.path.join(dir,path), mode='r', encoding='utf-8') as doc:
               peeked = doc.readline()
               if peeked.startswith('<!DOCTYPE'):
                  return send_from_directory(dir, path)
               glob.write(peeked)
               for line in doc:
                  glob.write(line)

               return render_template_string(generate_template(current_app.config,'content.html'), siteURL=siteURL if siteURL is not None else request.url_root[0:-1], html=glob.getvalue(), entry=None)
         except FileNotFoundError:
            abort(404)

      return send_from_directory(dir, path)
Example #22
0
    def send_static_file(self, filename):
        '''
        Override default static handling:
        - raises 404 if not debug
        - handle static aliases
        '''
        if not self.debug:
            self.logger.error('Static files are only served in debug')
            abort(404)

        cache_timeout = self.get_send_file_max_age(filename)

        # Default behavior
        if isfile(join(self.static_folder, filename)):
            return send_from_directory(self.static_folder, filename,
                                       cache_timeout=cache_timeout)

        # Handle aliases
        for prefix, directory in self.config.get('STATIC_DIRS', tuple()):
            if filename.startswith(prefix):
                real_filename = filename[len(prefix):]
                if real_filename.startswith('/'):
                    real_filename = real_filename[1:]
                if isfile(join(directory, real_filename)):
                    return send_from_directory(directory, real_filename,
                                               cache_timeout=cache_timeout)
        abort(404)
Example #23
0
def index(staticfile=None):
    """Useful if you want to be able to get things like .css and .js files"""
    if staticfile:
        # this doesn't perform well; should be set up in a proper webserver
        flask.send_from_directory('static', staticfile)
    else:
        return hello()
Example #24
0
def send_rec2(filename):
    filename1 = filename + "_b.png"
    filename2 = filename + "_a.png"
    if os.path.isfile(os.path.join(app.config['REC_FOLDER'], filename1)):
        response = make_response(send_from_directory(app.config['REC_FOLDER'], filename1))
        response.headers['Content-Disposition'] = "attachment; filename=" + filename1
        return response
    else:
        if os.path.isfile(os.path.join(app.config['REC_FOLDER'], filename2)):
            img_white=Image.open(os.path.join(app.config['REC_FOLDER'],filename2))
            img_white=img_white.convert("RGBA")
            iwdata=img_white.getdata()
            niwdata=[]
            for item in iwdata:
                if item[0]==255 and item[1]==255 and item[2]==255:
                    niwdata.append((255,255,255,0))
                else:
                    niwdata.append(item)
            img_white.putdata(niwdata)
            img_white.save(os.path.join(app.config['REC_FOLDER'],filename1),"PNG")

            response = make_response(send_from_directory(app.config['REC_FOLDER'], filename1))
            response.headers['Content-Disposition'] = "attachment; filename=" + filename1
            return response           
        else:
            return "-2"
Example #25
0
def get_img(img):
    '''
    Cache imdb images (imdb dont like no hotlinking...)
    '''
    if not path.isfile('cache/'+img):
        # query and store
        url = 'http://ia.media-imdb.com/images/M/' + img
        local_filename = path.join('cache', img)
        
        r, rem = None, 5
        while r==None and rem:
            rem -= 1
            try :
                r = requests.get(url, stream=True)
            except requests.ConnectionError as e:
                time.sleep(0.1)
                continue
            with open(local_filename, 'wb') as f:
                for chunk in r.iter_content(chunk_size=1024): 
                    if chunk:
                        f.write(chunk)
                        f.flush()
        if r == None :
            return send_from_directory('static','error.jpg')
    
    return send_from_directory('cache',img) 
Example #26
0
def get(settings=''):
    (year, code, website, server, imagepathloc, imagepathweb, viewerpath, path, geojson, datarange, custom) = readglobalvars()
    image = request.args.get('image')
    gzip = request.args.get('nlgis')
    svg = request.args.get('svg')
    pdf = request.args.get('pdf')
    outfile = ''

    thismimetype='image'
    if image:
	outfile = image
    if gzip:
	thismimetype = 'application/x-gzip'
	outfile = gzip
    if svg:
	thismimetype = 'text/plain'
	outfile = svg
    if pdf:
	thismimetype = 'application/pdf'
	outfile = pdf
  	
    if image:
        return send_from_directory(imagepathloc, outfile, mimetype=thismimetype)
    else:
	return send_from_directory(imagepathloc, outfile, as_attachment=True)
Example #27
0
File: views.py Project: osa1/kweb
def download_file():
    file_path = get_file_path().split('/')
    file_name = file_path[-1]
    file_directory = '/'.join(file_path[:-1])
    if os.path.isdir(os.path.join(file_directory, file_name)):
        zip_info = get_directory_zip(os.path.join(file_directory, file_name))
        return send_from_directory(zip_info[0], zip_info[1], as_attachment=True, attachment_filename = file_name + '.zip')
    return send_from_directory(file_directory, file_name, as_attachment=True)
 def _server_configs(self):
     env = EnvironmentChecker(self._environment_settings_loader['APP_SETTINGS'])
     if env.is_production():
         return send_from_directory(self._static_files_root_folder_path, 'configs/production.js')
     elif env.is_development():
         return send_from_directory(self._static_files_root_folder_path, 'configs/development.js')
     else:
         raise ConfigurationError("cannot retrieve app configs. make sure environment is configured")
Example #29
0
def show_photo(kind, filename):
	if not session.get('logged_in'):
		abort(401)
	if kind == 'equips':
		return send_from_directory(app.config['UPLOAD_FOLDER_EQUIP'],filename)
	if kind == 'groups':
		return send_from_directory(app.config['UPLOAD_FOLDER_GROUP'],filename)
	return redirect(url_for('show_entries'))
Example #30
0
def dev(filename):
    static_app = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../app'))
    static_tmp = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../.tmp'))

    if os.path.isfile( os.path.join(static_tmp, filename) ):
        return send_from_directory(static_tmp, filename)
    else:
        return send_from_directory(static_app, filename)
Example #31
0
def get_initial_page():
    return flask.send_from_directory(directory='HTML_pages',
                                     filename='initial_page.html')
Example #32
0
def uploadpics(filename):
    return send_from_directory(file_path, filename)
Example #33
0
def download_file():
    return send_from_directory('.', 'shortscoreOutput.zip', as_attachment=True)
Example #34
0
def serve_js(path):
    return send_from_directory(f'{static_dir}/javascripts', path)
Example #35
0
def send_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'] + '/img/', filename)
Example #36
0
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
Example #37
0
def download(filename):
    # 中文名的文件无法下载  2017-12-3 14:38:19
    return send_from_directory(upload_file_folder,filename, as_attachment=True)
Example #38
0
def uploaded_file(filename):
    return send_from_directory(current_app.config['UPLOAD_DIR'], filename)
Example #39
0
def static_from_root():
    return send_from_directory(app.static_folder, request.path[1:])
Example #40
0
def static_files(path):
    return send_from_directory('static/%s' % (request.path.split('/')[1]),
                               path)
Example #41
0
def assets(path):
    return send_from_directory('assets', path)
Example #42
0
def video():
    adsjson = request.get_json()
    run(adsjson)
    return send_from_directory(directory=app.root_path, filename='holy.avi')
Example #43
0
def uploaded_file():
    return send_from_directory('./','priceGraph.png')
Example #44
0
def serve_css(path):
    return send_from_directory(f'{static_dir}/stylesheets', path)
Example #45
0
 def send_build_dir(path: str) -> Any:
     return send_from_directory(str(BUILD_DIR), path)
Example #46
0
def static_file(path):
    static_folder = os.path.join(os.getcwd(), 'static')
    return send_from_directory(static_folder, path)
Example #47
0
def content(path: str) -> werkzeug.wrappers.Response:
    storage = _cfg('storage')
    if not storage or not os.path.isfile(os.path.join(storage, path)):
        abort(404)
    return send_from_directory(storage + "/", path)
Example #48
0
 def send_files(path):
     return send_from_directory(app.config["STATIC_DIR"], path)
Example #49
0
def send_image(path):
    root_dir = os.getcwd()
    return send_from_directory(os.path.join(root_dir, 'uploads'), path)
Example #50
0
def home():
    return send_from_directory(static_dir, 'index.html')
Example #51
0
def send_font(filename):
    return send_from_directory('/var/www/html/tada/UI/vendor/font-awesome/fonts/',filename)
Example #52
0
def serve_image(path):
    from flask import send_from_directory, current_app
    config = current_app.config
    return send_from_directory(config['imagedir'], path)
Example #53
0
def posterimgs(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
Example #54
0
def get_file(path):
    """Download a file."""
    return send_from_directory(UPLOAD_DIRECTORY, path, as_attachment=True)
Example #55
0
 def static_proxy(path: str) -> Response:  # pylint: disable=unused-variable
     return send_from_directory(build_dir, path)
Example #56
0
def send_img(filename):
    return send_from_directory('/var/www/html/tada/UI/img',filename,mimetype='image/png')
Example #57
0
def get_index():
    """
    :return: Returns the main site html.
    """
    return send_from_directory(html_dir, 'index.html', mimetype='text/html')
Example #58
0
 def static_js_proxy(path: str) -> Response:  # pylint: disable=unused-variable
     return send_from_directory(os.path.join(build_dir, 'static/js'), path)
Example #59
0
def serve_image(path):
    return send_from_directory(f'{static_dir}/images', path)
Example #60
0
def catch_compiled_templates(path):
    return send_from_directory(templates_dir, path)