コード例 #1
0
ファイル: views.py プロジェクト: eldie1984/birichini_web
def subir_productos():
    if request.method == 'POST':
        df = pd.DataFrame.from_dict(request.get_array(field_name='file'))
        df.columns = df.iloc[0]
        df = df.drop(0)
        df.set_index('codigo', inplace=True)
        df.to_sql('alimento', if_exists='replace', con=db.engine)
        return redirect(url_for('home.list_alimentos'))

        return jsonify({"result": request.get_array(field_name='file')})
    return '''
コード例 #2
0
ファイル: file.py プロジェクト: houkk/Symptoms
def basisupload():
    if request.method == 'POST':
        try:
            ac = request.get_array(field_name='file')
            result = ac[1:]
            for resu in result:
                res = []
                for re in resu:
                    if type(re) == float:
                        res.append(str(re))
                    else:
                        res.append(re)
                print res
                basis = Basis(
                    basisname=res[0], expertsname=res[1], patientname=res[2],
                    patientgender=res[3], patientage=res[4], clinicdate=res[5],
                    mainsuit=res[6], medicalhistory=res[7], westdiagnosis=res[8],
                    chdiagnosis=res[9], discriminate=res[10], prescription=res[11],
                    editorial=res[12]
                )
                basis.save()

            return jsonify({"result": "success"})
        except:
            return Response('fail')
コード例 #3
0
ファイル: routes.py プロジェクト: ActurialCapital/kashtable
def upload():
    form = UploadForm()
    user_email = str(current_user.email)
    try:
        os.mkdir(os.path.join(current_app.root_path, 'files/raw/' + user_email))
    except OSError:
        pass
    if request.method == 'POST':
        if form.validate_on_submit():
            file = request.get_array(field_name='file')
            df = pd.DataFrame(file)
            path = current_app.root_path
            name = str(form.dt.data)
            
            with pd.ExcelWriter(os.path.join(path, f'files/raw/{user_email}/{name}.xlsx')) as writer:
                df.to_excel(writer)
            
            with open(os.path.join(path, f'files/raw/{user_email}/{name}.txt'), "w") as text_file:
                print(f"Title: {form.title.data}\nBody: {form.body.data}", file=text_file)
            
            flash('File has been uploaded successfuly!', 'success')
            return redirect(url_for('main.home'))
        else:
            flash('OOPS! Something went wrong here! Please try again.', 'danger')
    return render_template('user_upload.html', form=form)
コード例 #4
0
ファイル: excel_read.py プロジェクト: mark-zarandi/BW
def upload_file():
    if request.method == 'POST':
        db.session.query(trans).delete()
        db.session.commit()
        x = request.get_array(field_name='file')
        just_data = []
        iter_x = iter(x)
        y = 0
        for y in range(6):
            next(iter_x)
        for trans_row in iter_x:
            if len(trans_row[3]) == 0 or trans_row[3] == ' ':
                continue
            else:
                just_data.append(trans_row)

        end_sum = 0
        for look in just_data:
            new_trans = trans(look[1],look[2],look[3],look[4],look[5],look[6],look[8],look[9],look[10],look[11],look[12],look[13],look[14],look[15],look[16],look[17])
            db.session.add(new_trans)
            db.session.commit()
            end_sum += float(look[17])


        return jsonify({"result": "success"})

    return '''
コード例 #5
0
ファイル: datasets.py プロジェクト: beia/CitiSIMDocker
def importDataset():
    datasetID = request.form.get("datasetID")
    data = request.get_array(field_name='file')
    data.pop(0)

    if (len(data) > 0):
        delQuery = ("DELETE FROM EnergySensorsData  WHERE SubscriptionID = " +
                    str(datasetID))
        mycursor = mydb.connection.cursor(MySQLdb.cursors.DictCursor)
        mycursor.execute(delQuery)

        query = (
            "INSERT INTO EnergySensorsData (SubscriptionID, SensorID, Value, Timestamp) VALUES "
        )
        for row in data:
            query = query + "(" + str(datasetID) + ","
            query = query + "'" + str(row[2]) + "', "
            query = query + str(row[0]) + ","
            query = query + "'" + str(row[1]) + "') ,"

        query = query[0:-1]
        mycursor.execute(query)
        mydb.connection.commit()

    return redirect("/datasets")
