flask学习1-基础

打印 上一主题 下一主题

主题 942|帖子 942|积分 2826

在线的省的自己装环境,选择python创建项目: Python: main.py - MarsCode
有2网站学flask:Flask 应用_w3cschool
官网:快速入门 — Flask 文档 (3.1.x)
1.环境安装

  1. # 创建虚拟环境
  2. $ mkdir testflask
  3. $ cd testflask
  4. $ python3 -m venv .venv
  5. # 激活虚拟环境
  6. $ . .venv/bin/activate
  7. # 安装 Flask
  8. pip install Flask
复制代码
2.利用

2.1 创建一个应用

在testflask下创建hello.py
  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route("/")
  4. def hello_world():
  5.     return "<p>Hello, World!</p>"
复制代码
启动项目 --debug 调试模式,不要在生产用
  1. flask --app hello run --host=0.0.0.0
复制代码
访问:https://5dmoq7jq-pou9c8l4-cnsn6oy3hfgo.vcc3.mcprev.cn
或者当地访问:curl http://localhost:5000

当然创建项目有可以选择flask的,我选择的是python,用做训练flask的安装利用。

2.2 路由

  1. # 路由也可以用add_url_rule绑定,访问/ak绑定到了hello_worldd函数,其他的都是可选值
  2. def hello_worldd():
  3.    return "<p>sssfsHello, World!</p>"
  4. app.add_url_rule('/ak', 'hello', hello_worldd)
复制代码
支持转换:
  1. @app.route('/post/<int:post_id>')
  2. @app.route('/path/<path:subpath>')
复制代码
转换器类型:
string(默认)接受任何不带斜杠的文本int接受正整数float接受正浮点值pathlike 但也接受斜杠stringuuid接受 UUID 字符串 2.3 HTTP 方法

@app.route(‘/login’, methods=[‘GET’, ‘POST’])
  1. # url_for使用
  2. def hello_user(name):
  3.    if name =='admin':
  4.       return redirect(url_for('hello_admin'))
  5.    else:
  6.       return redirect(url_for('hello_guest', guest = name))
  7. # 静态文件
  8. url_for('static', filename='style.css')
  9. #  Jinja2 模板引擎
  10. from flask import render_template
  11. @app.route('/hello/')
  12. @app.route('/hello/<name>')
  13. def hello(name=None):
  14.     return render_template('hello.html', person=name)
  15.    
  16. /templates
  17.     /hello.html
  18.    
  19. <!doctype html>
  20. <title>Hello from Flask</title>
  21. {% if person %}
  22.   <h1>Hello {{ person }}!</h1>
  23. {% else %}
  24.   <h1>Hello, World!</h1>
  25. {% endif %}
  26. # ---
复制代码
  1. # 当 Flask 接收到一个请求时,它会创建一个请求上下文(Request Context),并将其绑定到当前线程。
  2. # 在请求处理期间,request 和 session 等对象会被绑定到这个上下文。
  3. # 由于每个线程都有自己的上下文,因此即使在多线程环境中,request 和 session 也能正确地返回当前请求的数据。
  4. with app.test_request_context():
  5.     print(url_for('index'))
  6.     print(url_for('login'))
  7.     print(url_for('login', next='/'))
  8.     print(url_for('profile', username='John Doe'))
  9. # 上下文结束后,request 对象不再可用
  10. try:
  11.     request.path
  12. except RuntimeError:
  13.     print("Request context is no longer available.")
复制代码
2.4 哀求对象

要访问表单数据
  1. @app.route('/login', methods=['POST', 'GET'])
  2. def login():
  3.     error = None
  4.     if request.method == 'POST':
  5.         if valid_login(request.form['username'],
  6.                        request.form['password']):
  7.             return log_the_user_in(request.form['username'])
  8.         else:
  9.             error = 'Invalid username/password'
  10.     # the code below is executed if the request method
  11.     # was GET or the credentials were invalid
  12.     return render_template('login.html', error=error)
复制代码
要访问在 URL () 中提交的参数,您可以利用以下属性:?key=value
  1. searchword = request.args.get('key', '')
复制代码
2.5 文件上传

  1. from flask import request
  2. @app.route('/upload', methods=['GET', 'POST'])
  3. def upload_file():
  4.     if request.method == 'POST':
  5.         f = request.files['the_file']
  6.         f.save('/var/www/uploads/uploaded_file.txt')
  7.     ...
复制代码
2.6 Cookie

  1. # 取
  2. from flask import request
  3. request.cookies.get('username')
  4. # 存
  5. from flask import make_response
  6. resp = make_response(render_template(...))
  7. resp.set_cookie('username', 'the username')
