简体   繁体   中英

How to return flask output to the same html page

I have an html file which reads like this:

<!DOCTYPE html>
<html>
    <head>
    <meta charset="UTF-8">
    <title>Robots Uploader</title>
    <link rel="stylesheet" href="css/style.css">
    </head>
<body>
        <section id="content">
            <section class="module w100P">
                <div id="error_bar" style = "display:none" class="message-bar error">
                    <p><span class="icon">Error:</span> Uh-oh, something broke! <a href="#" class="btn close">Close</a></p>
                </div>
                <div id="success_bar" style="display:none" class="message-bar success">
                    <p><span class="icon">Success:</span> Your changes have been made. <a href="#" class="btn close">Close</a></p>
                </div>

                <div class="module-inner">
                    <h3>DailyHunt Robots Uploader</h3>
                    <div class="module-content frm">
                        <form action="http://localhost:5000/uploadFile" method="post" enctype="multipart/form-data">
                            <table>
                                <tr>
                                    <td>
                                        <select name ="domain">
                                            <option selected>Select Domain</option>
                                            <option value="m">m</option>
                                            <option value="www">www/option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="file" name="robots" accept='robots.txt'>
                                        <button type="submit">Upload</button>
                                    </td>
                                </tr>
                            </table>
                        </form>
            <form action="http://localhost:5000/uploadApk" method="post" enctype="multipart/form-data">
                <table>
                <tr>
                    <td>
                    Enter APK you want to upload:
                    </td>
                    <td>
                    <input type="file" name="apk">
                    <button type="submit">Upload</button>
                    </td>
                </table>
            </form>
                    </div>
                </div>
            </section>
        </section>
    </section>   
</body>
</html>

on hitting submit, it hits the flask api engine, where the 2 functions to be hit are defined as

@app.route('/uploadFile', methods=['POST'])
def upload_robots():
    domain = request.form.get('domain')
    if not domain:
        return "Domain does not exist"
    f = request.files[ROBOTS_IDENTIFIER]
    if f.filename!=ROBOTS_FILE_NAME:
        return "Incorrect file name. File name has to be robots.txt"
    if domain == 'm':
        robots_file_path = ROBOTS_MOBILE_FILE_PATH
    elif domain == 'www':
        robots_file_path = ROBOTS_WEB_FILE_PATH
    else:
        return "Domain not recognized"
    filename = secure_filename(f.filename)
    if os.path.isfile(robots_file_path + ROBOTS_FILE_NAME):
        folder_name = datetime.utcfromtimestamp(int(os.path.getmtime(robots_file_path + ROBOTS_FILE_NAME))).strftime('%Y-%m-%d %H:%M:%S')
        os.makedirs(robots_file_path + folder_name)
        shutil.move(robots_file_path + ROBOTS_FILE_NAME, robots_file_path + folder_name +'/' + ROBOTS_FILE_NAME)
    f.save(os.path.join(robots_file_path, ROBOTS_FILE_NAME))
    return "file uploaded successfully, This will reflect in prod after the next cron cycle"

@app.route('/uploadApk', methods=['POST'])
def upload_apk():
    f = request.files[APK_IDENTIFIER]
    if f.filename.split('.')[-1] != 'apk':
        return "upload file type must be apk"
    filename = secure_filename(f.filename)
    fname = '.'.join(f.filename.split('.')[0:-1])
    rename = False
    while os.path.isfile(APK_FILE_PATH + fname + '.apk'):
        rename = True
        fname += '_'
    if rename:
        shutil.move(APK_FILE_PATH + f.filename, APK_FILE_PATH + fname + '.apk')
    f.save(os.path.join(APK_FILE_PATH, filename))
    return "APK uploaded successfully"

Now when I hit submit the api returns some texts and it gets directed to a new page with just the text rendered. I would like this to remain in the same page and display the error_bar or success_bar divs in the html rather than it being redirected to a new page. Is it possible to achieve this without rendering a template or creating a new static html page?

Let's assume that your current page is: index.html.

I thought about two ways for resolving.

  • The first way, After making request to your API, just render_template index.html again, including extra data (error=True/False, message=...) and you have update your index.html to check condition when receive extra data to display the error/success message.

    => By this way, you should modify the template and use Flask's render_template. I prefer this way because of having control of the template (index.html) it just needs small update.

  • The second way, make request by using AJAX (XHR), when click submit button, you prevent the default form submit and use AJAX to request, then receive response and display the message. The AJAX script can stay in index.html or another *.js where your index.html can locate.

    => By this way, you are working in non-Flask dependent way, by using Ajax you make request and modify the document (index.html) by using a little Javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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