def validate(self):
if not Form.validate(self):
return False
if self.uploadfile.name not in request.files:
self.uploadfile.errors.append("Please select a valid file.")
return False
self.file_ = request.files[self.uploadfile.name]
self.filename = secure_filename(self.file_.filename)
uploads = os.listdir(os.path.join(app.root_path, app.config['UPLOAD_FOLDER']))
if self.filename in uploads:
self.uploadfile.errors.append("A file with this name already exists.")
return False
if not self.filename:
self.uploadfile.errors.append("Invalid file name.")
return False
return True
python类root_path()的实例源码
def get_uploads():
"""gets the images and other files from the uploads directory
and returns two lists of tuples in the form (name, path)
"""
images = [('none', '')]
others = [('none', '')]
uploads = os.listdir(os.path.join(app.root_path, app.config['UPLOAD_FOLDER']))
uploads.remove(".gitignore")
# sort by time last modified
uploads.sort(key=lambda filename: os.stat(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename)).st_mtime)
image_extensions = ["png", "jpg", "jpeg", "gif", "bmp"]
for upload in uploads[::-1]:
if '.' in upload and upload.rsplit('.', 1)[1].lower() in image_extensions:
images.append(('/uploads/' + upload, upload))
else:
others.append(('/uploads/' + upload, upload))
return images, others
# custom widget for rendering a TinyMCE input
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
def browserconfig():
return send_from_directory(os.path.join(app.root_path, 'static'), 'browserconfig.xml', mimetype='text/xml')
def manifest():
return send_from_directory(os.path.join(app.root_path, 'static'), 'manifest.json', mimetype='application/json')
def init_app(app, logName):
formatter = logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]'
)
debug_log = os.path.join(app.root_path, 'logs/%s_debug.log'% logName)
not_exist_makedirs(os.path.dirname(debug_log))
debug_file_handler = RotatingFileHandler(
debug_log, maxBytes=100000, backupCount=10
)
debug_file_handler.setLevel(logging.INFO)
debug_file_handler.setFormatter(formatter)
app.logger.addHandler(debug_file_handler)
error_log = os.path.join(app.root_path, 'logs/%s_error.log'% logName)
not_exist_makedirs(os.path.dirname(error_log))
error_file_handler = RotatingFileHandler(
error_log, maxBytes=100000, backupCount=10
)
error_file_handler.setLevel(logging.ERROR)
error_file_handler.setFormatter(formatter)
app.logger.addHandler(error_file_handler)
app.logger.setLevel(logging.DEBUG)
def regist(app):
d = os.path.join(app.root_path, 'logs/debug.log')
e = os.path.join(app.root_path, 'logs/error.log')
path_list = {
'debug': d,
'error': e
}
common(path_list)
# from management TODO
def regist_bat(app, log_name):
d = os.path.join(app.root_path, 'logs/%s_debug.log'% log_name)
e = os.path.join(app.root_path, 'logs/%s_error.log'% log_name)
path_list = {
'debug': d,
'error': e
}
common(path_list)
def rootDir_web(path):
index_key = path.rfind('py')
if index_key > (len(path)-4):
return redirect(url_for('view_rents'))
return send_from_directory(os.path.join(app.root_path, '.'), path)
def index():
stats = ""
try:
stats = shelve.open(path.join(app.root_path, STATS_DB))
except Exception as e:
print("ERROR: Could not open STATS_DB")
print(e)
attempts = 0
try:
attempts = stats['total_attempts']
except Exception as e:
print(e)
ips = 0
try:
ips = stats['unique_ips']
except:
pass
countries = 0
try:
countries = stats['unique_countries']
except:
pass
try:
stats.close()
except:
pass
return render_template('index.html', total_logins=attempts, unique_addresses=ips, unique_countries=countries)
def upload_file():
form = UploadForm()
if form.validate_on_submit():
form.file_.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], form.filename))
form.file_.close()
time.sleep(0.5)
return redirect('/uploads')
return utils.render_with_navbar("upload/upload.html", form=form)
def show_uploads():
uploads = os.listdir(os.path.join(app.root_path, app.config['UPLOAD_FOLDER']))
uploads.remove('.gitignore')
# sorts uploads by time last modified, which should always be the same as time uploaded
uploads.sort(key=lambda filename: os.stat(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename)).st_mtime)
return utils.render_with_navbar("upload/uploads.html", uploads=uploads[::-1])
def delete_upload():
filename = request.args.get("name")
if not filename:
return redirect("/uploads")
filename = secure_filename(filename)
if not filename:
return redirect("/uploads")
try:
os.remove(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
except OSError:
return redirect("/uploads")
time.sleep(0.5)
return redirect("/uploads")