# 基于werkzeug
# from werkzeug.serving import run_simple
#
# def func(environ,start_response):
#     print("进来了")
#     pass
#
# if __name__ == '__main__':
#     run_simple('127.0.0.1',5000,func)

# from werkzeug.serving import run_simple
# class Flask(object):
#     def __call__(self, environ, start_response):
#         return "xx"
#
# app = Flask()
#
# if __name__ == '__main__':
#     run_simple('127.0.0.1', 5000, app)


# from werkzeug.serving import run_simple
# class Flask(object):
#     def __call__(self, environ, start_response):
#         return "xx"
#     def run(self):
#         run_simple('127.0.0.1', 5000, self)
#
# app = Flask()
#
# if __name__ == '__main__':
#     app.run()


# 基于Flask
# from flask import Flask
#
# app = Flask(__name__)
# @app.route('/index')
# def index():
#     return 'hello word'
#
# if __name__ == '__main__':
#     app.run()

# 某管理系统登录页面
from flask import Flask, render_template, request, redirect, url_for,session

app = Flask(__name__, template_folder="templates")  # template_folder默认为templates

DATA_DICT = {
    1: {'name': '陈硕', 'age': 73},
    2: {'name': '汪洋', 'age': 84}
}

app.secret_key='hgcsdufdsjbc'

@app.route('/login', methods=["GET", "POST"])
def login():
    # return '登录'
    # return render_template('login.html')
    # return jsonify({'code':1000,'data':[1,2,3]})
    # POST 请求要接收用户数据
    if request.method == "GET":
        return render_template('login.html')
    # return (request.form)
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    if user == 'xu' and pwd == "li":
        session['xxx']='xu'
        # return "登录成功"
        return redirect('/index')
    error = "用户名或密码错误"
    # return render_template('login.html',**{'error':error})
    return render_template('login.html', error=error)


@app.route('/index', endpoint='idx')
def index():
    username=session.get('xxx')
    if not username:
        # return redirect('/login')
        return redirect(url_for('login'))
    # return "首页"
    data_dict = DATA_DICT
    return render_template('index.html', data_dict=data_dict)


@app.route('/edit', methods=['GET', 'POST'])
def edit():
    nid = request.args.get('nid')
    nid = int(nid)

    if request.method == "GET":
        print(nid, type(nid))  # 通过get获得的都是str
        info = DATA_DICT[nid]
        # return "修改"
        return render_template('edit.html', info=info)  # 提交是post请求

    user = request.form.get('user')
    age = request.form.get('age')
    # print(user, age)
    # return "修改"
    DATA_DICT[nid]['name'] = user
    DATA_DICT[nid]['age'] = age
    return redirect(url_for('idx'))


@app.route('/del/<int:nid>')
def delete(nid):
    # nid = request.args.get("nid")
    del DATA_DICT[nid]
    # print(nid)
    # return "删除"
    # return redirect('/index')
    return redirect(url_for("idx"))


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