コード例 #6
0
def index():
    session.clear()
    if request.method == 'POST':
        try:
            data = request.get_array(field_name='file')
            smiles, include_property, highest_val, lowest_val = construct_smiles(
                data)
            session['smiles'] = smiles
            session['include_property'] = include_property
            session['prop_name'] = include_property
            session['highest_val'] = highest_val
            session['lowest_val'] = lowest_val

            if include_property:
                unique_compounds = pd.DataFrame(
                    dict((k, [v.get('property', ''), v['label']])
                         for k, v in smiles.items()),
                    index=[include_property, 'label']).T
            else:
                unique_compounds = pd.DataFrame(dict(
                    (k, [v['label']]) for k, v in smiles.items()),
                                                index=['label']).T
            return render_template('index.html',
                                   title='Cheminformatic Analysis',
                                   unique_compounds=unique_compounds.to_html(),
                                   num_compounds=len(unique_compounds),
                                   smiles=smiles,
                                   include_property=include_property)

        except Exception as e:
            return render_template('index.html',
                                   title='Cheminformatic Analysis',
                                   errors=["Please input a valid file format"])

    return render_template('index.html', title='Cheminformatic Analysis')
コード例 #7
0
 def on_model_change(self, form, model, is_created=False):
     file = request.get_array(field_name='doc')
     df = pd.DataFrame(file)
     # convert first row to column header
     df = df.rename(columns=df.iloc[0]).drop(df.index[0])
     df = df.apply(pd.to_numeric, errors='ignore')
     # load to db
     model.doc = json.loads(df.to_json(orient='records', date_format='iso'))
コード例 #8
0
ファイル: main.py プロジェクト: sandeepbhaisora/mail-python
def upload():
    if request.method == 'POST':
        data = request.get_array(field_name='file')
        for user in data[1:]:
            email = user[0]
            password = user[1]
            success = mail.copy_mail(email, password=password)
        return jsonify({"success": success})
コード例 #9
0
def handle_answers():
    # check if the post request has the file part
    if 'file' not in request.files:
        flash(u'ОШИБКА: нет файла')
        return redirect(url_for('serve_answers'))

    file = request.files['file']
    filename = file.filename
    # if user does not select file, browser also
    # submit an empty part without filename
    if filename == '':
        flash(u'ОШИБКА: нет файла')
        return redirect(url_for('serve_answers'))

    allowed_extensions = ['xls', 'xlsx', 'xlsm']
    normal_file = '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions
    if not file or not normal_file:
        flash(u'ОШИБКА: неверное расширение у файла или название')
        return redirect(url_for('serve_answers'))

    try:
        real_variant = request.form['real_variant']
        type_ = request.form['type']
    except:
        flash(u'ОШИБКА: не выбран вариант')
        return redirect(url_for('serve_answers'))

    data = request.get_array(field_name='file')
    cur_num_quests = NUM_QUESTS[type_]
    answers = [x[0].upper() for x in data[:cur_num_quests]]
    if len(answers) != cur_num_quests:
        flash(u'ОШИБКА: некорректные значения ответов')
        return redirect(url_for('serve_answers'))
    for ans in answers:
        if ans not in LABELS:
            flash(u'ОШИБКА: некорректные значения ответов')
            return redirect(url_for('serve_answers'))

    filename = secure_filename(filename)
    flash(u'Filename=%s' % filename)
    flash(u'type=%s' % type_)
    flash(u'real_variant=%s' % real_variant)
    flash(u'Загрузка файла успешно осуществлена!')
    flash(u'------------------------------------')

    updated_right_answers_id = test_answers.update_one(
        {
            'type': type_,
            'real_variant': real_variant
        }, {'$set': {str(i + 1): answers[i]
                     for i in range(cur_num_quests)}})

    flash(u'Ответы на вариант {}_{} были добавлены.'.format(
        type_, real_variant))
    flash(u'------------------------------------')

    return redirect(url_for('serve_answers'))
