简体   繁体   English

将 python 脚本应用到烧瓶

[英]apply python script to flask

(Python beginner question) (Python初学者问题)

I've built a csv parser that I wanted to build a simple site to allow users to upload a csv and it return the parsed csv.我已经构建了一个 csv 解析器,我想构建一个简单的站点以允许用户上传 csv 并返回解析后的 csv。

I'm having trouble understanding how to integrate my parser script into a simple Flask site that generated.我无法理解如何将我的解析器脚本集成到生成的简单 Flask 站点中。 I was able to get an upload module working that will consume the csv.我能够让一个上传模块工作,它将消耗 csv。

My Flask view looks like this:我的 Flask 视图如下所示:

import os
from app import app
from flask import render_template, flash, redirect, session, url_for, request, g, send_from_directory
from werkzeug import secure_filename

UPLOAD_FOLDER = '/csv_upload_directory'
ALLOWED_EXTENSION = set(['csv', 'txt'])

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSION

@app.route('/', methods=['GET'])
@app.route('/index', methods=['GET'] )
def index():
    return render_template('index.html')


@app.route('/upload', methods=['GET','POST'])
def upload():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        getfile = file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('index'))

@app.route('/uploads/<filename>', methods=['GET','POST'])
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

My parser script:我的解析器脚本:

def parse(text):
    #states
    is_token = False
    previous_character_is_escape = False
    no_quote_value = True
    quote_value = False

    row_counter = 1

    print "This is row %i" % (row_counter)
    row_counter += 1
    with io.open(text,'rb',newline=None) as f:
        while True:
            byte = f.read(1)
            for i in byte:
                #print "%s,%s" % (no_quote_value,previous_character_is_escape)
                if is_token == False:
                    if i == '"':
                        print '\b' + i,
                        is_token = True
                        no_quote_value = False
                        quote_value = True
                    elif i == '\n':
                        print '\n'
                        print "This is row %i" % (row_counter)
                        row_counter += 1
                    elif i == ',':
                        print '\n' + '\b',
                    elif no_quote_value == True:
                        print '\b' + i,
                        is_token = True
                        quote_value = False
                    else:
                        print '\b' + i,


                elif is_token == True:
                    # start of an escape sequence
                    if i == '\\':
                        print '\b' + i,
                        previous_character_is_escape = True
                    # for line delimiter, the quoted values are being processed outside token
                    elif no_quote_value == True and i == '\n':
                        print '\n'
                        print "This is row %i" % (row_counter)
                        row_counter += 1
                        is_token = False
                    # if token is not a quoted value but ends with quotes, and there is no escape character
                    elif no_quote_value == True and previous_character_is_escape == False and i == '"':
                        print '\b' + i,
                        print "(This is a not a valid token, this is not a quoted value but there is an ending quote)"
                        return False
                    # builds off previous_character_is_escape and captures any escape sequence
                    elif previous_character_is_escape == True:
                        print '\b' + i,
                        previous_character_is_escape = False
                    # this type of quote is the end of token, returns back to other if statement
                    elif previous_character_is_escape == False and i == '"':
                        print '\b' + i,
                        no_quote_value = True
                        quote_value = False
                        is_token = False
                    # if token starts as a quote but ends without quotes
                    elif quote_value == True and previous_character_is_escape == False and i == ',':
                        print '\b' + i,
                        print "(This is not a valid token, there should be a quote at the end of this token)"
                        return False
                    # this comma marks the end of a non quoted token, this invokes a newline
                    elif no_quote_value == True and previous_character_is_escape == False and i == ',':
                        print '\n' + '\b',
                        is_token = False
                    elif no_quote_value == False and i == ',':
                        print '\b' + i,
                    else:
                        print '\b' + i,

Since my parser script is already written to accept a file format, I was thinking of adding a "parse" button that will execute this script on the file that is uploaded and simply print the results on the same page.由于我的解析器脚本已经编写为接受文件格式,因此我正在考虑添加一个“解析”按钮,该按钮将在上传的文件上执行此脚本,并在同一页面上简单地打印结果。 How do you go about applying my python scripts into the Flask framework?你如何将我的 python 脚本应用到 Flask 框架中?

Once you uploaded your file you can call this URL and get your result.上传文件后,您可以调用此 URL 并获得结果。

You can use this function (this is an example which you can change to suit your purpose):您可以使用此功能(这是一个示例,您可以根据自己的目的进行更改):

from from_parse_function_file import parse

@app.route('/get_parsed/<filename>')
def get_parsed(filename):
    try:
        file = open(os.path.join(current_app.config.get('UPLOAD_FOLDER'),
                    filename))
    except:
        return abort(404)
    return parse(file.read())

I also changed your parse() function to return a string:我还更改了您的parse()函数以返回一个字符串:

def parse(text):
    #states
    is_token = False
    previous_character_is_escape = False
    no_quote_value = True
    quote_value = False

    row_counter = 1

    result = "This is row %i" % (row_counter)
    row_counter += 1
    with io.open(text,'rb',newline=None) as f:
        while True:
            byte = f.read(1)
            for i in byte:
                #print "%s,%s" % (no_quote_value,previous_character_is_escape)
                if is_token == False:
                    if i == '"':
                        result += '\b' + i,
                        is_token = True
                        no_quote_value = False
                        quote_value = True
                    elif i == '\n':
                        result += '\n'
                        result += "This is row %i" % (row_counter)
                        row_counter += 1
                    elif i == ',':
                        result += '\n' + '\b',
                    elif no_quote_value == True:
                        result += '\b' + i,
                        is_token = True
                        quote_value = False
                    else:
                        result += '\b' + i,


                elif is_token == True:
                    # start of an escape sequence
                    if i == '\\':
                        result += '\b' + i,
                        previous_character_is_escape = True
                    # for line delimiter, the quoted values are being processed outside token
                    elif no_quote_value == True and i == '\n':
                        result += '\n'
                        result += "This is row %i" % (row_counter)
                        row_counter += 1
                        is_token = False
                    # if token is not a quoted value but ends with quotes, and there is no escape character
                    elif no_quote_value == True and previous_character_is_escape == False and i == '"':
                        result += '\b' + i,
                        result += "(This is a not a valid token, this is not a quoted value but there is an ending quote)"
                        return False
                    # builds off previous_character_is_escape and captures any escape sequence
                    elif previous_character_is_escape == True:
                        result += '\b' + i,
                        previous_character_is_escape = False
                    # this type of quote is the end of token, returns back to other if statement
                    elif previous_character_is_escape == False and i == '"':
                        result += '\b' + i,
                        no_quote_value = True
                        quote_value = False
                        is_token = False
                    # if token starts as a quote but ends without quotes
                    elif quote_value == True and previous_character_is_escape == False and i == ',':
                        result += '\b' + i,
                        result += "(This is not a valid token, there should be a quote at the end of this token)"
                        return False
                    # this comma marks the end of a non quoted token, this invokes a newline
                    elif no_quote_value == True and previous_character_is_escape == False and i == ',':
                        result += '\n' + '\b',
                        is_token = False
                    elif no_quote_value == False and i == ',':
                        result += '\b' + i,
                    else:
                        result += '\b' + i,
    return result

The thing I did to your function is to set a result value to things you print in console and then return the result value.我对你的函数所做的事情是为你在控制台中打印的东西设置一个结果值,然后返回结果值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM