🌞欢迎来到python的世界
🌈博客主页:卿云阁💌欢迎关注🎉点赞👍收藏⭐️留言📝
🌟本文由卿云阁原创!
🌠本阶段属于练气阶段,希望各位仙友顺利完成突破
📆首发时间:🌹2021年4月18日🌹
✉️希望可以和大家一起完成进阶之路!
🙏作者水平很有限,如果发现错误,请留言轰炸哦!万分感谢!
🍈 一、Flask的介绍
Flask是一个使用 Python 编写的轻量级 Web 应用框架。
🍉二. Flask的简单使用
1、创建工程
选择new project创建工程,输入项目名,选择配置好的
虚拟环境2、配置工程目录
在app.py中的代码如下
from flask import Flask, render_template app = Flask(__name__) app.config['SECRET_KEY'] = '1456719640@qq.com' @app.route("/") def root(): """ 主页 :return: Index.html """ return render_template('Index.html') if __name__ == '__main__': app.run(debug=True, host='127.0.0.1', port='5000')
static文件夹用来存放css、JavaScript、image等静态资源文件
templates文件夹,该文件夹用来存放HTML文件
在templates文件夹下新建index.html文件,index.html文件的代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>hello world</h1> </body> </html>
至此,在app.py中运行main函数,进去127.0.0.1::5000即可看到index.html中的内容!
🍊三,Flask 应用程序
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World' if __name__ == '__main__': app.run()
在项目中导入Flask模块是强制性的。
Flask构造函数将当前模块的名称(__name__)作为参数。
Flask类的route()函数是一个装饰器,它告诉应用程序哪个URL应该调用相关的函数。
app.route(rule, options)
rule 参数表示与该函数绑定的URL。options 是要转发给底层Rule对象的参数列表。
在上面的实例中,'/' URL与hello_world()方法绑定。 因此,在浏览器中打开Web服务器的主页时,将呈现此函数的输出。
最后,Flask类的run()方法在本地开发服务器上运行应用程序。
app.run(host, port, debug, options)
🍋四、Flask 路由(Route)
现代Web框架使用路由技术来帮助用户记住应用程序URL。 无需从主页导航即可直接访问所需页面。
Flask中的route()装饰器用于将URL绑定到函数。 例如 -
@app.route('/hello') def hello_world(): return 'hello world'
这里,URL /hello规则绑定到hello_world()函数。 因此,如果用户访问URL : http://localhost:5000/hello ,就会调用hello_world()函数,这个函数中的执行的结果输出将在浏览器中呈现。
应用程序对象的add_url_rule()函数也可用于将URL与函数绑定,如上例所示,使用route()。
Flask 变量规则
可以通过将可变部分添加到规则参数来动态构建URL。 这个变量部分被标记为<variable-name>。 它作为关键字参数传递给规则所关联的函数。
在以下示例中,route()装饰器的规则参数包含附加到URL /hello的<name>变量部分。 因此,如果在浏览器中输入URL: http://localhost:5000/hello/nhooo,那么 ‘nhooo’ 将作为参数提供给hello()函数。
参考如下代码 -
from flask import Flask app = Flask(__name__) @app.route('/hello/<name>') def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run(debug = True)
接下来,打开浏览器并输入URL => http://localhost:5000/hello/nhooo。在浏览器中将看到Hello nhooo
除了默认的字符串变量部分之外,还可以使用以下转换器构造规则 -
在下面的代码中,使用了所有这些构造函数。
from flask import Flask app = Flask(__name__) @app.route('/blog/<int:postID>') def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<float:revNo>') def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run()
从Python Shell运行上述代码。 在浏览器中访问URL => http:// localhost:5000/blog/11。
给定的数字值作为:show_blog()函数的参数。 浏览器显示以下输出 -
Blog Number 11
在浏览器中输入此URL - http://localhost:5000/rev/1.1
revision()函数将浮点数作为参数。 以下结果出现在浏览器窗口中 -
Revision Number 1.100000
Flask的URL规则基于Werkzeug的路由模块。 这确保了形成的URL是唯一的,并且基于Apache制定的先例。
考虑以下脚本中定义的规则 -
from flask import Flask app = Flask(__name__) @app.route('/flask') def hello_flask(): return 'Hello Flask' @app.route('/python/') def hello_python(): return 'Hello Python' if __name__ == '__main__': app.run()
两条规则看起来都很相似,但在第二条规则中,使用了尾部斜线(/)。 因此,它变成了一个规范的URL。 因此,使用/python或/python/返回相同的输出。 但是,在第一条规则的情况下, URL:/flask/会导致404 Not Found页面。
Flask URL构建
url_for()函数对于动态构建特定函数的URL非常有用。 该函数接受函数的名称作为第一个参数,并接受一个或多个关键字参数,每个参数对应于URL的变量部分。
from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>') def user(name): if name =='admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest',guest = name)) if __name__ == '__main__': app.run(debug = True)
User()函数检查收到的参数是否与’admin’匹配。 如果匹配,则使用url_for()将应用程序重定向到hello_admin()函数,否则将该接收的参数作为guest参数传递给hello_guest()函数
Hello Admin
Hello qingyun as Guest
Flask 静态文件
Web应用程序通常需要一个静态文件,例如支持显示网页的JavaScript文件或CSS文件。 通常,可以通过配置Web服务器提供这些服务,但在开发过程中,这些文件将从包中的静态文件夹或模块旁边提供,它将在应用程序的/static上提供。
使用特殊的端点“静态”来为静态文件生成URL。
在以下示例中,index.html中的HTML按钮的OnClick事件调用hello.js中定义的javascript函数,该函数在Flask应用程序的URL => / 中呈现。
index.html
<html> <head> <script type = "text/javascript" src = "{{ url_for('static', filename = 'hello.js') }}" ></script> </head> <body> <input type = "button" onclick = "sayHello()" value = "Say Hello" /> </body> </html>
app.py
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") if __name__ == '__main__': app.run(debug = True)
hello.js
function sayHello() { alert("Hello World") }
Flask 表单处理
我们已经看到,可以在URL规则中指定http方法。URL映射的函数接收到的表单数据可以以字典对象的形式收集,并将其转发给模板以在相应的网页上呈现它。
在以下示例中,URL => / 呈现具有表单的网页( student.html)。填充的数据会提交到触发result()函数的URL => /result 中。
results()函数收集字典对象中request.form中存在的表单数据,并将其发送给 result.html 并显示出来。该模板动态呈现表单数据的HTML表格。
app.py
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def student(): return render_template('student.html') @app.route('/result',methods = ['POST', 'GET']) def result(): if request.method == 'POST': result = request.form return render_template("result.html",result = result) if __name__ == '__main__': app.run(debug = True)
student.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask示例</title> </head> <body> <form action = "http://localhost:5000/result" method = "POST"> <p>姓名 <input type = "text" name = "Name" /></p> <p>物理分数: <input type = "text" name = "Physics" /></p> <p>化学分数: <input type = "text" name = "Chemistry" /></p> <p>数学分数: <input type ="text" name = "Mathematics" /></p> <p><input type = "submit" value = "提交" /></p> </form> </body> </html>
result.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask示例</title> </head> <body> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body> </html>