コード例 #10
0
def upload_gates_excel():
    gates_list = request.get_array(field_name="excel_file")
    return_list = []
    failed_list = []
    for index, gate in enumerate(gates_list):
        if index == 0:
            continue
        g1 = Gate(
            name=gate[0],
            number=str(gate[1]),
            category=gate[2],
            mc_id=str(gate[3]),
            hand_max=gate[4],
            hand_min=gate[5],
            foot_max=gate[6],
            foot_min=gate[7],
            hand_near_max=gate[8],
            hand_near_min=gate[9],
            foot_near_max=gate[10],
            foot_near_min=gate[11],
        )
        if not g1.hand_max:
            g1.hand_max = 35000
        if not g1.hand_min:
            g1.hand_min = 750
        if not g1.foot_max:
            g1.foot_max = 200000
        if not g1.foot_min:
            g1.foot_min = 200

        if not g1.hand_near_max:
            g1.hand_near_max = 35000
        if not g1.hand_near_min:
            g1.hand_near_min = 750
        if not g1.foot_near_max:
            g1.foot_near_max = 200000
        if not g1.foot_near_min:
            g1.foot_near_min = 200

        try:
            g1.save()
        except Exception as e:
            failed_list.append((g1.to_json(), str(e)))
        else:
            return_list.append(g1.to_json())

    return (
        jsonify({
            "result": len(return_list),
            "failed": failed_list,
            "failed_numbers": len(failed_list),
        }),
        {
            "Content-Type": "application/json"
        },
    )
