赞
踩
在自己python的环境下直接通过pip安装,不写版本会默认最新版本,安装同时安装其他的库,属于flask的依赖包。
pip install flask
from flask import Flask
# 创建Flask对象
app = Flask(__name__)
# route()函数告诉那个URL执行哪个函数
@app.route("/mingda")
def hello():
return "hello,mingda"
if __name__ == "__main__":
app.run()
运行后:
出错原因就是路由@app.route("/mingda")的问题,修改后就成功了。
传参
@app.route(("/age/<int:age>"))
def age(age):
print(age)
return "how old are you?"
成功
此外,我很还可以渲染html页面,导入render_template
from flask import Flask,render_template
@app.route("/login")
def login():
return render_template("login.html")
我们的html页面放在以下路径,如果不放在以下路径,可能会报错。因为Flask对象会默认去templates下去找。
成功
使用post或者get请求时,是需要加入methonds
@app.route("/login", methods=["post", "get"])
注意POST和GET的书写方式,错了好多次。。。。
我们可以连接数据库做个简单的登陆验证
html页面还用刚才上面的
@app.route("/login", methods=["post", "get"]) def login(): if request.method == "GET": return render_template("login.html") if request.method == "POST": # 通过request获取表单提交的内容 user = request.form.get("user") pwd = request.form.get("pwd") # 连接数据库 db = pymysql.connect(host="localhost", port=3306, user="root", password="root123", database='flask') # 创建游标作用:如果不使用游标功能,直接使用select查询,会一次性将结果集打印到屏幕上,你无法针对结果集做第二次编程。 # 使用游标功能后,我们可以将得到的结果先保存起来,然后可以随意进行自己的编程,得到我们最终想要的结果集。 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()
这样简单的登录功能就写好了
如果输入错误,就会提示错误。
第一部分就先写到这里,后续会更新以下。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。