复制代码
2.7 重定向和错误

  1. from flask import abort, redirect, url_for
  2. @app.route('/')
  3. def index():
  4.     return redirect(url_for('login'))
  5. @app.route('/login')
  6. def login():
  7.     abort(401)
  8.     this_is_never_executed()
复制代码
  1. from flask import render_template
  2. # 全局拦截定义错误页面 404
  3. @app.errorhandler(404)
  4. def page_not_found(error):
  5.     return render_template('page_not_found.html'), 404
复制代码
2.8 返回json

如果您从视图返回dict or list ,它将转换为 JSON 响应。 dict 或 list 中的全部数据都必须是 JSON 可序列化。
  1. @app.route("/me")
  2. def get_current_user():
  3.     user = {
  4.         "username": "example_user",
  5.         "theme": "dark",
  6.         "image": "default.jpg"
  7.     }
  8.     return user
  9. @app.route("/users")
  10. def get_all_users():
  11.     # 假设这里有一些逻辑来获取所有用户
  12.     users = [
  13.         {"id": 1, "username": "user1"},
  14.         {"id": 2, "username": "user2"},
  15.         {"id": 3, "username": "user3"},
  16.     ]
  17.     # users = get_all_users()
  18.     # return [user.to_json() for user in users]
  19.     return users
复制代码
2.9 会话

  1. from flask import session
  2. # Set the secret key to some random bytes. Keep this really secret!
  3. app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
  4. @app.route('/')
  5. def index():
  6.     if 'username' in session:
  7.         return f'Logged in as {session["username"]}'
  8.     return 'You are not logged in'
  9. @app.route('/login', methods=['GET', 'POST'])
  10. def login():
  11.     if request.method == 'POST':
  12.         session['username'] = request.form['username']
  13.         return redirect(url_for('index'))
  14.     return '''
  15.         <form method="post">
  16.             <p><input type=text name=username>
  17.             <p><input type=submit value=Login>
  18.         </form>
  19.     '''
  20. @app.route('/logout')
  21. def logout():
  22.     # remove the username from the session if it's there
  23.     session.pop('username', None)
  24.     return redirect(url_for('index'))
复制代码
访问:http://localhost:5000/login
天生密钥
  1. python -c 'import secrets; print(secrets.token_hex())'
复制代码
关于基于 cookie 的会话的说明:Flask 将采用您放入 session 对象并将它们序列化为 cookie。如果您发现一些 值不会在哀求之间保留,Cookie 确实已启用,并且您 没有收到明确的错误消息,请查抄页面中 cookie 的大小 响应与 Web 浏览器支持的大小举行比较。
2.10 日记

  1. app.logger.debug('A value for debugging')
  2. app.logger.warning('A warning occurred (%d apples)', 42)
  3. app.logger.error('An error occurred')
复制代码
2.11 WSGI 中心件中的挂钩¶

要将 WSGI 中心件添加到您的 Flask 应用程序,请包装应用程序的 attribute。例如,要应用 Werkzeug 的中心件来运行 Nginx 背面:wsgi_app
  1. server {
  2.     listen 443 ssl;
  3.     server_name example.com;
  4.     ssl_certificate /path/to/cert.pem;
  5.     ssl_certificate_key /path/to/key.pem;
  6.     location / {
  7.         proxy_pass http://127.0.0.1:5000;  # 将请求转发到 Flask 应用
  8.         proxy_set_header Host $host;
  9.         proxy_set_header X-Real-IP $remote_addr;
  10.         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  11.         proxy_set_header X-Forwarded-Proto $scheme;
  12.     }
  13. }
复制代码
  1. from flask import Flask
  2. from werkzeug.middleware.proxy_fix import ProxyFix
  3. app = Flask(__name__)
  4. @app.route('/')
  5. def index():
  6.     return "Hello, World!"
  7. # 包装 wsgi_app,修复请求头
  8. app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1, x_prefix=1)
  9. if __name__ == '__main__':
  10.     app.run()
复制代码


  • x_for=1:修复 X-Forwarded-For 头,获取客户端的真实 IP 地址。
  • x_proto=1:修复 X-Forwarded-Proto 头,确保 Flask 应用知道哀求是通过 HTTPS 发起的
2.12 利用 Flask 扩展

查找扩展

Flask 扩展通常定名为 “Flask-Foo” 或 “Foo-Flask”。您可以 在 PyPI 中搜索标记为 Framework :: Flask 的包。
利用扩展

