python Web应用程序

web应用程序是一种可以通过浏览器访问的应用程序,主要采用浏览器/服务器架构

安装flask库pip install flask

第一个服务器程序

hello.py :

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "hello, world <br> 这是一个web应用程序"

if __name__ == "__main__":
    app.run()


python hello.py 打开 127.0.0.1:5000

返回html界面

hello_html.py

from flask import Flask

app = Flask(__name__)

@app.route("/index")
def index():
    return '''<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>div标签</title>
</head>
<body>
    <h2>最新课程排行</h2>
    <ol>
        <li>版本管理工具介绍-Git篇</li>
        <li>Maven项目构建与管理</li>
        <li>SpringBoot 后端业务代码</li>
    </ol>

</body>
</html>'''


if __name__ == "__main__":
    app.run()


python hello_html.py 打开 127.0.0.1:5000/index

css层叠样式表

python_css.py

from flask import Flask

app = Flask(__name__)

@app.route("/css")
def css():
    return '''<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>css标签</title>
    <style type="text/css">
        .stress{font-weight: bold;}
        .bigsize{font-size: 25px;}
        #stressid{font-weight: bold;}
        #bigsizeid{font-size: 30px;}
    </style>

</head>
<body>
    <h2>热门课程排行榜</h2>
    <ol>
        <li>java</li>
        <li>html/css/<span id="stressid">javascript</span>前端三剑客</li>
        <li>数据库</li>
    </ol>

    <h2>最新课程排行</h2>
    <ol>
        <li>版本<span class="stress">管理工具</span>介绍-Git篇</li>
        <li>Maven 项目构建与管理</li>
        <li><span class="stress bigsize">SpringBoot</span>后端业务代码</li>
    </ol>

</body>
</html>'''


if __name__ == "__main__":
    app.run()


python hello_css.py 打开 127.0.0.1:5000/css

flask的使用
  1. 多个URL执行同一个函数 hello_hello.py :
from flask import Flask

app = Flask(__name__)

@app.route("/hello")
@app.route("/")
def hello():
    return "hello, world <br> 这是一个web应用程序"

if __name__ == "__main__":
    app.run()


浏览器输入 http://127.0.0.1:5000http://127.0.0.1:5000/hello 结果是相同的

  1. get和post方法 默认是相当于 @app.route("/", methods = ["get"]) 可以写成@app.route("/", methods = ["get", "post"]) add.py :
from flask import Flask

app = Flask(__name__)
html = '''
<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>两数之和</title>
</head>
<body>
    <h2>输入两个数求和</h2>
    <form method="post" action="/add">
    <table>
        <p>使用表单计算两个数的和</p>
        <tr>
            <td>    被加数  </td>
            <td>    <input type="text" name = 'a'/>    </td>
        </tr>

        <tr>
            <td> 加数 </td>
            <td> <input type="text" name = 'b'/>   </td>
        </tr>

        <tr>
            <td> 和 </td>
            <td> <input type="text" name = 's'/> </td> 
        </tr>
    </table>
    
    <button name="sum" type="submit" value="sum"> 求和</button>

</body>
</html>
'''
from flask import request
@app.route("/add", methods = ["post"])
def add():
    a = int(request.form['a'])
    b = int(request.form['b'])
    s = a + b
    return str(s)

@app.route("/", methods = ["get"])
def index():
    return html

if __name__ == "__main__":
    app.run()


浏览器输入 http://127.0.0.1:5000 , 输入两个数a和b,返回 a + b的结果

  1. 改进在原界面显示结果 要是界面不跳转,实际上是跳转到原来的界面就行了 add.py :
from flask import Flask

app = Flask(__name__)


html = '''
<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>两数之和</title>
</head>
<body>
    <h2>输入两个数求和</h2>
    <form method="post" action="/add">
    <table>
        <p>使用表单计算两个数的和</p>
        <tr>
            <td>    被加数  </td>
            <td>    <input type="text" name = 'a'/ value=%s>    </td>
        </tr>

        <tr>
            <td> 加数 </td>
            <td> <input type="text" name = 'b'/ value=%s>   </td>
        </tr>

        <tr>
            <td> 和 </td>
            <td> <input type="text" name = 's'/ value=%s> </td> 
        </tr>
    </table>
    
    <button name="sum" type="submit" value="sum"> 求和</button>

</body>
</html>
'''


from flask import request
@app.route("/add", methods = ["post"])
def add():
    a = int(request.form['a'])
    b = int(request.form['b'])
    s = a + b
    return html % (a, b, s)

@app.route("/", methods = ["get"])
def index():
    return html % ("", "", "")

if __name__ == "__main__":
    app.run()


浏览器输入 http://127.0.0.1:5000 , 输入两个数a和b,返回 a + b的结果

  1. 使用一个函数来处理多个请求 add.py :
from flask import Flask

app = Flask(__name__)

html = '''
<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>两数之和</title>
</head>
<body>
    <h2>输入两个数求和</h2>
    <form method="post" action="/add">
    <table>
        <p>使用表单计算两个数的和</p>
        <tr>
            <td>    被加数  </td>
            <td>    <input type="text" name = 'a'/ value=%s>    </td>
        </tr>

        <tr>
            <td> 加数 </td>
            <td> <input type="text" name = 'b'/ value=%s>   </td>
        </tr>

        <tr>
            <td> 和 </td>
            <td> <input type="text" name = 's'/ value=%s> </td> 
        </tr>
    </table>
    
    <button name="sum" type="submit" value="sum"> 求和</button>

</body>
</html>
'''


from flask import request


