Flask初探
看过:
- https://www.bilibili.com/video/BV17W41177oE?p=18&spm_id_from=pageDriver
- https://www.bilibili.com/video/av254332268?from=search&seid=13702896751479222359&spm_id_from=333.337.0.0
flask 基本配置
from flask import Flask
app = Flask(__name__) # 开头必写,创建一个Flask对象从而进行后续操作
app.config["SECRET_KEY"] = "ABCDFWA" # 为防CSRF提供一个密匙
app.config["UPLOAD_FOLDER"] = "\upload" # 全局设置UPLOAD_FOLDER
@app.route('/')
def hello_world(): # 这是视图函数
# 控制相关的代码写在这里面
if __name__ == '__main__':
app.run() # 用刚刚创建的Flask对象控制程序运行
flask 规定路由和上传方式
@app.route('/', methods=['GET', 'POST']) # 规定访问网址(也就是路由)为ip/,可用传输方式为GET和POST
def hello_world():
# put application's code here
@app.route('/index', methods=['POST']) # 规定访问网址(也就是路由)为ip/index,可用传输方式为POST
def hello_world2():
# put application's code here
flask静态资源重定向(url_for)
url_for('static', filename='style.css')
这个文件应该存储在文件系统上的 static/style.css 。
在html中一般这样写:
<script src="{{ url_for('static',filename='front/js/yxMobileSlider.js') }}"></script>
flask路由转发
from flask import redirect
@app.route('/', methods=["GET", "POST"])
def login():
Form = LoginForm()
if Form.validate_on_submit():
Name = Form.UserName.data
Pas = Form.PassWord.data
print(Name)
print(Pas)
try:
x = db.QueryUserPas(Name)
if x == Pas:
print("Login Success")
else:
print("Login Failed")
return redirect(url_for("hello_world")) # 路由转发到hello_world函数的url
except Exception as e:
print(e)
return render_template("login.html", form=Form)
flask路由传参
@app.route("/showlog/<permission>", methods=['GET'])
# 这里就将/showlog/后面的东西当做了permission的值传过来了
def showlog(permission):
KEY = "PSAASS"
with open(staticFilePath, "a", encoding='utf-8') as f:
f.write("Somebody is Trying to open the File, {}:: {}\n".format(
"and this guy is admin" if permission == KEY else "and he failed", str(datetime.datetime.now())))
if permission == KEY:
return redirect(url_for('static', filename='loginfo.log'))
else:
return redirect(url_for("index"))
flask 渲染html模板
html内容(downloadBook.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件下载</title>
<style>
a{
text-decoration: none;
color: #2062e0;
}
a:hover{
text-decoration: none;
color: #2062e0;
}
</style>
</head>
<body>
<div align="center">
{# 将指定文件夹中的文件获取遍历显示 #}
{% for n in name %}
<a href="downloads/{{ n }}">{{ n }}</a>
<br><br>
{% endfor %}
</div>
</body>
</html>
flask路由函数内容
@app.route('/download', methods=['GET', 'POST'])
def download():
timelist = [] # 获取指定文件夹下文件并显示
Foder_Name = [] # 文件夹下所有文件
Files_Name = [] # 文件名
file_dir = app.config['UPLOAD_FOLDER']
# 获取到指定文件夹下所有文件
lists = os.listdir(file_dir + '/')
# 遍历文件夹下所有文件
for i in lists:
# os.path.getatime => 获取对指定路径的最后访问时间
timelist.append(time.ctime(os.path.getatime(file_dir + '/' + i)))
# 遍历文件夹下的所有文件
for k in range(len(lists)):
# 单显示文件名
Files_Name.append(lists[k])
# 获取文件名以及时间信息
Foder_Name.append(lists[k] + " ~~~~~~~~~~~~~~~~~~~~~ " + timelist[k])
print(file_dir) # ./upload
return render_template('downloadBook.html', allname=Foder_Name, name=Files_Name)
# 这里就在渲染的时候将模板中的allname用Foder_Name替换了,name用Files_Name替换了
模版html放在templates文件夹下
flask提供本地文件上传服务
@app.route('/mainview/', methods=['GET', 'POST'])
def hello_world(): # 这是视图函数
Up = UploadData()
UserName = session.get("UserName")
if UserName is None:
return redirect(url_for("login"))
RegisterTime, BriefDesc = db.QueryUserInfo(UserName)
UserSourceList = db.QueryUserResources(UserName)
SourceDetails = []
for ID in UserSourceList:
Detail = db.QueryResourcesByID(ID[0])[0]
SourceDetails.append([Detail[0], Detail[1], Detail[2], Detail[3], Detail[4], Detail[5]])
if Up.validate_on_submit():
f = Up.photo.data
filename = Up.fileName.data
f.save(os.path.join(ConfiglocalSources(), f.filename)) # 存储上传后的文件
SIZE = os.path.getsize(os.path.join(ConfiglocalSources(), f.filename)) # 计算文件的大小
db.UploadResource(filename, "::{}".format(f.filename), SIZE/(1024*1024), UserName) # 将文件数据存在数据库中
return redirect(url_for("hello_world"))
return render_template("dashboard.html", UserName=UserName, RegisterTime=RegisterTime, BriefDescription=BriefDesc,
NumOfSources=len(UserSourceList), SourceDetails=SourceDetails, Up=Up)
flask提供本地文件下载服务
@app.route('/downloads/<path:path>', methods=['GET', 'POST'])
def downloads(path):
return send_from_directory(app.config['UPLOAD_FOLDER'], path, as_attachment=True)
上面的代码就使得访问/downloads/Path
就可以获得app.config['UPLOAD_FOLDER']
设置的默认本地文件地址中的Path
文件了
flask表单验证
要写一个自定义表单,就先得自定义一个继承于FlaskForm的类,然后在类中进行自定义
class CodeSubmitForm(FlaskForm):
Code = TextAreaField("ChatMsg", validators=[InputRequired()])
submit1 = SubmitField("提交代码")
定义好类后,在视图函数中进行应用
@app.route('/', methods=['GET', 'POST'])
def index(): # 主页面
form = LoginForm()
flag = False
validate = True
dataDescription = ''
if form.validate_on_submit(): # 用户提交了文本就会触发这个
global Data
global res
Data = form.TextInput.data
res = Validate(Data) # 对数据块进行合法性验证
flag = True
if res[0]: # 如果数据格式没问题,那就跳转到config路由,也就是输入代码和造小样例的页面
# dataDescription = "数据格式无误,原数据如下:", [str(Data)], "数据解释如下:", res[1]
return redirect(url_for("config"))
else:
validate = False
dataDescription = "数据格式有误,报错信息如下:", res[1], "原数据为:\n\n", [str(Data)]
return render_template("index.html", Functions=Configs.configFun, form=form, flag=flag,
dataDescription=dataDescription, validate=validate)
理论上讲,验证表单的函数有:
- Form.validate()
- Form.is_submitted()
- Form.validate_on_submit()
按需求使用即可
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 AndrewLee!