web_app.py 2.18 KB
Newer Older
carignani's avatar
carignani committed
#!/bin/bash

import os

from flask import Flask, flash, request, redirect, url_for, send_file, render_template
carignani's avatar
carignani committed
from werkzeug.utils import secure_filename
import docx

import tosca2doc

app = Flask(__name__)

UPLOAD_FOLDER = '/tmp/upload'

ALLOWED_EXTENSIONS = set(['txt', 'yaml', 'docx'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'super secret key'
app.config['SESSION_TYPE'] = 'filesystem'

TOSCA_DEFS=['VNFD', 'NSD', 'PNFD']

def allowed_file(filename):
    '''
    Check filename is in the list of allowed extensions
    '''
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route("/")
def hello():
    return render_template("./home.html") 
carignani's avatar
carignani committed

@app.route("/tosca2doc", methods=['POST'])
def mk_tosca2doc():

    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)

    ufiles=request.files.getlist("file")

    for tosca_def in TOSCA_DEFS:
        found=False
        for uploaded_file in ufiles:
            if tosca_def in uploaded_file.filename or \
                tosca_def.lower() in uploaded_file.filename:
                found=True
                #if uploaded_file:
                #    print "-------------------"
                #    print uploaded_file.read()
                #    print "-------------------"
        if not found:
            flash('No file part')
            print('No file part')
            return redirect("/")

    for file in ufiles:
        if file.filename == '':
            print('No selected file')
            flash('No selected file')
            return redirect("/")

    doc = docx.Document()    

    for tosca_def in TOSCA_DEFS:
        for file in ufiles:
            if tosca_def in uploaded_file.filename or \
                tosca_def.lower() in uploaded_file.filename:
                filename = secure_filename(file.filename)
                filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                file.save(filepath)
                file.close()

                tosca2doc.generate_from_file(tosca_def, doc, filepath)

    doc.save('/tmp/myfile.docx')
    return send_file('/tmp/myfile.docx')

    return ("No content found")