当前位置:   article > 正文

Python 之 Flask 框架学习

Python 之 Flask 框架学习

毕业那会使用过这个轻量级的框架,最近再来回看一下,依赖相关的就不多说了,直接从例子开始。下面示例中的 html 模板,千万记得要放到 templates 目录下。

快速启动

hello world

  1. from flask import Flask, jsonify, url_for
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. return '<h1>Hello World!</h1>'
  6. if __name__ == '__main__':
  7. app.run()

路由

既然涉及到web框架,就必然涉及到路由。

动态路由

动态路由就是将变量拼接到路由 url 当中,可以把字段编辑为<variable_name>,这个部分将会作为命名参数传递到你的函数。如果在动态路由中指定了变量的类型,比如 <int:user_id>,则需要按照指定类型进行传值,否则的话也会报错。参数也可以根据类似 request.args.get("id") 进行获取。

  1. from flask import Flask, request
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. return 'Hello World!'
  6. @app.route('/user/<username>')
  7. def show_user_profile(username):
  8. id = request.args.get("id")
  9. return 'User %s, id %s' % (username, id)
  10. @app.route('/users/<int:user_id>')
  11. def show_user_id(user_id):
  12. return 'User id %d' % user_id
  13. if __name__ == '__main__':
  14. app.run(debug=True)

构造 url

Flask 还可以用 url_for() 函数来给指定的函数构造URL,也称为反向路由。它接收函数名作为第一个参数,也接受对应 URL 规则的变量部分的命名参数。未知变量部分会添加到URL末尾作为查询条件。

  1. from flask import Flask, url_for
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. return url_for('article', id=1, name="look") # /article/1?name=look
  6. @app.route('/article/<id>')
  7. def article(id):
  8. return f'id {id} article detail'
  9. if __name__ == '__main__':
  10. app.run()

http方法

HTTP 有许多的不同的构造方法访问 URL 方法。默认情况下,路由只回应 GET 请求,当时通过route() 装饰器传递 methods 参数可以改变这个行为,至于每个 method 对应的行为,这块就不多细说了。

  1. from flask import Flask, url_for, request
  2. app = Flask(__name__)
  3. @app.route('/', methods=['GET', 'POST'])
  4. def index():
  5. if request.method == 'POST':
  6. return "go post method"
  7. elif request.method == 'GET':
  8. return "go get method"
  9. if __name__ == '__main__':
  10. app.run()

 模板

html模板文件一般默认是放在 templates 目录下的,如果没有这个目录的话,可以自己新建一个。

templates/index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>template</title>
  6. </head>
  7. <body>
  8. <h1>hello world!</h1>
  9. </body>
  10. </html>
  1. from flask import Flask, render_template
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. return render_template('index.html')
  6. if __name__ == '__main__':
  7. app.run()

变量替换

而且还可以将内容传递到模板文件进行展示,下面这种也是展示 hello world!只不过我们将静态文件的内容藏起来了,通过后端返回的内容再显示出来,用的是模板语法,两种方法在前端显示的都一样。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>template</title>
  6. </head>
  7. <body>
  8. <h1>{{content}}</h1>
  9. </body>
  10. </html>
  1. from flask import Flask, render_template
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def hello_world():
  5. content = "hello world!"
  6. return render_template('index.html', content=content)
  7. if __name__ == '__main__':
  8. app.run()

当然,也可以将对象实例传递到模板中去。

user_index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>user</title>
  6. </head>
  7. <body>
  8. <h1>hello {{user.name}}</h1>
  9. </body>
  10. </html>

models.py

  1. class User:
  2. def __init__(self, id, name):
  3. self.id = id
  4. self.name = name

main.py

  1. from flask import Flask, render_template
  2. from models import User
  3. app = Flask(__name__)
  4. # 引用模板
  5. @app.route('/')
  6. def hello_world():
  7. content = 'hello world!'
  8. return render_template('index.html', content=content)
  9. @app.route('/user')
  10. def user_index():
  11. user = User(1, 'Looking')
  12. return render_template('user_index.html', user=user)
  13. if __name__ == '__main__':
  14. app.run()

条件语句 

info.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>条件语句</title>
  6. </head>
  7. <body>
  8. {% if user.id == 1 %}
  9. <h1> Hello {{user.name}}</h1>
  10. {% else %}
  11. <h1>There is no user!</h1>
  12. {% endif %}
  13. </body>
  14. </html>
  1. from flask import Flask, render_template
  2. from models import User
  3. app = Flask(__name__)
  4. # 路由
  5. @app.route('/info/<user_id>')
  6. def info_judge(user_id):
  7. user = None
  8. if int(user_id) == 1:
  9. user = User(1, 'Looking')
  10. return render_template('info.html', user=user)
  11. if __name__ == '__main__':
  12. app.run()

循环语句