@app.route("/", methods = ["get"])
@app.route("/add", methods = ["post"])
def index():
    print(request.method)
    if request.method == "GET":
        return html % ("", "", "")
    else:
        a = int(request.form['a'])
        b = int(request.form['b'])
        s = a + b
        return html % (a, b, s)

if __name__ == "__main__":
    app.run()
前后端分别开发

建立目录结构

add.py
templates
    |----- index.html
    |----- result.html

用 render_template对html进行渲染

add.py

from flask import Flask
app = Flask(__name__)

from flask import request, render_template

@app.route("/", methods = ["get"])
@app.route("/add", methods = ["post"])
def index():
    print(request.method)
    if request.method == "GET":
        return render_template("index.html")
    else:
        a = int(request.form['a'])
        b = int(request.form['b'])
        s = a + b
        return render_template("result.html", a = a, b = b, s = s)

if __name__ == "__main__":
    app.run()

index.html

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>两数之和</title>
</head>
<body>
    <h2>输入两个数求和</h2>
    <form method="post" action="/add">
    <table>
        <p>使用表单计算两个数的和</p>
        <tr>
            <td>    被加数  </td>
            <td>    <input type="text" name = 'a'/ >    </td>
        </tr>

        <tr>
            <td> 加数 </td>
            <td> <input type="text" name = 'b'/ >   </td>
        </tr>


    </table>
    
    <button name="sum" type="submit" value="sum"> 求和</button>

</body>
</html>

result.html

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>两数之和</title>
</head>
<body>
    <h2>输入两个数求和</h2>
    <form method="post" action="/add">
    <table>
        <p>使用表单计算两个数的和</p>
        <tr>
            <td>    被加数  </td>
            <td>    <input type="text" name = 'a'/ value = {{a}} >    </td>
        </tr>

        <tr>
            <td> 加数 </td>
            <td> <input type="text" name = 'b'/ value = {{b}} >   </td>
        </tr>

        <tr>
            <td> 和 </td>
            <td> <input type="text" name = 's'/ value = {{s}}> </td> 
        </tr>
    </table>
    
    <button name="sum" type="submit" value="sum"> 求和</button>

</body>
</html>
前后端分离

前端使用 jQuery来向后端发起请求,后端处理后返回结果给前端,前端根据数据进行填充

<!DOCTYPE HTML>
<html>
<head>
    <!-- 导入 jQuery  -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>两数之和</title>
</head>
<body>
    <h2>输入两个数求和</h2>
    <form id = "sumForm">
    <table>
        <p>使用表单计算两个数的和</p>
        <tr>
            <td>    被加数  </td>
            <td>    <input type="text" id = 'a' name = 'a'/ required >    </td>
        </tr>

        <tr>
            <td> 加数 </td>
            <td> <input type="text" id = 'b' name = 'b'/ required>   </td>
        </tr>
    </table>
    
    <button name="sum" type="submit" value="sum"> 求和</button>

    <h2>结果是: <span id="result"></span></h2>

    <script>
        $(document).ready(function() {
            $('#sumForm').on('submit', function(event) {
                event.preventDefault();
                const a = parseFloat($('#a').val());
                const b = parseFloat($('#b').val());

                $.ajax({
                    url: '/calculate',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ a: a, b: b }),
                    success: function(response) {
                        $('#result').text(response.sum);
                    },
                    error: function(error) {
                        $('#result').text('请求错误: ' + error.responseText);
                    }
                });
            });
        });
    </script>

</body>
</html>

后端

from flask import Flask

app = Flask(__name__)


from flask import request, jsonify, render_template

@app.route("/")
def index():
    return render_template("cal.html")

@app.route("/calculate", methods = ["POST"])
def calculate():
    data = request.get_json()
    a = data.get("a")
    b = data.get("b")
    return jsonify({
        "sum" : a + b 
    })

if __name__ == "__main__":
    app.run()

目录结构

cal.py
templates
    |----- cal.html
    |----- result.html
查询学生信息

目录结构

student.py
templates
    |----- student.html
from flask import Flask

app = Flask(__name__)

# 示例学生数据
students = [
    {'name': '阿里', 'id': 'S001', 'age': 20},
    {'name': '京东', 'id': 'S002', 'age': 22},
    {'name': '美团', 'id': 'S003', 'age': 23}
]

from flask import jsonify, render_template

@app.route("/")
def index():
    return render_template("student.html")


@app.route('/students', methods=['GET'])
def get_students():
    return jsonify({'students': students})

if __name__ == '__main__':
    app.run(debug=True)

student.html

<!DOCTYPE HTML>
<html>
<head>
    <!-- 导入 jQuery  -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>学生信息</title>

    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid black;
        }
        th, td {
            padding: 15px;
            text-align: left;
        }
    </style>


</head>
<body>
    <h2>学生信息</h2>
    <button id="loadStudents">加载学生</button>
    <br><br>
    <table id="studentTable">
        <thead>
            <tr>
                <th>姓名</th>
                <th>学号</th>
                <th>年龄</th>
            </tr>
        </thead>
        <tbody>
            <!-- Student rows will be added here -->
        </tbody>
    </table>

    <script>
        $(document).ready(function() {
            $('#loadStudents').on('click', function() {
                $.ajax({
                    url: '/students',
                    type: 'GET',
                    success: function(response) {
                        const students = response.students;
                        const tbody = $('#studentTable tbody');
                        tbody.empty(); // Clear any existing rows
                        students.forEach(student => {
                            const row = `<tr>
                                            <td>${student.name}</td>
                                            <td>${student.id}</td>
                                            <td>${student.age}</td>
                                        </tr>`;
                            tbody.append(row);
                        });
                    },
                    error: function(error) {
                        alert('Error fetching student data');
                    }
                });
            });
        });
    </script>

</body>
</html>

0 条评论

目前还没有评论...