コード例 #11
0
ファイル: weights.py プロジェクト: ceciliacase/weight-tracker
def upload_file():
  if request.method == 'POST':
    todaysDate = time.strftime("%Y-%m-%d")
    loadedData = request.get_array(field_name='file')
    # Test for header row
    # TODO: test this code, make sure it works
    if loadedData[0][0].isdigit():
      print "no header to delete"
    else:
      print "deleted a header row"
      del loadedData[0]

    for row in loadedData:
      # TODO: Add an error check for the parsed date
      row[0] = parser.parse(row[0]).date()
      if row[1]:
        c.execute('''UPDATE OR IGNORE weights SET date=?, dateSubmitted=?, weight=? WHERE date=?''',(row[0], todaysDate, row[1], row[0]))
        c.execute('''INSERT OR IGNORE INTO weights (date,dateSubmitted,weight) VALUES (?, ?, ?)''',(row[0], todaysDate, row[1]))
    db.commit()
    print 'excel file data loaded'
    # TODO: Figure out how to pass the updated table back to automatically refresh?
    return jsonify({"result": request.get_array(field_name='file')})
  return '''
コード例 #12
0
def get_result():
    """
    Function to be run at each API call
    """

    # This is how you jsonify a list
    # request_file = jsonify({"result": request.get_array(field_name='data_file')})

    if not request:
        return "No file"

    # This line creates a dataframe from a list of lists
    df = pd.DataFrame(request.get_array(field_name='data_file'))

    # The first row is the list of column names so set the column names to the first row
    df.columns = df.iloc[0, :]

    # Now remove the first row
    df = df[1:]

    # Print the dataframe to the console
    print(df)

    # These are the values given for the fields
    input_list = list(request.form.values())

    # These are the names of the fields, i.e. LotFrontage, LotArea etc...
    input_names = list(request.form)
    '''
    # This code section creates a dictionary where each key is a list of observations
    res = dict()
    i = 0
    for j in df.columns:
        res[i] = list(df[j])
        i += 1
    '''

    result = get_prediction(df, input_list)

    # This code section creates a dictionary where each key is a row in the dataframe
    res = dict()
    for i in range(len(df)):
        res[i] = list(df.iloc[i, :])

    # Return the result

    # return jsonify(res)
    return 'The predicted Sale Price of this house is: ' + str(round(
        result, 2))
コード例 #13
0
def respond_array(struct_type):
    if struct_type == "array":
        array = request.get_array(field_name='file')
        return jsonify({"result": array})
    elif struct_type == "dict":
        adict = request.get_dict(field_name='file')
        return jsonify({"result": adict})
    elif struct_type == "records":
        records = request.get_records(field_name='file')
        return jsonify({"result": records})
    elif struct_type == "book":
        book = request.get_book(field_name='file')
        return jsonify({"result": book.to_dict()})
    elif struct_type == "book_dict":
        book_dict = request.get_book_dict(field_name='file')
        return jsonify({"result": book_dict})
コード例 #14
0
def upload_array(struct_type):
    if struct_type == "array":
        array = request.get_array(field_name='file')
        return excel.make_response_from_array(array, 'xls')
    elif struct_type == "dict":
        adict = request.get_dict(field_name='file')
        return excel.make_response_from_dict(adict, 'xls')
    elif struct_type == "records":
        records = request.get_records(field_name='file')
        return excel.make_response_from_records(records, 'xls')
    elif struct_type == "book":
        book = request.get_book(field_name='file')
        return excel.make_response(book, 'xls')
    elif struct_type == "book_dict":
        book_dict = request.get_book_dict(field_name='file')
        return excel.make_response_from_book_dict(book_dict, 'xls')
コード例 #15
0
def export_records():
    print("inside export")
    array = request.get_array(field_name='file')
    aspects = []

    directory = os.fsencode('Files/')
    filename = os.fsdecode(os.listdir(directory)[0])

    with open(os.path.join(directory, os.listdir(directory)[0])) as fp:
        line = fp.readline()
        while line:
            aspects.append(line.strip())
            line = fp.readline()

    columns = ["Sentences"] + aspects
    return render_template("annotate.html", content=columns, file=array)
コード例 #16
0
def update_manulVsim():
    """

    :return:
    """
    if request.method == 'POST':
        arrayData = request.get_array(field_name='file')

        return updateManuleVsimSrc(array_data=arrayData)

    else:
        returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []}

        return json.dumps(returnJsonData,
                          sort_keys=True,
                          indent=4,
                          default=json_util.default)
コード例 #17
0
def delet_newvsimtest_info_table():
    """

    :return:
    """
    if request.method == 'POST':
        arrayData = request.get_array(field_name='file')

        return deleteNewVsimTestInfo(array_data=arrayData)

    else:
        returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []}

        return json.dumps(returnJsonData,
                          sort_keys=True,
                          indent=4,
                          default=json_util.default)
コード例 #18
0
ファイル: app.py プロジェクト: keerthanavarma/task
def doimport():
    if request.method == 'POST':
        with open('datares.json', 'w') as f:
            json.dump({"result": request.get_array(field_name='file')}, f)

        with open('datares.json') as f:
            data = json.load(f)

        def check(email):
            if (re.search(regex, email)):
                email = email
            else:
                email = 'NULL'
            return email

        for i in range(1, len(data['result'])):
            data['result'][i][5] = check(data['result'][i][5])
            if len(str(
                    data['result'][i][6])) < 10 or data['result'][i][6] == '':
                data['result'][i][6] = 'Null'
            data['result'][i][3].islower()
            if not (data['result'][i][3] == "f" or data['result'][i][3]
                    == "female" or data['result'][i][3] == "male"
                    or data['result'][i][3] == "m"
                    or data['result'][i][3] == "other"):
                data['result'][i][3] = 'Null'

        for i in range(1, len(data['result'])):
            details = Orders(email=data['result'][i][5],
                             gender=data['result'][i][3],
                             rollname=data['result'][i][4],
                             sno=data['result'][i][0],
                             firstname=data['result'][i][1],
                             lastname=data['result'][i][2],
                             phone=data['result'][i][6],
                             address=data['result'][i][7],
                             city=data['result'][i][8],
                             state=data['result'][i][9],
                             country=data['result'][i][10],
                             branch=data['result'][i][11],
                             section=data['result'][i][12])
            db.session.add(details)
        db.session.commit()
        flash('saved successfully')
        return redirect('/import')
    return render_template('index.html')
コード例 #19
0
ファイル: file.py プロジェクト: houkk/Symptoms
def uplaod_file():
    if request.method == 'POST':
        try:
            ac = request.get_array(field_name='file')
            result = ac[1:]
            for res in result:
                liter = []
                for re in res:
                    if type(re) == float:
                        liter.append(str(re))
                    else:
                        liter.append(re)
                print liter
                literature = Literature(literaturename=liter[0], authorname=liter[1], interlink=liter[2])
                literature.save()
            return jsonify({"result": "success"})
        except:
            return Response('fail')
コード例 #20
0
ファイル: views.py プロジェクト: mtanderson17/selfKnowledge
def upload_data():
    if request.method == 'POST':
        try:
            json_data = {"result": request.get_array(field_name='file')}
            flash("File uploaded successfully", 'SUCCESS')
        except:
            flash(
                'File Upload Error! - ensure extension is .xlsx, .xls, .xlsx, .csv - ensure first column is valid date - ensure column names align to habits',
                'ERROR')

        messages = process_file_upload(json_data)

        if len(messages) > 0:
            for message in messages:
                flash(message, 'ERROR')

        return redirect(url_for('user_app.manage_account'))
    return redirect(url_for("user_app.manage_account"))
コード例 #21
0
def home():
    """Home."""
    file_input_form = FileForm()
    if file_input_form.validate_on_submit():
        if RECORDS:
            RECORDS.clear()

        try:
            json_str = request.files["file"].read()
            RECORDS.update(json.loads(json_str))

        except json.decoder.JSONDecodeError:

            try:
                table_data = request.get_array(field_name="file")

                if len(
                        table_data[0]
                ) == 1 and table_data[0][0].lower() != "base identifier":
                    table_header = ["Base Identifier"]
                else:
                    table_header = table_data.pop(0)

                for table_row in table_data:
                    record = create_initial_record(header=table_header,
                                                   row=table_row)
                    RECORDS[record["record_id"]] = record

                for i in generate_table(records=RECORDS):
                    progress_percentage = "{0:.0%}".format(i / len(RECORDS))

            except FileTypeNotSupported:
                flash("Invalid file", "danger")
                return render_template("home.html",
                                       file_input_form=file_input_form)

        except Exception:
            flash("Invalid file", "danger")
            return render_template("home.html",
                                   file_input_form=file_input_form)

        return redirect(url_for("table"))
    return render_template("home.html", file_input_form=file_input_form)
コード例 #22
0
def store_excel_data():
    total_crimes = []
    if request.method == 'POST':
        files = request.get_array(field_name="crimes_excel")

        for file in files:
            crimes = {}
            crimes['reference_number'] = file[0]
            crimes['longitude'] = file[1]
            crimes['latitude'] = file[2]
            crimes['location_description'] = file[3]
            crimes['image_file'] = file[4]
            crimes['date_posted'] = file[5]
            crimes['user_id'] = file[6]
            crimes['police_id'] = file[7]
            crimes['category'] = file[8]
            crimes['location'] = file[9]
            crimes['Arrest'] = file[10]
            crimes['Domestic'] = file[11]
            total_crimes.append(crimes)
            # print(total_crimes)

        for crime in total_crimes:
            crime_scene = CrimeScene(
                longitude=crime["longitude"],
                latitude=crime["latitude"],
                description=crime["location_description"],
                date_posted=crime["date_posted"],
                location=crime["location"],
                category_id=crime["category"],
                user_id=crime["user_id"],
                police_id=crime["police_id"],
                arrest=crime['Arrest'],
                domestic=crime['Domestic']
            )
            db.session.add(crime_scene)
            db.session.commit()

        print()
        return jsonify({"result": total_crimes})
    # return render_template('crimes/add_crime_excel.html',
    #                         title="Add Excel Data")
    pass
コード例 #23
0
ファイル: __init__.py プロジェクト: TanselArif-21/MLApp
def dosomething2():
    # If the request is a post request
    if request.method == 'POST':
        # This line creates a dataframe from a list of lists
        df = pd.DataFrame(request.get_array(field_name='file'))

        # The first row is the list of column names so set the column names to the first row
        df.columns = df.iloc[0, :]

        # Now remove the first row
        df = df[1:]

        # Print the dataframe to the console
        print(df)

        # Print the column names to the console
        print(df.columns)

        # These are the values given for the fields
        input_list = list(request.form.values())

        filename = ''
        for i in range(4):
            filename = filename + random.choice(string.ascii_letters)

        # These are the names of the fields, i.e. LotFrontage, LotArea etc...
        input_names = list(request.form)

        result = get_prediction_lr(df, input_list, filename)

        # This code section creates a dictionary where each key is a row in the dataframe
        res = dict()
        for i in range(len(df)):
            res[i] = list(df.iloc[i, :])

        # Return the result
        return 'The predicted Sale Price of this house is: ' + str(
            round(result, 2)
        ) + '. <p></p> <img src="static/' + filename + '.png"><p></p>'
    else:
        # Show the form page
        return render_template('dosomethingform.html')
コード例 #24
0
ファイル: views.py プロジェクト: jack-ling/ukl-gsvc-web
def export_excel():
    if request.method == 'POST':
        arrayData = request.get_array(field_name='file')
        DicData = exportExcelFunc.getDictExcelData(array_data=arrayData)
        print(DicData['data'][0])
        if DicData['err']:
            returnJsonData = {
                'err': True,
                'errinfo': DicData['errinfo'],
                'data': []
            }
        else:
            returnJsonData = {
                'err': False,
                'errinfo': DicData['errinfo'],
                'data': DicData['data']
            }
            return jsonify({"data": returnJsonData})

    return render_template('/test_jquery/test_uploadfiles.html')
コード例 #25
0
def create_invoice():
    form = CreateLineInvoice(request.form)
    if form.validate_on_submit():
        invoiceAmt = str(
            float(form.data['unitCount']) * float(form.data['unitPrice']))
        line = [
            form.data['invoiceNumber'], form.data['clientName'],
            form.data['clientEmail'], form.data['clientPhone'],
            form.data['itemSummary'], form.data['description'],
            form.data['invoiceDueDate'], form.data['unitCount'],
            form.data['unitPrice'], invoiceAmt
        ]
        print line
        invoice = createLineInvoice(line, current_user)
        db.session.add(invoice)
        db.session.commit()
        invoiceDict = {}
        invoiceDict['invoice' + str(invoice.id) + '.pdf'] = invoice
        returnedInvoiceDict = sendMail(invoiceDict, False)
        return redirect(
            url_for('display_result', result=json.dumps(returnedInvoiceDict)))
    if request.method == 'POST':
        excelContent = request.get_array(field_name='file')
        header = [str(x) for x in excelContent[0]]
        line = [
            "Invoice Number", "Client Name", "Client Email", "Client Phone",
            "Item Summary", "Item Description", "Invoice Due Date",
            "Unit Count", "Unit Price"
        ]
        if (header == line):
            invoiceDict = createInvoice(excelContent, current_user)
            returnedInvoiceDict = sendMail(invoiceDict, False)
            return redirect(
                url_for('display_result',
                        result=json.dumps(returnedInvoiceDict)))
        else:
            print header
            flash(
                "Correct your column order to the following - 'Invoice Number','Client Name','Client Email','Client Phone','Item Summary','Item Description','Invoice Due Date','Unit Count','Unit Price'"
            )
    return render_template('forms/createInvoice.html', form=form)
コード例 #26
0
def export_records():
    print("inside export")
    try:
        array = request.get_array(field_name='file')
    except:
        print("An exception occurred")
        return redirect(url_for("error"))

    aspects = []

    directory = os.fsencode('Files/')

    with open(os.path.join(directory, os.listdir(directory)[0])) as fp:
        line = fp.readline()
        while line:
            aspects.append(line.strip())
            line = fp.readline()

    columns = ["Sentences"] + aspects
    session["transcript"] = array
    session["columns"] = columns
    return render_template("annotate.html", content=columns, file=array)
コード例 #27
0
def upload_array(struct_type):
    if struct_type == "array":
        array = request.get_array(field_name="file")
        return excel.make_response_from_array(array,
                                              "xls",
                                              sheet_name="test_array")
    elif struct_type == "dict":
        adict = request.get_dict(field_name="file")
        return excel.make_response_from_dict(adict,
                                             "xls",
                                             sheet_name="test_array")
    elif struct_type == "records":
        records = request.get_records(field_name="file")
        return excel.make_response_from_records(records,
                                                "xls",
                                                sheet_name="test_array")
    elif struct_type == "book":
        book = request.get_book(field_name="file")
        return excel.make_response(book, "xls")
    elif struct_type == "book_dict":
        book_dict = request.get_book_dict(field_name="file")
        return excel.make_response_from_book_dict(book_dict, "xls")
コード例 #28
0
def upload_file():
    if request.method == 'POST':
        whole_file = request.get_array(field_name='file')
        df = format_file()
        columns = df.columns
        year_data = read_year_data()
        month_data = read_month_data()
        merged_frame = merged_df(df, year_data, month_data)
        merged_frame = drop_cols(merged_frame)

        try:
            open('output.xlsx', 'w')
            merged_frame = merged_frame.to_excel("output.xlsx",
                                                 sheet_name='Sheet_name_1')
            send_file('output.xlsx', attachment_filename='output.xlsx')
            import os
            os.remove('output.xlsx')
            return render_template("index.html")
        except Exception as e:
            return str(e)

    return render_template("index.html")
コード例 #29
0
def updatedb():
    if request.method == 'POST':
        bill = request.get_array(field_name='file')
        cur = db.connection.cursor()
        for b in bill:
            total_bill = cal_bill(int(b[3]))
            date = str(b[2]).split(" ")
            cur.execute(
                "INSERT INTO `bill`(`meter_id`,`total_bill`,`maintenance_cost`,`due_date`,`meter_unit`,`month`,`year`,`status`) \
            VALUES('{}','{}','{}','{}','{}','{}','{}','{}')".format(
                    b[0], total_bill, b[1], date[0], b[3], b[4], b[5], b[6]))
        db.connection.commit()
        cur.execute("SELECT * FROM `meter`")
        meter = cur.fetchall()
        for m in meter:
            meter_id = m[0]
            meter_total_unit = int(m[1])
            meter_total_unit_cur_month = int(m[2])
            current_month = datetime.now().strftime("%b")
            cur.execute(
                "SELECT `meter_unit` FROM `bill` WHERE `meter_id`='{}' AND `month`='{}'"
                .format(meter_id, current_month.upper()))
            m_unit = cur.fetchone()
            print(m_unit)
            meter_total_unit = meter_total_unit_cur_month
            print(meter_total_unit)

            meter_total_unit_cur_month += m_unit[0]
            cur.execute(
                "UPDATE `meter` SET `meter_total_unit`='{}',`meter_total_unit_cur_month`='{}' WHERE `meter_id`='{}'"
                .format(meter_total_unit, meter_total_unit_cur_month,
                        meter_id))
            db.connection.commit()
        return '''
        <!doctype html>
        <h1>Success</h1>
        '''
    return render_template("updatedb.html")
コード例 #30
0
ファイル: app.py プロジェクト: Apex1000/content-management
def upload():
    dd = []
    form = Uploaddata()
    if request.method == 'POST':
        result = request.get_array(field_name='file')
        for i in result:
            data = {
                'category' : i[0],
                'name' : i[1],
                'dob' : str(i[3]),
                'membership_number' : i[2],
                'designation' : i[4],
                'company_name' : i[5],
                'address':[{
                    'add1' : i[6],
                    'add2' : i[7],
                    'add3' : i[8],
                    'add4' : i[9],
                    'city' : i[10],
                    'state' : i[11],
                    'region' : i[20],
                    'pin_code' : str(i[12])
                }],
                'email' : [{'email' : i[13]},{'email' : i[14]}],
                'phone_number' : [{
                    'number' : str(i[15])
                    }],
                'landline_number' : i[16],
                'source_of_data' : str(i[17]),
                'date_of_creation' : str(i[18]),
                'file_name' : i[19]
            }

            db.datas.insert_one(data)
        flash('New File Uploaded.', 'success')
        return redirect(url_for('index'))
    return render_template('./upload.html', form=form)
コード例 #31
0
ファイル: __init__.py プロジェクト: TanselArif-21/MLApp
def getwordcloud():
    # If the request is a post request
    if request.method == 'POST':
        # This line creates a dataframe from a list of lists
        df = pd.DataFrame(request.get_array(field_name='file'))

        # The first row is the list of column names so set the column names to the first row
        df.columns = df.iloc[0, :]

        # Now remove the first row
        df = df[1:]

        # Print the dataframe to the console
        print(df)

        # Print the column names to the console
        print(df.columns)

        # These are the values given for the fields
        input_list = list(request.form.values())

        filename = ''
        for i in range(4):
            filename = filename + random.choice(string.ascii_letters)

        get_word_cloud(df, filename + '.png')

        # This code section creates a dictionary where each key is a row in the dataframe
        res = dict()
        for i in range(len(df)):
            res[i] = list(df.iloc[i, :])

        # Return the result
        return '. <p></p> <img src="static/' + filename + '.png"><p></p><p></p> <img src="static/wc' + filename + '.png"><p></p>'
    else:
        # Show the form page
        return render_template('getwordcloud.html')
コード例 #32
0
def upload_file():
    if g.user:
        if request.method == 'POST':
            array = request.get_array(field_name='file')
            print(array[0])
            print('hey bro')
            for i in array[0]:
                print(i)

            #fil = request.files('file')
            #book = xlrd.open_workbook(fil)
            #sheet = book.sheet_by_name("Sheet1")
            #print (book)
            return jsonify({"result": array})

        return '''
        <!doctype html>
        <title>Upload an excel file</title>
        <h1>Excel file upload (csv, tsv, csvz, tsvz only)</h1>
        <form action="" method=post enctype=multipart/form-data>
        <p><input type=file name=file><input type=submit value=Upload>
    </form>
        '''
    return '''<h2>Unauthorised Access Visit <a href ='/login'>login<a></h2>'''
コード例 #33
0
def upload_file():
    if request.method == 'POST':
        return jsonify({"result": request.get_array(field_name='file')})
    return '''