list.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>循环语句</title>
  6. </head>
  7. <body>
  8. {% for user in users %}
  9. <h4>user_id: {{user.id}}; user_name: {{user.name}}</h4><br>
  10. {% endfor %}
  11. </body>
  12. </html>
  1. from flask import Flask, render_template
  2. from models import User
  3. app = Flask(__name__)
  4. # 路由
  5. @app.route('/list')
  6. def info_judge():
  7. users = []
  8. for i in range(5):
  9. users.append(User(i, f"student{i}"))
  10. return render_template('list.html', users=users)
  11. if __name__ == '__main__':
  12. app.run()

 

模板继承

我们会发现有一些网页的有些部分是不变的,比如说页头页脚等,当跳转相同网页的时候只有中间部分会改变,这就要使用到模板的继承,可以使用 extends 实现对模板文件的继承。

base.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>模板的继承</title>
  6. </head>
  7. <body>
  8. <div>
  9. <H2>Header 欢迎光临!</H2>
  10. </div>
  11. {% block content %}
  12. {% endblock %}
  13. <div>
  14. <H2>Footer 欢迎下次再来!</H2>
  15. </div>
  16. </body>
  17. </html>

page_one.html

  1. {% extends 'base.html'%}
  2. {% block content %}
  3. <h3>{{content}}</h3>
  4. {% endblock %}

 page_two.html

  1. {% extends 'base.html'%}
  2. {% block content %}
  3. <h3>{{content}}</h3>
  4. {% endblock %}

 main.py

  1. from flask import Flask, render_template
  2. app = Flask(__name__)
  3. # 第一页路由
  4. @app.route('/page_one')
  5. def one_page():
  6. content = '这是第一页!'
  7. return render_template('page_one.html', content=content)
  8. # 第二页路由
  9. @app.route('/page_two')
  10. def secend_page():
  11. content = '这是第二页!'
  12. return render_template('page_two.html', content=content)
  13. # 运行
  14. if __name__ == "__main__":
  15. app.run()

消息提示

使用 flash 可以将后台处理的消息提示刷新到页面

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Flask消息提示与异常捕获</title>
  6. </head>
  7. <body>
  8. <h1>Login</h1>
  9. <form action="/login" method="post">
  10. <input type="text" name="username" placeholder="账号"><br />
  11. <input type="password" name="password" placeholder="密码" style="margin-top:10px"><br />
  12. <input type="submit" value="Submit" style="margin-left:50px;margin-top:10px">
  13. </form>
  14. <!--这里获取的是一个数组-->
  15. {{get_flashed_messages()[0]}}
  16. </body>
  17. </html>

main.py 

  1. from flask import Flask, render_template, flash, request
  2. app = Flask(__name__)
  3. # 对flash的内容加密
  4. app.secret_key = '123'
  5. @app.route('/login')
  6. def index():
  7. return render_template("index.html")
  8. # 路由
  9. @app.route('/login', methods=['POST'])
  10. def login():
  11. # 获取表单上传的数据
  12. form = request.form
  13. username = form.get('username')
  14. password = form.get('password')
  15. # 进行判断
  16. if not username:
  17. flash("please enter username")
  18. return render_template("index.html")
  19. if not password:
  20. flash("please enter password")
  21. return render_template("index.html")
  22. if username == "looking" and password == "123456":
  23. flash("login success")
  24. return render_template("index.html")
  25. else:
  26. flash("username and password not match!")
  27. return render_template("index.html")
  28. # 运行
  29. if __name__ == "__main__":
  30. app.run()

异常捕获 

如果用户输入了错误的路径,创建网站的人又没有设置异常捕获及处理,它会出现404;如果处理了的话,那就显示的为处理后的页面。所以,我们的异常处理也就是对返回的 404 页面(或者其他异常)返回我们设置的页面。

404.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Flask异常捕获与处理</title>
  6. </head>
  7. <body>
  8. <h2>抱歉,你访问的页面去火星了......</h2><br />
  9. <h2>请检查你的网址是否输入正确!</h2>
  10. </body>
  11. </html>

user.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <h1>This is user page</h1>
  9. </body>
  10. </html>

 main.py

  1. from flask import Flask, render_template, abort
  2. app = Flask(__name__)
  3. # 异常捕获一
  4. @app.errorhandler(404)
  5. def not_found():
  6. return render_template('404.html'), 404
  7. # 异常捕获二
  8. @app.route('/user/<user_id>')
  9. def user_info(user_id):
  10. if int(user_id) == 1:
  11. return render_template("user.html")
  12. else:
  13. abort(404)
  14. if __name__ == "__main__":
  15. app.run()

如果没有添加针对 404 的错误处理,就是下面这种界面。

403 是 Forbidden

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/383593?site
推荐阅读
相关标签
  

闽ICP备14008679号