HHR的小站
享受代码带来的快乐吧
首页
用Flask实现一个简单的Web应用
2021-02-04 |HHR | 代码使人快乐

我做了什么?

一个基于Flask的Web应用,输入教务系统的账号密码,即可查询学生的平时成绩

怎么用?

打开这个链接,输入账号密码,即可查看到成绩

想看源代码?

本应用在GitHub上开源,点击这个链接查看

部分代码实现

import json

from flask import Flask, request, render_template

from service import get_score_detail, get_gpa_info, beautify_msg

app = Flask(__name__)


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


@app.route('/score', methods=["POST"])
def get_score():
    username = request.form['username']
    password = request.form['password']
    year = request.form['year']
    term = request.form['term']
    config = [username, password, year, term]
    score_list = beautify_msg(get_gpa_info(config, get_score_detail(config)))
    return json.dumps(score_list)


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

指定路由

使用@app.route()方法,可以包含参数指定路由及支持的请求方法

@app.route('/score', methods=["POST"])

获取表单数据

使用 Flask框架提供的 request对象,通过request.form获取表单中的数据

    username = request.form['username']
    password = request.form['password']
    year = request.form['year']
    term = request.form['term']

返回数据

使用 json.dumps方法将需要返回的对象转化为json,返回给前端

    return json.dumps(score_list)

模板页面

将页面放入 template文件夹,在方法中使用render_template函数渲染页面

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

静态资源

将静态资源放入 static 文件夹,即可使用类似于 https://www.example.com/static/css/example.css 的方法访问静态资源

respond-post-498

添加新评论

请填写称呼
请填写合法的电子邮箱地址
请填写合法的网站地址
请填写内容