def upload(app, request): download_dir = app.config.get("DATA_DIR") # root download dir file_id = generate_uuid() # This will create a class that gives us the ability to save files onto the # file system. All saved files will be placed in the "default_dest" folder # under the subdirectory specified by the set name. In this case, the files # will be stored in $DATA_DIR/files/<filename> fileSet = flask_uploads.UploadSet( "files", extensions=flask_uploads.ALL, default_dest=download_dir ) filename = fileSet.save( request.files["file"], name=f"{file_id}." ) logger.debug(f'Uploaded file: {filename}') return {"file_id": file_id}
import ssl import smtplib import threading import email import flask import flask_bcrypt import flask_uploads from urllib.parse import urlparse, urljoin # Note that if a module imports this as only "bcrypt", it will override # the actual `bcrypt` library if imported. To avoid namespace issues, # do instead: `from flasquelistan import util; util.bcrypt(...)` bcrypt = flask_bcrypt.Bcrypt() image_uploads = flask_uploads.UploadSet('images', flask_uploads.IMAGES) def send_email(toaddr, subject, body): """Send an email with SMTP & STARTTLS. Uses the best security defaults according to the python documentation at the time of writing: https://docs.python.org/3/library/ssl.html#ssl-security "[ssl.create_default_context()] will load the system’s trusted CA certificates, enable certificate validation and hostname checking, and try to choose reasonably secure protocol and cipher settings." """ msg = email.message.EmailMessage() msg.set_content(body)
ADMIN_USERNAME = '******' ADMIN_PASSWORD = '******' COUCHDB_SERVER = 'http://localhost:5984/' COUCHDB_DATABASE = 'flask-photolog' # application app = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('PHOTOLOG_SETTINGS', silent=True) # uploads uploaded_photos = flask_uploads.UploadSet('photos', flask_uploads.IMAGES) flask_uploads.configure_uploads(app, uploaded_photos) # documents manager = CouchDBManager() def unique_id(): return hex(uuid.uuid4().time)[2:-1] class Post(Document): doc_type = 'post' title = TextField() filename = TextField()
import time from functools import wraps from werkzeug.utils import secure_filename import db app = flask.Flask(__name__) CORS(app) app.config["DEBUG"] = True app.config['CORS_HEADERS'] = 'Content-Type' app.config['Access-Control-Allow-Origin'] = '*' images = flask_uploads.UploadSet( 'images', flask_uploads.IMAGES, default_dest=lambda app: os.path.join(app.root_path, 'images'), ) flask_uploads.configure_uploads(app, images) def byte_to_string(byte_string): return byte_string.decode("utf-8") def parse_list_to_map(result): result_map = {} if result: for row in result: if len(row[1:]) <= 1: result_map[row[0]] = row[1] else: result_map[row[0]] = row[1:]
import flask_wtf import flask_wtf.file #from flask import Flask, render_template import flask_uploads #import UploadSet, configure_uploads, IMAGES, patch_request_class #from flask_wtf import FlaskForm #from flask_wtf.file import FileField, FileRequired, FileAllowed #from wtforms import SubmitField import wtforms import frontend.bookform as bookform import bookanalyzer app = flask.Flask(__name__) app.config['SECRET_KEY'] = 'I have a dream' app.config['UPLOADED_BOOKS_DEST'] = "/tmp/" books = flask_uploads.UploadSet('books', tuple(["epub"])) flask_uploads.configure_uploads(app, books) flask_uploads.patch_request_class( app) # set maximum file size, default is 16MB class UploadForm(flask_wtf.FlaskForm): book = flask_wtf.file.FileField(validators=[ flask_wtf.file.FileAllowed(books, u'Only .epub files!'), flask_wtf.file.FileRequired(u'File was empty!') ]) submit = wtforms.SubmitField(u'Upload') @app.route('/', methods=['GET', 'POST']) def upload_file():
import os.path import random import string from flask import render_template, flash, redirect, url_for, request, abort, send_file import flask_uploads import model from model import db from shelf import app documents = flask_uploads.UploadSet( 'documents', flask_uploads.DOCUMENTS + flask_uploads.TEXT + ('pdf', 'ppt')) flask_uploads.configure_uploads(app, documents) class Document(object): """ Class to mediate storing and retrieving documents to and from database. """ doc_id_chars = string.letters + string.digits def __init__(self, fs_name, friendly_name): self.fs_name = fs_name self.friendly_name = friendly_name self.doc_id = None @classmethod def gen_doc_id(cls): return ''.join(random.sample(cls.doc_id_chars, 5))
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, PasswordField, BooleanField, DecimalField, IntegerField from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms.validators import DataRequired, Email, Length import flask_uploads # Library that contains all the forms and upload patterns LENGTH = 200 # Create an upload set times = flask_uploads.UploadSet("times", flask_uploads.DATA) photos = flask_uploads.UploadSet("photos", flask_uploads.IMAGES) def format_exts(exts: list): """ Returns a formatted list of extentions. """ return ", ".join(["." + ext for ext in exts]) class UploadForm(FlaskForm): file = FileField("Choose file", [FileRequired(), FileAllowed(times, "Data files only.")]) class PhotoForm(FlaskForm): photo = FileField("", [ FileRequired(), FileAllowed( photos, "Only files with the extentions {} are allowed.".format(
def construct_app(): """ Constructs the Flask app by taking the following steps: 1. Setup and configure the app 2. Setup JSON encoding for Flask and flask_restful to handle F prime types natively 3. Setup standard pipeline used throughout the system 4. Create Restful API for registering flask items 5. Setup flask_uploads settings 6. Register all restful endpoints :return: setup app """ app = flask.Flask(__name__, static_url_path="") app.config.from_object("fprime_gds.flask.default_settings") # Override defaults from python files specified in 'FP_FLASK_SETTINGS' if "FP_FLASK_SETTINGS" in os.environ: app.config.from_envvar("FP_FLASK_SETTINGS") # JSON encoding seeting must come before restful app.json_encoder = fprime_gds.flask.json.GDSJsonEncoder app.config['RESTFUL_JSON'] = {'cls': app.json_encoder} # Standard pipeline creation pipeline = components.setup_pipelined_components( app.debug, app.logger, app.config["GDS_CONFIG"], app.config["DICTIONARY"], app.config["DOWNLINK_DIR"], app.config["LOG_DIR"], app.config["ADDRESS"], app.config["PORT"]) # Restful API registration api = flask_restful.Api(app) # File upload configuration, 1 set for everything uplink_set = flask_uploads.UploadSet("uplink", flask_uploads.ALL) flask_uploads.configure_uploads(app, [uplink_set]) # Application routes api.add_resource(fprime_gds.flask.commands.CommandDictionary, "/dictionary/commands", resource_class_args=[pipeline.dictionaries.command_name]) api.add_resource(fprime_gds.flask.commands.CommandHistory, "/commands", resource_class_args=[pipeline.histories.commands]) api.add_resource(fprime_gds.flask.commands.Command, "/commands/<command>", resource_class_args=[pipeline]) api.add_resource(fprime_gds.flask.events.EventDictionary, "/dictionary/events", resource_class_args=[pipeline.dictionaries.event_id]) api.add_resource(fprime_gds.flask.events.EventHistory, "/events", resource_class_args=[pipeline.histories.events]) api.add_resource(fprime_gds.flask.channels.ChannelDictionary, "/dictionary/channels", resource_class_args=[pipeline.dictionaries.channel_id]) api.add_resource(fprime_gds.flask.channels.ChannelHistory, "/channels", resource_class_args=[pipeline.histories.channels]) api.add_resource(fprime_gds.flask.updown.Destination, "/upload/destination", resource_class_args=[pipeline.files.uplinker]) api.add_resource(fprime_gds.flask.updown.FileUploads, "/upload/files", resource_class_args=[pipeline.files.uplinker, uplink_set]) api.add_resource(fprime_gds.flask.updown.FileDownload, "/download/files", "/download/files/<string:source>", resource_class_args=[pipeline.files.downlinker]) # Optionally serve log files if app.config["SERVE_LOGS"]: api.add_resource(fprime_gds.flask.logs.FlaskLogger, "/logdata", resource_class_args=[app.config["LOG_DIR"]]) return app, api
"""Configuration for the flask_uploads extension that handles file uploading""" import os import flask_uploads audio_files = flask_uploads.UploadSet(name="audio", extensions=("wav", "wave", "mp3")) text_files = flask_uploads.UploadSet(name="text", extensions=("txt", "phonemes", "phonemes_and_tones")) # URL of files being served by this app uploads_url_base = 'uploads/' def configure_uploads(flask_app, base_upload_path=None) -> None: """Configure flask_uploads and upload paths""" flask_app.config[ 'MAX_CONTENT_LENGTH'] = 64 * 1024 * 1024 #max 64 MB file upload if base_upload_path: flask_app.config['BASE_UPLOAD_DIRECTORY'] = base_upload_path else: flask_app.config['BASE_UPLOAD_DIRECTORY'] = os.path.join( flask_app.instance_path, 'user_uploads') flask_app.config['UPLOADED_AUDIO_DEST'] = os.path.join( flask_app.config['BASE_UPLOAD_DIRECTORY'], 'audio_uploads') flask_app.config['UPLOADED_TEXT_DEST'] = os.path.join( flask_app.config['BASE_UPLOAD_DIRECTORY'], 'text_uploads') flask_app.config['UPLOADED_FILES_URL'] = uploads_url_base flask_uploads.configure_uploads(flask_app, (audio_files, text_files)) return None
import flask_uploads as u from app import app from flask import request, render_template, redirect, flash, url_for, send_from_directory, send_file import os files = u.UploadSet('files', u.IMAGES) ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app.config[ 'UPLOADED_FILES_DEST'] = '/Users/Kamila/PycharmProjects/students_manager/files' app.config[ 'UPLOAD_FOLDER'] = '/Users/Kamila/PycharmProjects/students_manager/files' u.configure_uploads(app, files) PATH = '/Users/Kamila/PycharmProjects/students_manager/files' def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def make_tree(path): tree = dict(name=os.path.basename(PATH), children=[]) try: lst = os.listdir(PATH) except OSError: pass else: for name in lst:
import base64 import datetime import email import hashlib import smtplib import ssl import threading from urllib.parse import urljoin, urlparse import flask import flask_uploads import phonenumbers import werkzeug from PIL import Image, ImageOps image_uploads = flask_uploads.UploadSet('images', flask_uploads.IMAGES) profile_pictures = flask_uploads.UploadSet('profilepictures', flask_uploads.IMAGES) def generate_secure_path_hash(expires, url, secret): data = f"{expires}{url}{flask.request.remote_addr} {secret}" binary_hash = hashlib.md5(data.encode()).digest() nginx_hash = base64.urlsafe_b64encode(binary_hash).decode().rstrip('=') return nginx_hash def url_for_image(filename, imagetype, width=None): if imagetype == 'profilepicture': base = profile_pictures.config.base_url
from pathlib import Path import flask_uploads UPLOAD_SETS = [ flask_uploads.UploadSet( "files", flask_uploads.ALL, lambda app: Path(app.config.get("DATA_DIR")).joinpath("files"), ) ] def configure_upload_sets(app): flask_uploads.configure_uploads(app, UPLOAD_SETS)
'css/fonts.css', 'css/style.css', output='gen/common.css', filters=['autoprefixer6', 'cleancss'], ), } assets = flask_assets.Environment(app) assets.register(bundles) login_manager = flask_login.LoginManager() login_manager.init_app(app) login_manager.login_view = '.login' login_manager.login_message_category = 'info' photo_set = flask_uploads.UploadSet('photos', flask_uploads.IMAGES) flask_uploads.configure_uploads(app, photo_set) def photo_resize_url(photo, size): if app.debug: return photo_set.url(photo.filename) return "{}img{}/{}".format(photo_set.config.base_url, size, photo.filename) def image_resize_url(image, size): if app.debug: return 'static/images/{}'.format(image)