flask [微型网络开发框架]

    # http://dormousehole.readthedocs.org/en/latest/
    # http://www.pythonhosted.org/Flask-Bootstrap/basic-usage.html#templates
    # html放在 ./templates/   js放在 ./static/

    #pip install Flask-Login
    #pip install Flask-OpenID
    #pip install Flask-WTF
    #pip install flask-bootstrap
    #pip install flask-sqlalchemy
    #pip install flask-script
    #pip install flask-migrate

    request.args.get('page', 1)          # 获取参数 ?page=1
    request.json                         # 获取传递的整个json数据
    request.form.get("host",'127')       # 获取表单值
    request.form.getlist('client')       # 获取表单列表

简单实例 # 接收数据和展示

        import MySQLdb as mysql
        from flask import Flask, request

        app = Flask(__name__)
        db.autocommit(True)
        c = db.cursor()

        """
        CREATE TABLE `statusinfo` (
          `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
          `hostname` varchar(32) NOT NULL,
          `load` float(10) NOT NULL DEFAULT 0.00,
          `time` int(15) NOT NULL,
          `memtotal` int(15) NOT NULL,
          `memusage` int(15) NOT NULL,
          `memfree` int(15) NOT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=161 DEFAULT CHARSET=utf8;
        """

        @app.route("/collect", methods=["GET", "POST"])
        def collect():
            sql = ""
            if request.method == "POST":
                data = request.json                      # 获取传递的json
                hostname = data["Host"]
                load = data["LoadAvg"]
                time = data["Time"]
                memtotal = data["MemTotal"]
                memusage = data["MemUsage"]
                memfree = data["MemFree"]

                try:
                    sql = "INSERT INTO `statusinfo` (`hostname`,`load`,`time`,`memtotal`,`memusage`,`memfree`) VALUES('%s', %s, %s, %s, %s, %s);" % (hostname, load,time,memtotal,memusage,memfree)
                    ret = c.execute(sql)
                    return 'ok'
                except mysql.IntegrityError:
                    return 'errer'

        @app.route("/show", methods=["GET", "POST"])
        def show():
            try:
                hostname = request.form.get("hostname")     # 获取表单方式的变量值
                sql = "SELECT `load` FROM `statusinfo` WHERE hostname = '%s';" % (hostname)
                c.execute(sql)
                ones = c.fetchall()
                return render_template("sysstatus.html", data=ones, sql = sql)
            except:
                print 'hostname null'

        from flask import render_template
        @app.route("/xxx/<name>")
        def hello_xx(name):
            return render_template("sysstatus.html", name='teach')

        if __name__ == "__main__":
            app.run(host="0.0.0.0", port=50000, debug=True)
文档更新时间: 2018-11-21 17:53   作者:RuM