程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Python Flask框架之页面跳转

发布于2019-08-23 19:00     阅读(862)     评论(0)     点赞(6)     收藏(5)


IDE用的PyCharm(还是vs强大啊)。

项目结构:

2:页面:
复制代码
<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title><link rel="shortcut icon" href="{{ url_for('static', filename='images/lock.png')}}"/>
</head>
<body>
<div align="center">
    <div>
        <div>
            <h1>Welcome</h1>
            <form class="form" method="post" action="" onsubmit="return Login();">
                <input type="text" placeholder="Username" name="username" id="username">
                <input type="password" placeholder="Password" name="password" id="password">
                <button type="submit" id="login-button">SubmitLogin</button>
                <button type="button" id="btnlogin">ButtonLogin</button>
                <a href="infor">testhtm</a>
            </form>
        </div>
    </div>
</div>

<script type="text/javascript" src="{{ url_for('static', filename='jquery.min.js') }} "></script>
{#<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>#}
<script type="text/javascript">
    function Login() {
        var login = false;
        var  txtname = $("#username").val();
        var txtpsw = $("#password").val();

        $.ajax({
            {#url:  "/py_login",可以#}
            url:"{{url_for("py_login") }}",{# 可以调到后台,路由名称#}
            {#data: "username=" + txtname + "&password=" + txtpsw,#}
            data:{"username":txtname,"userpswd":txtpsw},
            type: 'GET',
            contentType: 'json',{#'application/x-www-form-urlencoded',#}
            async: false,
            success: function (d) {
                alert("success!"+d)
                var status = d.status;
                if (d != "undefined" && d=="success")
                {
                     window.location.href="infor";{# 这里链接的应该是路由中的名称#}
                }
                else
                {
                    alert("登录失败!")
                }
            }
        });
        return login;
    }
</script>

</body>
</html>
复制代码


3:后台FlaskWeb.py文件。

复制代码
from flask import Flask, render_template, redirect, request, url_for , send_file
import pymssql

app = Flask(__name__)
# app.debug = True;
# @app.route('/')
@app.route('/')
def index():
    return render_template('login.html') # send_file('index.html')


@app.route('/py_login',methods=['GET','POST'])
def py_login():
    if request.method == 'GET':

        print(request.form)
        txtname = request.args.get('username')
        txtpswd = request.args.get('userpswd')

        if(txtname=="longdb" and txtpswd=="123"):
            return "success"  # get可以到这里
            print(url_for('/testhtm'))
            # return redirect(url_for('/testhtm'))
        else:
            return "enterfailed"

@app.route('/infor') #页面链接该路由名称
def f_infor():
    return render_template('infor.html')  # send_file('/templates/testhtm.html') #

# 函数


@app.route('/insertdata',methods=['GET','POST'])
def py_insertdata():
    # noinspection PyBroadException
    try:
        # conn = pymssql.connect(server='longdabing',user='sa',password='sasa',database='longtest')
        conn = pymssql.connect('longdabing', 'sa', 'sasa', 'longtest')
        cursor = conn.cursor()

        txtno = request.args.get('hno')
        txtname = request.args.get('hname')
        txtobject = request.args.get('hobject')
        txtscore = request.args.get('hscore')
        sql = "INSERT dbo.infor( no, name, object, score )VALUES ( '"+txtno+"','"+txtname+"','"+txtobject+"','"+txtscore+"')"
        cursor.execute(sql)
        conn.commit()  # 提交数据到数据库,否则不会插入到数据库中

        conn.close()
        return "insertok"
    except Exception as e:
        conn.rollback()  # 回滚操作
        return "insertfailed"
        raise e
    # finally:
    #   conn.close()




def getdata(sql):
    # conn = pymssql.connect(server='longdabing',user='sa',password='sasa',database='longtest')
    conn = pymssql.connect('longdabing', 'sa', 'sasa', 'longtest')
    cursor = conn.cursor()
    cursor.execute(sql)
    row = cursor.fetchone()
    while row:
      print("ID=%d, No=%s, Name=%s, Object=%s, Score=%s" % (row[0], row[1], row[2], row[3], row[4]))
      row = cursor.fetchone()
    conn.close()
    return




if __name__ == '__main__':
    app.run()
复制代码

注明:运行FlaskWeb.py文件时,路由longin.html页面,进入该页面后,输录入账号和密码,验证通过的话,则通过window.location.href="infor";{# 这里链接是路由中的名称#} 来跳转页面,最终还是由后台加载页面 infor.html

 

本来想在用户和密码验证通过后,用 redirect()方法跳转到 infor.html页面的,但是都失败,所以才用了window.location.href

求大神指点后台直接跳转的方法。



所属网站分类: 技术文章 > 博客

作者:j878

链接:https://www.pythonheidong.com/blog/article/55812/b1aa1103f896707b3dc1/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

6 0
收藏该文
已收藏

评论内容:(最多支持255个字符)