コード例 #34
0
ファイル: views.py プロジェクト: ZimmerHao/raptor
 def post(self):
     return jsonify({"result": request.get_array(field_name='file')})
コード例 #35
0
ファイル: main.py プロジェクト: steventhan/my-hng
def client_list():
    page = 'Client List'
    if request.method == "POST":
        try:
            excel_file = request.get_array(field_name='client_list_file')
            # Check for valid SF client list excel file
            # NOTE: This feature is dependent on Service Fusion customer report
            # If they change their excel format, the source code has to be
            # modified to accomodate.
            if (excel_file[5][5] == 'Primary Contact First Name' and
                excel_file[5][6] == 'Primary Contact Last Name' and
                excel_file[5][7] == 'Primary Contact Phone 1' and
                excel_file[5][14] == 'Primary Service Location Address 1' and
                excel_file[5][15] == 'Primary Service Location Address 2' and
                excel_file[5][16] == 'Primary Service Location City' and
                    excel_file[5][27] == 'Date Created'):
                for each_line in excel_file[6:]:
                    email = str(each_line[8]).strip()
                    first_name = str(each_line[5]).strip()
                    last_name = str(each_line[6]).strip()
                    phone = filter(str.isdigit, str(each_line[7]).strip())
                    address1 = str(each_line[15]).strip()
                    address2 = str(each_line[14]).strip()
                    city = str(each_line[16]).strip()
                    state = str(each_line[17]).strip()
                    zip_code = str(each_line[18]).strip()
                    added_date = str(each_line[27]).strip()
                    is_subscribed = "T"
                    client_id = (first_name + last_name + zip_code).lower()

                    if Client.query.filter(
                        Client.first_name == first_name,
                        Client.last_name == last_name
                    ).count() == 1:
                        client = Client.query.filter_by(id=client_id).first()
                        client.email = email
                        client.first_name = first_name
                        client.last_name = last_name
                        client.added_date = added_date
                        client.phone = phone
                        client.address1 = address1
                        client.address2 = address2
                        client.city = city
                        client.state = state
                        client.zip_code = zip_code

                    elif Client.query.filter_by(id=client_id).count() == 0:
                        client = Client(
                            id=client_id,
                            email=email,
                            first_name=first_name,
                            last_name=last_name,
                            added_date=added_date,
                            phone=phone,
                            address1=address1,
                            address2=address2,
                            city=city,
                            state=state,
                            zip_code=zip_code,
                            is_subscribed=is_subscribed
                        )
                        db.session.add(client)
                    db.session.commit()
                flash("Synced successfully", "alert-success")
            else:
                flash("Invalid file, try again", 'alert-danger')
            return render_template(
                'employee_site/client/client_list.html',
                page=page
            )
        except Exception as e:
            flash(e, 'alert-danger')
            return render_template(
                'employee_site/client/client_list.html',
                page=page
            )
    else:
        return render_template(
            'employee_site/client/client_list.html',
            page=page
        )
コード例 #36
0
ファイル: app.py プロジェクト: Gcav66/aWhere-App
def upload_file():
    template = 'upload.html'
    if request.method == 'POST':
	    return jsonify({"result": request.get_array(field_name='file')})
    return render_template(template)