2016-03-22 2 views
-1

(начинающий Python вопроса)применять питон скрипт колбу

Я построил Csv анализатор, который я хотел создать простой сайт, чтобы пользователи могли загрузить файл CSV и вернуть разобранную CSV.

У меня возникли проблемы с пониманием того, как интегрировать сценарий синтаксического анализатора в простой созданный фляж. Я смог получить модуль загрузки, который будет использовать csv.

флягу вид выглядит следующим образом:

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) 

Мой парсер скрипт:

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, 

Поскольку мой парсер сценарий уже написан, чтобы принять формат файла, я думал о добавлении «разобрать ", который выполнит этот скрипт в загружаемом файле и просто распечатает результаты на той же странице. Как вы собираетесь применять мои скрипты python в флеш-фреймворке?

+1

Вместо того, чтобы печатать анализируемый текст, вам необходимо объединить его в строку, которую вы затем вернетесь из 'parse'. После этого вы можете использовать функцию в своем флеш-приложении и визуализировать анализируемый текст в браузере или все, что вы хотите с ним делать. – Sevanteri

+0

импортируйте свой сценарий «синтаксического анализа» и предоставите rest uri для выполнения действия. – LittleQ

ответ

0

После того, как вы загрузили свой файл, вы можете позвонить по этому URL-адресу и получить свой результат.

Вы можете использовать эту функцию (это пример, который можно изменить в соответствии с вашими целями):

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()) 

Я также изменил свою 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 

что я сделал с вашей функцией, это установить значение результата для вещей, которые вы печатаете на консоли, а затем вернуть значение результата.

+0

Большое спасибо за ваше объяснение. Это имеет большой смысл. Я не знал, что мой синтаксический анализатор распечатает результаты, чтобы строка была такой простой. Я попробую это и дам вам знать, если это сработает – Paul