首页 > 解决方案 > Python 应用程序无法重定向到另一个页面

问题描述

我正在尝试根据 if 和 else 语句将一个页面重定向到 python 中的另一个 html 页面。我已经导入了所需的库(flask,redirect)。我可以通过 URL 访问其他 Html 页面,但是当我尝试通过单击按钮呈现特定的 html 页面(CompleteAppliction.html)时,它显示错误 Not Found The requested URL was not found 在服务器上。如果您手动输入了 URL,请检查您的拼写并重试。我也使用了完整的目录但没有用。

这是python代码。

import flask
import pickle
import pandas as pd
import numpy as np
from flask import Flask,redirect

from sklearn.preprocessing import StandardScaler


#load models at top of app to load into memory only one time
with open('models/loan_application_model_lr.pickle', 'rb') as f:
    clf_lr = pickle.load(f)


# with open('models/knn_regression.pkl', 'rb') as f:
#     knn = pickle.load(f)    
ss = StandardScaler()


genders_to_int = {'MALE':1,
                  'FEMALE':0}

married_to_int = {'YES':1,
                  'NO':0}

education_to_int = {'GRADUATED':1,
                  'NOT GRADUATED':0}

dependents_to_int = {'0':0,
                      '1':1,
                      '2':2,
                      '3+':3}

self_employment_to_int = {'YES':1,
                          'NO':0}                      

property_area_to_int = {'RURAL':0,
                        'SEMIRURAL':1, 
                        'URBAN':2}




app = flask.Flask(__name__, template_folder='templates')
@app.route('/')
def main():
    return (flask.render_template('index.html'))

@app.route('/report')
def report():
    return (flask.render_template('report.html'))

@app.route('/jointreport')
def jointreport():
    return (flask.render_template('jointreport.html'))

@app.route('/CompleteApplication')
def CompleteApplication():
    return (flask.render_template('CompleteApplication.html'))

@app.route("/Loan_Application1", methods=['GET', 'POST'])
def Loan_Application1():
    
    if flask.request.method == 'GET':
        return (flask.render_template('Loan_Application1.html'))
    
    if flask.request.method =='POST':
        
        #get input
        #gender as string
        genders_type = flask.request.form['genders_type']
        #marriage status as boolean YES: 1 , NO: 0
        marital_status = flask.request.form['marital_status']
        #Dependents: No. of people dependent on the applicant (0,1,2,3+)
        dependents = flask.request.form['dependents']
        
        #dependents = dependents_to_int[dependents.upper()]
        
        #education status as boolean Graduated, Not graduated.
        education_status = flask.request.form['education_status']
        #Self_Employed: If the applicant is self-employed or not (Yes, No)
        self_employment = flask.request.form['self_employment']
        #Applicant Income
        applicantIncome = float(flask.request.form['applicantIncome'])
        #Co-Applicant Income
        coapplicantIncome = float(flask.request.form['coapplicantIncome'])
        #loan amount as integer
        loan_amnt = float(flask.request.form['loan_amnt'])
        #term as integer: from 10 to 365 days...
        term_d = int(flask.request.form['term_d'])
        # credit_history
        credit_history = int(flask.request.form['credit_history'])
        # property are
        property_area = flask.request.form['property_area']
        #property_area = property_area_to_int[property_area.upper()]

        #create original output dict
        output_dict= dict()
        output_dict['Applicant Income'] = applicantIncome
        output_dict['Co-Applicant Income'] = coapplicantIncome
        output_dict['Loan Amount'] = loan_amnt
        output_dict['Loan Amount Term']=term_d
        output_dict['Credit History'] = credit_history
        output_dict['Gender'] = genders_type
        output_dict['Marital Status'] = marital_status
        output_dict['Education Level'] = education_status
        output_dict['No of Dependents'] = dependents
        output_dict['Self Employment'] = self_employment
        output_dict['Property Area'] = property_area
        


        x = np.zeros(21)
    
        x[0] = applicantIncome
        x[1] = coapplicantIncome
        x[2] = loan_amnt
        x[3] = term_d
        x[4] = credit_history

        print('------this is array data to predict-------')
        print('X = '+str(x))
        print('------------------------------------------')

        pred = clf_lr.predict([x])[0]
        
        if pred==1:
            res = 'Congratulations! your Loan Application has been Approved!'
            # return redirect (flask.render_template('Loan_Application1.html')
            return redirect(flask.render_template('CompleteApplication.html'))
        else:
                res = 'Unfortunatly your Loan Application has been Denied'
        #Stay in same page 

 
        #render form again and add prediction
        return flask.render_template('Loan_Application1.html', 
                                     original_input=output_dict,
                                     result=res,)
     
        
      
if __name__ == '__main__':
    app.run(debug=True)

这是项目结构的屏幕截图。

在此处输入图像描述

这是页面第一次加载并且工作正常时的屏幕截图。 在此处输入图像描述

这是我单击按钮时的屏幕截图。 在此处输入图像描述

标签: pythonhtmlvisual-studioflask

解决方案


改变

return redirect(flask.render_template('CompleteApplication.html'))

return flask.render_template('CompleteApplication.html')

redirect()用于 URL,例如return redirect('https://stackoverflow.com')


推荐阅读