如何从python中的html获取下拉输入的值?

时间:2019-10-19 04:23:48

标签: python html flask werkzeug

我正在创建一个应用程序,该应用程序将图像中的文本转换为用户从下拉菜单中选择的语言。此下拉菜单基于一个词典,该词典具有所有google翻译支持的语言及其相应的代码。但是,我在从此下拉菜单中获取输入并将其放回python代码进行翻译时遇到了麻烦。翻译的代码可以正常工作,因为我可以输入固定的语言,它将翻译成该语言。但是如何根据用户输入来确定目标语言。我尝试将语言下拉列表设置为您选择图像时使用的相同形式,使用request.method = "POST",然后使用target = request.args['lang_target'],将其命名为“ lang_target”。但这会返回错误:werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'lang_target'

Python:

def Lang_target():
    language_targ={
        'af': 'Afrikaans',              'sq':'Albanian',    'ar': 'Arabic',     'az': 'Azerbaijani',
        'be': 'Belarusian',             'bn': 'Bengali',    'ca': 'Catalan',    'zh-CN': 'Chinese Simplified',
        'zh-TW': 'Chinese Traditional', 'hr': 'Croatian',   'cs': 'Czech',      'da': 'Danish',     
        'nl': 'Dutch',                  'en': 'English',    'eo': 'Esperanto',  'et': 'Estonian',
        'tl': 'Filipino',               'fi': 'Finnish',    'fr': 'French',     'gl': 'Galician',   
        'ka': 'Georgian',               'de': 'German',     'el': 'Greek',      'gu': 'Gujarati',
        'ht': 'Haitian Creole',         'iw': 'Hebrew',     'hi': 'Hindi',      'hu': 'Hungarian',
        'is': 'Icelandic',              'ga': 'Irish',      'it': 'Italian',    'id': 'Indonesian',
        'ja': 'Japanese',               'kn': 'Kannada',    'ko': 'Korean',     'la': 'Latin',
        'lv': 'Latvian',                'lt': 'Lithuanian', 'mk': 'Macedonian', 'ms': 'Malay',
        'mt': 'Maltese',                'no': 'Norwegian',  'fa': 'Persian',    'pl': 'Polish', 
        'pt': 'Portuguese',             'ro': 'Romanian',   'ru': 'Russian',    'sr': 'Serbian',
        'sk': 'Slovak',                 'es': 'Spanish',    'sl': 'Slovenian',  'sw': 'Swahili',
        'sv': 'Swedish',                'ta': 'Tamil',      'te': 'Telugu',     'th': 'Thai',
        'tr': 'Turkish',                'uk': 'Ukrainian',  'ur': 'Urdu',       'vi': 'Vietnamese',             
        'cy': 'Welsh',                  'yi': 'Yiddish',
    }
    return language_targ

@app.route('/selectImage')
def selectImage():
    fn = image_name()
    language_target = Lang_target()
    return render_template("selectImage.html", image_name=image_name, fn=fn, language_target=language_target)

@app.route('/getfileHelper', methods=['GET','POST'])
def getfileHelper():
    if request.method == 'POST':
        #get the file name
        #hfile upload: ttps://www.tutorialspoint.com/flask/flask_file_uploading.htm
        file = request.files['imgfile']
        filename = secure_filename(file.filename)   #from werkzeug import secure_filename
        #TEMP PRINT STATEMENT
        #print("filename    : ",filename)
        #if the user did not select a file return to the selectImage.html page
        if file.filename == '':
            flash("No file selected. Please select an image file")
            return render_template('selectImage.html')
        #call the funcion whihc does the AI
        texts = detect_text('static/images/'+filename)

        text_translations = [] #emty list for dictionary of original text and translation
        #loop through list of texts, call the transpate AI function,
        #  add origi nal text and tranlation to list of dictionaries
        for text in texts:
            #print('\n"{}"'.format(text.description))
            translate_client = translate.Client()  # Instantiates a client
            translate_text = text.description  # The text to translate
            source = 'en'  # The source language
            target = request.args['lang_target']  # The target language 
            # Translate text into targget language
            translation = translate_client.translate(translate_text, source_language=source, target_language=target)
            # add original text and translation as a dictionary to a list
            text_translations.append({'text':translate_text, 'translation':translation['translatedText']})

            db_append(filename, translate_text, translation['translatedText'])
        #print('TRANSLATIONS')
        #print(text_translations)
    return render_template('home.html', filename=filename, text_translations=text_translations)

HTML

<div class="container" style="padding-bottom: 100%; background-color: #f4976c; color: #66fcf1; ">
        <h1>Select image...</h1>
        <div style="height:100px;"></div>

        <form action="getfileHelper" method="POST" enctype="multipart/form-data">
            Project file path: <input type="file" name="imgfile">
            <br>
            <select name="lang_target">
                {% for x in language_target%} 
                    <option value='1'> {{ language_target[x] }}</option>
                {% endfor %}
            </select>
            <br>
            <input type="submit" value="Submit">
        </form>
        <br>

        {% if filename %}
            <img src="{{ url_for('static', filename='images/'+filename) }} " style="max-width:300px">
        {% endif %}

2 个答案:

答案 0 :(得分:0)

request.args查看URL参数,但是您正在通过POST发送回数据。尝试将request.args替换为request.form

答案 1 :(得分:0)

flask html中的for循环替换为key, value对。用以下几行替换您的代码(我假设您的flask重定向和参数正确传递了。)

<select name="lang_target">
  {% for key,value in language_target%}
    <option value='{{ key }}'> {{ value }}</option>
  {% endfor %}
</select>