请查阅每个扩展的文档,了解安装、设置、 和利用说明。通常,扩展会拉取自己的 设置 from ``和 are 在初始化期间通报应用程序实例。例如 一个名为 “Flask-Foo” 的扩展可以像如许利用:
  1. from flask_foo import Foo
  2. foo = Foo()
  3. app = Flask(__name__)
  4. app.config.update(
  5.     FOO_BAR='baz',
  6.     FOO_SPAM='eggs',
  7. )
  8. foo.init_app(app)
复制代码
构建扩展

固然 PyPI 包罗许多 Flask 扩展,但您大概找不到 适合您需求的扩展。如果是这种环境,您可以创建 您自己的,并将其发布供其他人利用。阅读 Flask 扩展开辟 以开辟您自己的 Flask 扩展。
2.13 部署到 Web 服务器

WSGI服务器有内置的HTTP服务器。但是,专用的HTTP服务器大概更安全、更高效或功能更强大。将HTTP服务器放在WSGI服务器的前面称为“反向代理”。


  • Tell Flask it is Behind a Proxy
  • nginx
  • Apache httpd
2.14 flask、wsgi服务器、wsgi中心件、nginx的关系

Flask



  • Flask 是一个轻量级的 WSGI Web 框架,用于开辟 Web 应用。
  • Flask 应用本质上是一个 WSGI 应用,可以通过任何符合 WSGI 标准的服务器运行。
WSGI 服务器(如 Gunicorn 或 uWSGI)



  • WSGI 服务器是运行 Flask 应用的后端服务,负责处理 Python 应用的哀求和响应。
  • 常用的 WSGI 服务器包括 Gunicorn 和 uWSGI:

    • Gunicorn:轻量级、易于设置,适合快速部署。
    • uWSGI:功能丰富,支持多进程、多线程和异步模式,适合高性能需求。

Nginx



  • Nginx 是一个高性能的 Web 服务器和反向代理服务器。
  • 在部署 Flask 应用时,Nginx 通常作为反向代理服务器,将客户端的 HTTP 哀求转发到后端的 WSGI 服务器(如 Gunicorn 或 uWSGI),并处理静态文件、SSL/TLS 终止等
WSGI 中心件


  • WSGI 中心件是位于 WSGI 服务器和 Flask 应用之间的可调用对象,用于在不修改应用代码的环境下添加功能
部署流程

步骤 1:运行 Flask 应用



  • 利用 WSGI 服务器(如 Gunicorn 或 uWSGI)启动 Flask 应用。
  • 示例:利用 Gunicorn 启动 Flask 应用:
    bash复制
    1. gunicorn -w 4 -b 0.0.0.0:8000 app:app
    复制代码
    此中 -w 4 表示启动 4 个工作进程,-b 0.0.0.0:8000 表示绑定到 8000 端口。
步骤 2:设置 Nginx 作为反向代理



  • Nginx 设置文件示例:
    nginx复制
    1. server {
    2.     listen 80;
    3.     server_name yourdomain.com;
    4.     location / {
    5.         proxy_pass http://127.0.0.1:8000;
    6.         proxy_set_header Host $host;
    7.         proxy_set_header X-Real-IP $remote_addr;
    8.         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    9.         proxy_set_header X-Forwarded-Proto $scheme;
    10.     }
    11.     location /static {
    12.         alias /path/to/your/static/files;
    13.     }
    14. }
    复制代码

    • proxy_pass 将哀求转发到后端的 WSGI 服务器。
    • location /static 用于处理静态文件。

步骤 3:启动和管理服务



  • 启动 Nginx 并确保其设置生效:
    bash复制
    1. sudo systemctl restart nginx
    复制代码
  • 确保 WSGI 服务器(如 Gunicorn 或 uWSGI)在后台持续运行。
WSGI 中心件的作用



  • WSGI 中心件是位于 WSGI 服务器和 Flask 应用之间的可调用对象,用于在不修改应用代码的环境下添加功能。
  • 例如,可以利用 ProxyFix 中心件修复在 Nginx 反向代理环境下大概出现的哀求头题目:
    1. from werkzeug.middleware.proxy_fix import ProxyFix
    2. app.wsgi_app = ProxyFix(app.wsgi_app)
    复制代码
    如允许以确保 Flask 应用能够精确处理通过 Nginx 转发的哀求。
总结



  • Flask 是 WSGI 应用,负责处理业务逻辑。
  • WSGI 服务器(如 Gunicorn 或 uWSGI)运行 Flask 应用,处理 Python 哀求。
  • Nginx 作为反向代理,处理静态文件、SSL/TLS 终止,并将动态哀求转发到 WSGI 服务器。
  • WSGI 中心件 用于在 WSGI 服务器和 Flask 应用之间添加额外功能,如哀求头修复。
通过这种架构,可以实现高性能、高可用的 Flask 应用部署。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

小小小幸运

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表