def confirm(): if request.method == 'POST': # ファイルが送信されているかどうか if 'upload_file' not in request.files: return redirect(url_for('index')) file = request.files['upload_file'] from_lang = request.form['from_lang'] to_lang = request.form['to_lang'] # target_text = request.form['target_text'] if file.filename == '': return redirect(request.url) if file and functions.allowed_file(file.filename, ALLOWED_EXTENSIONS): filename = secure_filename(file.filename) # file_img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) text = functions.connect_s3(config.S3_ACCESS_KEY, config.S3_SECRET_KEY, "c-tas-uploads", filename) # text = functions.img2digit(uploaded_file) trans_text = functions.lang_translation(text, from_lang, to_lang) return render_template('confirm.html', before_text=text, after_text=trans_text) else: return redirect(url_for('index'))
def upload(dataset_id): ''' Upload a zip of one shapefile to datastore ''' datastore = make_datastore(app.config['DATASTORE']) # Check that they uploaded a .zip file if not request.files['file'] or not allowed_file( request.files['file'].filename): return make_response("Only .zip files allowed", 403) # Upload original file to S3 zip_buff = StringIO(request.files['file'].read()) zip_base = '{0}/uploads/trail-segments'.format(dataset_id) datastore.write(zip_base + '.zip', zip_buff) # Get geojson data from shapefile shapefile_path = unzip(zip_buff) geojson_obj = shapefile2geojson(shapefile_path) # Compress geojson file geojson_zip = StringIO() geojson_raw = json.dumps(geojson_obj) zip_file(geojson_zip, geojson_raw, 'trail-segments.geojson') # Upload .geojson.zip file to datastore datastore.write(zip_base + '.geojson.zip', geojson_zip) # Show sample data from original file return redirect('/datasets/' + dataset_id + "/sample-segment")
def classify(): """ Receives POST request containing files Returns JSON of files and their classification """ try: data = {'user_id': 'None', 'files': []} #get the request parameters params = request.json if (params == None): params = request.args # if parameters are found, return a prediction if (params != None): user_id = request.form['user_id'] data['user_id'] = user_id files = request.files.getlist('file') instance = {} for file in files: if file and allowed_file(file.filename): file_type, prediction = parse_classify(file) data["files"].append({ 'file name': file.filename, 'file size in bytes': file.seek(0, 2), 'file type': file_type, 'prediction': prediction }) return jsonify(data) except Exception as e: return str(e)
def upload(dataset_id): ''' Upload a zip of one shapefile to datastore ''' datastore = make_datastore(app.config['DATASTORE']) # Check that they uploaded a .zip file if not request.files['file'] or not allowed_file(request.files['file'].filename): return make_response("Only .zip files allowed", 403) # Upload original file to S3 zip_buff = StringIO(request.files['file'].read()) zip_base = '{0}/uploads/trail-segments'.format(dataset_id) datastore.write(zip_base + '.zip', zip_buff) # Get geojson data from shapefile shapefile_path = unzip(zip_buff) geojson_obj = shapefile2geojson(shapefile_path) # Compress geojson file geojson_zip = StringIO() geojson_raw = json.dumps(geojson_obj) zip_file(geojson_zip, geojson_raw, 'trail-segments.geojson') # Upload .geojson.zip file to datastore datastore.write(zip_base + '.geojson.zip', geojson_zip) # Show sample data from original file return redirect('/datasets/' + dataset_id + "/sample-segment")
def home(): # investigate https://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html#userguide-quickstart if request.method == 'POST': if request.form['submit_button'] == 'upload': file = request.files['file'] if file and allowed_file(file.filename): my_df.home_file = file.filename if file.filename.rsplit('.', 1)[1].lower() == 'csv': my_df.df = pd.read_csv(request.files.get('file')) if file.filename.rsplit('.', 1)[1].lower() == 'xlsx' or \ file.filename.rsplit('.', 1)[1].lower() == 'xls': my_df.df = pd.read_excel(request.files.get('file')) if request.form['submit_button'] == 'update': my_df.df = pd.DataFrame(np.reshape(request.values.getlist('df'), (11, 6))) # fix, not flexible to update dfs my_df.df.columns = ['Internal Perspective', 'External Perspective', 'Peer rating', 'Social media', 'News reports', 'Survey data'] x_dim_index = request.values.getlist('x_dim') x_dim_index = [int(x) for x in x_dim_index] my_df.x_dim = my_df.df.iloc[:, x_dim_index].astype(float).mean(axis=1) y_dim_index = request.values.getlist('y_dim') y_dim_index = [int(y) for y in y_dim_index] my_df.y_dim = my_df.df.iloc[:, y_dim_index].astype(float).mean(axis=1) '''nasty piece of temp json to test courtesy of https://github.com/plotly/plotlyjs-flask-example/blob/master/app.py''' graphs = [ dict( data=[ dict( x=my_df.x_dim, y=my_df.y_dim, mode='markers', text=my_df.df.index.values ), ], layout=dict( title='Materiality matrix', hovermode='closest', xaxis=dict( title='x-axis', rangemode='tozero' ), yaxis=dict( title='y-axis', rangemode='tozero' ) ) ) ] ids = ['graph-{}'.format(i) for i, _ in enumerate(graphs)] plot = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder) df = my_df.df.style.format('<input type="number" name="df" value="{}" />').hide_index().render() return render_template('matrix.html', datadf=df, ids=ids, graphJSON=plot, filename=my_df.home_file)
def uploadSyllabus(n): '''After creating a course, a student may upload a syllabus pdf to that course page''' if request.method == 'GET': return render_template('syl_upload.html') else: if 'file' not in request.files: flash('No file part') file = request.files['file'] if file.filename == '': flash('No selected file') if file and functions.allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) functions.saveToDB(n, file.filename) return render_template('home.html', courses = functions.getRecommended())
def updateSyllabus(cid): #uses same functions as upload syllabus...not updating the course table if request.method == 'GET': return render_template('update_syl.html') else: if 'file' not in request.files: flash('No file part') file = request.files['file'] if file.filename == '': flash('No selected file') if file and functions.allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) functions.saveToDB(cid, file.filename) #bring them back to the updated course page return redirect(url_for('showCourse', cid=cid))
def uploadSyllabus(n): if request.method == 'GET': return render_template('syl_upload.html') else: if 'file' not in request.files: flash('No file part') file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') if file and functions.allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) functions.saveToDB(n, file.filename) return render_template('home.html', courses=functions.getRecommended())
def upload_file(): username = session['username'] if check_grupa(username) == check_grupa('admin'): if request.method == 'POST': if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join('static/storage', filename)) return redirect(url_for('index', filename=filename)), flash('Upload file successfull') return render_template('upload.html', info=username, grupa=check_grupa(username))
def validate_upload(dataset_id): ''' ''' datastore = make_datastore(app.config['DATASTORE']) # Check that they uploaded a .zip file if not request.files['file'] or not allowed_file( request.files['file'].filename): return make_response("Only .zip files allowed", 403) # Read zip data to buffer zipfile_data = StringIO() zipfile_path = '{0}/uploads/open-trails.zip'.format(dataset_id) request.files['file'].save(zipfile_data) # Upload original file data to S3 datastore.write(zipfile_path, zipfile_data) # Validate data locally. zf = zipfile.ZipFile(zipfile_data, 'r') local_dir = mkdtemp(prefix='validate-') names = [ 'trail_segments.geojson', 'named_trails.csv', 'trailheads.geojson', 'stewards.csv', 'areas.geojson' ] for name in sorted(zf.namelist()): base, (_, ext) = os.path.basename(name), os.path.splitext(name) if base in names: with open(os.path.join(local_dir, base), 'w') as file: file.write(zf.open(name).read()) args = [os.path.join(local_dir, base) for base in names] messages, succeeded = check_open_trails(*args) # Clean up after ourselves. shutil.rmtree(local_dir) path = '{0}/opentrails/validate-messages.json'.format(dataset_id) datastore.write(path, StringIO(json.dumps(messages))) # Show sample data from original file return redirect('/checks/' + dataset_id + "/results", code=303)
def upload_file(): if request.method == 'POST': if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No selected file') return redirect(request.url) if file and functions.allowed_file(file.filename, ALLOWED_EXTENSIONS): filename = secure_filename(file.filename) print('uploaded ' + filename) if functions.check_file_not_exist(app.config['UPLOAD_FOLDER'], filename): file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('uploaded_file', filename=filename)) else: return redirect( url_for('uploaded_existed_file', filename=filename))
def validate_upload(dataset_id): ''' ''' datastore = make_datastore(app.config['DATASTORE']) # Check that they uploaded a .zip file if not request.files['file'] or not allowed_file(request.files['file'].filename): return make_response("Only .zip files allowed", 403) # Read zip data to buffer zipfile_data = StringIO() zipfile_path = '{0}/uploads/open-trails.zip'.format(dataset_id) request.files['file'].save(zipfile_data) # Upload original file data to S3 datastore.write(zipfile_path, zipfile_data) # Validate data locally. zf = zipfile.ZipFile(zipfile_data, 'r') local_dir = mkdtemp(prefix='validate-') names = ['trail_segments.geojson', 'named_trails.csv', 'trailheads.geojson', 'stewards.csv', 'areas.geojson'] for name in sorted(zf.namelist()): base, (_, ext) = os.path.basename(name), os.path.splitext(name) if base in names: with open(os.path.join(local_dir, base), 'w') as file: file.write(zf.open(name).read()) args = [os.path.join(local_dir, base) for base in names] messages, succeeded = check_open_trails(*args) # Clean up after ourselves. shutil.rmtree(local_dir) path = '{0}/opentrails/validate-messages.json'.format(dataset_id) datastore.write(path, StringIO(json.dumps(messages))) # Show sample data from original file return redirect('/checks/' + dataset_id + "/results", code=303)
def scorecard(): id = request.form.get('id', None) user = User.query.get(id) file = request.files['file'] if file and file.filename != '' and allowed_file(file.filename, ALLOWED_EXTENSIONS_IMAGES): filename = secure_filename(file.filename) file.save(os.path.join(os.path.join(app.config['UPLOAD_FOLDER'], 'img/files'), filename)) else: return jsonify({"msg": "File not allowed"}), 400 if file: user.file = filename db.session.commit() return jsonify(user.serialize()), 200
def put(self, project_id): if 'file' not in request.files: abort(404, message="No file part in the request") file = request.files['file'] if file.filename == '': abort(404, message="No file selected for uploading") if file and allowed_file(file.filename): filename = secure_filename(file.filename) #path to file path = app.config['UPLOAD_FOLDER'] + '/' + filename file.save(path) project = Projects.query.filter_by(id=project_id).first() project.user_stories = path db.session.add(project) db.session.commit() return jsonify({ 'message': 'file successfully uploaded!', 'status_code': '201' }) else: abort(400, message="file type not allowed")
def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and fn.allowed_file(file.filename): filename = secure_filename(file.filename) file_path = os.path.abspath(app.config['UPLOAD_FOLDER']) file.save(os.path.join(file_path, filename)) print(file_path) fn.insertData(file_path, filename) return redirect(url_for('uploaded_file', filename=filename)) # Set The upload HTML template '\templates\uploadForm.html' return render_template('uploadForm.html')
def create_post(): if request.method == 'POST': try: title = request.form.get('title') body = request.form.get('body') author = current_user.login p = Post(title=title, body=body, author=author) db.session.add(p) db.session.commit() except Exception: raise (Exception) photos = request.form.get('files') photos = json.loads(photos) for photo in photos: if allowed_file(photo['name']): img = Photos(link='static/images/' + slugify(str(p.created), '') + photo['name'], post_id=p.id) db.session.add(img) db.session.commit() image_data = re.sub('^data:image/.+;base64,', '', photo['dataURL']) image = Image.open( io.BytesIO(base64.decodebytes(image_data.encode()))) image.save( UPLOAD_FOLDER + '/' + slugify(str(p.created), '') + photo['name'], 'JPEG') last_post = Post.query.order_by(Post.id.desc()).first() last_alert = Alert.query.order_by(Alert.id.desc()).first() return render_template('create_post.html', last_post=last_post, last_alert=last_alert, weekDays=rusWeekDays, months=rusMonths)
def setimgblog(id=None): if request.method == 'PUT': file = request.files['blogimagen'] if file and file.filename != '' and allowed_file( file.filename, ALLOWED_EXTENSIONS_IMAGES): filename = secure_filename(file.filename) file.save( os.path.join( os.path.join(app.config['UPLOAD_FOLDER'], 'img/blog'), filename)) else: return jsonify({"msg": "File incorrect"}), 400 blogs = Blogs.query.get(id) if not blogs: return jsonify({"msg": "Not found"}), 404 if file: blogs.blogimagen = filename db.session.commit() return jsonify(blogs.serialize()), 201
def setavatar(id=None): if request.method == 'PUT': file = request.files['avatar'] if file and file.filename != '' and allowed_file( file.filename, ALLOWED_EXTENSIONS_IMAGES): filename = secure_filename(file.filename) file.save( os.path.join( os.path.join(app.config['UPLOAD_FOLDER'], 'img/avatars'), filename)) else: return jsonify({"msg": "File is not correct "}), 400 users = Users.query.get(id) if not users: return jsonify({"msg": "Not Found"}), 404 if file: users.avatar = filename db.session.commit() return jsonify(users.serialize()), 201
def blog(id=None): if request.method == 'GET': if id is not None: blog = Blogs.query.get(id) if blog: return jsonify(blog.serialize()), 200 else: return jsonify({"msg": "Blog not found"}), 404 else: blogs = Blogs.query.all() blogs = list(map(lambda blog: blog.serialize(), blogs)) return jsonify(blogs), 200 if request.method == 'POST': title = request.form.get('title', None) bintro = request.form.get('bintro', None) publictext = request.form.get('publictext', None) privatext = request.form.get('privatext', None) if not title or title == "": return jsonify({"msg": "Insert the blog title"}), 400 if not bintro or bintro == "": return jsonify({"msg": "Insert the blog introduction"}), 400 if not publictext or publictext == "": return jsonify({"msg": "Insert the blog public text"}), 400 if not privatext or privatext == "": return jsonify({"msg": "Insert the blog private text"}), 400 # if not blogimagen or blogimagen == "": # return jsonify({"msg":"Debes agregar una foto para el blog"}), 400 file = request.files['blogimagen'] if file and file.filename != '' and allowed_file( file.filename, ALLOWED_EXTENSIONS_IMAGES): filename = secure_filename(file.filename) file.save( os.path.join( os.path.join(app.config['UPLOAD_FOLDER'], 'img/blog'), filename)) else: return jsonify({"msg": "Incorrect File"}), 400 blogs = Blogs() blogs.title = title blogs.bintro = bintro blogs.publictext = publictext blogs.blogvideo = blogvideo blogs.privatext = privatext if file: blogs.blogimagen = filename db.session.add(blogs) db.session.commit() blogs = Blogs.query.all() blogs = list(map(lambda blog: blog.serialize(), blogs)) return jsonify(blogs), 201 if request.method == 'PUT': title = request.json.get('title', None) bintro = request.json.get('bintro', None) publictext = request.json.get('publictext', None) privatext = request.json.get('privatext', None) if not title or title == "": return jsonify({"msg": "Insert the blog title"}), 400 if not bintro or bintro == "": return jsonify({"msg": "Insert the blog introduction"}), 400 if not publictext or publictext == "": return jsonify({"msg": "Insert the blog public text"}), 400 if not privatext or privatext == "": return jsonify({"msg": "Insert the blog private text"}), 400 blogput = Blogs.query.get(id) #busca por el id if not blogput: return jsonify({"msg": "Not Found" }), 404 # para no actualizar algo q no existe blogput.title = title blogput.bintro = bintro blogput.publictext = publictext blogput.privatext = privatext db.session.commit() blogput = Blogs.query.all() blogput = list(map(lambda blog: blog.serialize(), blogput)) return jsonify(blogput), 200 if request.method == 'DELETE': blog = Blogs.query.get(id) if not blog: return jsonify({"msg": "Blog not found"}), 404 db.session.delete(blog) db.session.commit() return jsonify({"msg": "Blog deleted"}), 200
def register(): #if not request.is_form: # return jsonify({"msg": "Missing Form request"}), 400 nombre = request.form.get('nombre', '') apellido = request.form.get('apellido', '') rut = request.form.get('rut', '') email = request.form.get('email', None) pais = request.form.get('pais', '') ciudad = request.form.get('ciudad', '') sexo = request.form.get('sexo', '') password = request.form.get('password', None) #avatar = request.json.get('avatar', '') #VALIDACIONES OBLIGATORIAS if not nombre or nombre == '': return jsonify({"msg": "Missing nombre"}), 400 if not apellido or apellido == '': return jsonify({"msg": "Missing apellido"}), 400 if not rut or rut == '': return jsonify({"msg": "Missing rut"}), 400 if not email or email == '': return jsonify({"msg": "Missing email"}), 400 if not pais or pais == '': return jsonify({"msg": "Missing País"}), 400 if not ciudad or ciudad == '': return jsonify({"msg": "Missing Ciudad"}), 400 if not password or password == '': return jsonify({"msg": "Missing password."}), 400 user = User.query.filter_by(email=email).first() if user: return jsonify({"msg": "email already exist"}), 400 userrut = User.query.filter_by(rut=rut).first() if userrut: return jsonify({"msg": "rut already exist"}), 400 file = request.files['avatar'] if file and file.filename != '' and allowed_file( file.filename, ALLOWED_EXTENSIONS_IMAGES ): #si existe el archivo y esta dentro de las extensiones permitidas filename = secure_filename(file.filename) file.save( os.path.join( os.path.join(app.config['UPLOAD_FOLDER'], 'images/avatars'), filename)) else: return jsonify({ "msg": "Archivo no permitido, debe ser de extensión png, jpg, jpeg, gif o svg" }), 400 user = User() # se crea una instancia de la clase User #asignando valores a los campos corresp. user.nombre = nombre user.apellido = apellido user.rut = rut user.email = email user.pais = pais user.ciudad = ciudad user.sexo = sexo user.password = bcrypt.generate_password_hash(password) if file: user.avatar = filename db.session.add(user) #se agrega todo lo anterior y se hace commit db.session.commit() access_token = create_access_token(identity=user.email) data = {"access_token": access_token, "user": user.serialize()} return jsonify(data), 201
def blog(id=None): if request.method == 'GET': if id is not None: blog = Blog.query.get(id) if blog: return jsonify(blog.serialize()), 200 else: return jsonify({"msg": "Not Found"}), 404 else: blogs = Blog.query.all() blogs = list(map(lambda blog: blog.serialize(), blogs)) return jsonify(blogs), 200 if request.method == 'POST': e_titulo = request.form.get('e_titulo', None) e_cuerpo = request.form.get('e_cuerpo', None) e_fecha = request.form.get('e_fecha', None) if not e_titulo and e_titulo == "": return jsonify({"msg": "Field titulo is required"}), 400 if not e_cuerpo and e_cuerpo == "": return jsonify({"msg": "Field cuerpo is required"}), 400 if not e_fecha and e_fecha == "": return jsonify({"msg": "Field fecha is required"}), 400 file = request.files['e_imagen'] if file and file.filename != '' and allowed_file( file.filename, ALLOWED_EXTENSIONS_IMAGES): filename = secure_filename(file.filename) file.save( os.path.join( os.path.join(app.config['UPLOAD_FOLDER'], 'images/blogs'), filename)) else: return jsonify({"msg": "File not allowed"}), 400 blog = Blog() blog.e_titulo = e_titulo blog.e_cuerpo = e_cuerpo blog.e_fecha = e_fecha if file: blog.e_imagen = filename db.session.add(blog) db.session.commit() return jsonify(blog.serialize()), 201 if request.method == 'PUT': e_titulo = request.form.get('e_titulo', None) e_cuerpo = request.form.get('e_cuerpo', None) e_fecha = request.form.get('e_fecha', None) if not e_titulo and e_titulo == "": return jsonify({"msg": "Field titulo is required"}), 400 if not e_cuerpo and e_cuerpo == "": return jsonify({"msg": "Field cuerpo is required"}), 400 if not e_fecha and e_fecha == "": return jsonify({"msg": "Field fecha is required"}), 400 file = request.files['e_imagen'] if file and file.filename != '' and allowed_file( file.filename, ALLOWED_EXTENSIONS_IMAGES): filename = secure_filename(file.filename) file.save( os.path.join( os.path.join(app.config['UPLOAD_FOLDER'], 'images/blogs'), filename)) else: return jsonify({"msg": "File not allowed"}), 400 blog = Blog.query.get(id) blog.e_titulo = e_titulo blog.e_cuerpo = e_cuerpo blog.e_fecha = e_fecha if file: blog.e_imagen = filename db.session.commit() return jsonify(blog.serialize()), 201 if request.method == 'DELETE': blog = Blog.query.get(id) if not blog: return jsonify({"msg": "Not Found"}), 404 db.session.delete(blog) db.session.commit() return jsonify({"msg": "Blog was deleted"}), 200