最近去网上学了Flask框架,于是来写点笔记,就当是给日后复习用。
这是第一篇笔记,就从最基础的return开始,一步步讲吧,如果有错漏的地方还请各位和今后的我指出,十分感谢。
以下代码的编辑器均使用Pycharm
第一个Flask应用
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'hello world'`
if __name__ == "__main__":
app.run()
这就创建好了第一个应用了,点击运行,会弹出
点击链接,就可以在浏览器上看到Hello world。
Flask三剑客和小儿子
Flask三剑客
第一种为直接返回
@app.route('/index')
def index():
return '123'
第二种为重定向路由,导入redirect,重定向至/index
from flask import redirect
@app.route('/')
def red():
return redirect('/index')
第三种是返回静态模板,导入render_template,当访问/login即返回index.html。
实现该方法需要在app下创建templates目录。
from flask import render_template
@app.route('/login')
def login():
return render_template('index.html')
Flask 小儿子
Flask有提供返回json标准的字符串方法,即jsonify。
from flask import jsonify
@app.route('/')
def red():
return jsonify ({'name':11,})
运行后会返回字典,同时浏览器可见
Content-Tpye:application/json
Flask还提供了返回图片、视频、音频等文件的方法,即send_file。
比如,我的应用下存在/static/img目录,将其中一张图片返回
from flask import send_file
@app.route('/')
def red():
return send_file('./static/img/1.jpg')
将一个音频返回
@app.route('/index')
def index():
return send_file('./static/img/千里之外.mp3')
以此推类,注意,send_file可自动识别返回文件格式。
Flask的request
Flask的request用来获取用户提交的表单,下面是一个简单的登录验证。
先是一个简单的登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form method="post">
<input type="text" placeholder="请输入用户名" name="username">
<input type="text" placeholder="请输入密码" name="password">
<button>登录</button>
</form>
</body>
</html>
然后是Python代码:
from flask import Flask, render_template, request
@app.route('/')
def index():
return redirect('/login')
@app.route('/login', methods=['GET', 'POST'])
def Login():
if request.method == 'GET':
return render_template('login.html')
if request.method == 'POST':
print(request.form)
if request.form.get('username') == 'AZerork' and request.form.get('password') == '123456':
student['name'] = request.form.get('username')
student['password'] = request.form.get('password')
return render_template('index.html', stu=student)
else:
return render_template('login.html')
注意,methods=[‘GET’,‘POST’]中的GET为请求,用户进入页面,点击页面都算是一个请求,POST为提交,登录就是一种POST,故有时为了限制用户,会将POST去掉。
第二则是request,request有很多种方法,如代码所示,.method是提取状态,.form是提取用户提交表单,表单格式为字典,格式为{‘前端name’:‘用户输入’,}
此时浏览器页面为:
仅当输入AZerork和123456时,返回index.html,否则返回login.html
request有如下的几种方法:
先写到这,有空继续慢慢更新,有错误欢迎指正。