1.安装flask框架 在自己python的环境下直接通过pip安装,不写版本会默认最新版本,安装同时安装其他的库,属于flask的依赖包。
pip install flask
2.快速使用flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "hello,flask!"
if __name__ == "__main__":
app.run()
2.1传入参数
@app.route(("/chuanzhi/<int:age>"))
def age(age):
print(age)
return "传值成功"
2.2 还可以渲染html页面,导入render_template
from flask import Flask,render_template
完整代码: Mian.py
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/login", methods=["post", "get"])
def login():
return render_template("login.html")
if __name__ == "__main__":
app.run()
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>testFlask</title>
</head>
<body>
<h1>登录页面</h1>
<form method="POST">
用户名<input type="text" name="user">
密码<input type="text" name="pwd">
<input type="submit" name="提交">
</form>
</body>
</html>
接下来进行用户名以及密码的判断,为了方便就不接入数据库了
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route("/login", methods=["post", "get"])
def login():
if request.method == "GET":
return render_template("login.html")
if request.method == "POST":
user = request.form.get("user")
pwd = request.form.get("pwd")
if (user == "11") and (pwd == "11"):
return "登陆成功!!"
else:
return "用户名或密码错误!!"
if __name__ == "__main__":
app.run()
以下是接入数据库的代码,可自行实践
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route("/login", methods=["post", "get"])
def login():
if request.method == "GET":
return render_template("login.html")
if request.method == "POST":
user = request.form.get("user")
pwd = request.form.get("pwd")
db = pymysql.connect(host="localhost", port=3306, user="root", password="root123", database='flask')
cursor = db.cursor()
sql = "select * from flask.user where name='"+user+"' and pwd='"+pwd+"';"
cursor.execute(sql)
results = cursor.fetchall()
if results == ():
return "用户名或密码错误!!"
else:
return "登陆成功!!"
if __name__ == "__main__":
app.run()
|