文章目录

  • 1、Flask 介绍
  • 2、Flask 实现网页版美颜效果
  • 3、参考
  • 4、附录——Django、Flask、FastAPI
  • 1、Flask 介绍

    Flask 是一个用 Python 编写的轻量级 Web 应用框架。它设计简单且易于扩展,非常适合小型项目到大型应用的开发。

    以下是一些 Flask 库中常用的函数和组件:

    一、Flask 应用对象

    Flask(__name__):创建一个 Flask 应用实例。

    from flask import Flask
    app = Flask(__name__)
    

    二、路由和视图函数

    @app.route(path, methods=['GET', 'POST']):装饰器,用于将 URL 路径绑定到视图函数。

    @app.route('/')
    def hello_world():
        return 'Hello, World!'
    

    三、请求对象

    request:包含有关客户端请求的信息,比如请求参数、表单数据、HTTP 头等。

    from flask import request
     
    @app.route('/greet', methods=['POST'])
    def greet():
        name = request.form['name']
        return f'Hello, {name}!'
    

    四、响应对象

    make_response(response, *args, **kwargs):创建一个响应对象,可以附加 HTTP 状态码和头信息。

    from flask import make_response
     
    @app.route('/custom_response')
    def custom_response():
        response = make_response("This is a custom response")
        response.headers['X-Special-Header'] = 'Some value'
        return response
    

    五、会话管理

    session:一个签名的字典对象,用于跨请求存储信息。

    from flask import session
     
    @app.route('/login', methods=['POST'])
    def login():
        session['username'] = request.form['username']
        return 'Logged in successfully!'
     
    @app.route('/logout')
    def logout():
        session.pop('username', None)
        return 'You were logged out'
    

    六、模板渲染

    render_template(template_name_or_list, **context):渲染一个模板,并返回生成的 HTML。

    from flask import render_template
     
    @app.route('/template')
    def template_example():
        return render_template('example.html', name='John Doe')
    

    七、重定向

    redirect(location, code=302, response=None):生成一个重定向响应。

    from flask import redirect
     
    @app.route('/redirect_me')
    def redirect_example():
        return redirect('http://www.example.com')
    

    八、URL 生成

    url_for(endpoint, **values):生成 URL,对于动态 URL 特别有用。

    from flask import url_for
     
    @app.route('/url_for_example')
    def url_for_example():
        return f'The URL for the index is {url_for("index")}'
    

    九、异常处理

    @app.errorhandler(code_or_exception):装饰器,用于处理特定异常或 HTTP 状态码。

    @app.errorhandler(404)
    def page_not_found(e):
        return 'Sorry, the page you are looking for does not exist.', 404
    

    十、配置

    app.config.from_object(config_object) 或 app.config.update(dictionary):加载配置。

    class Config:
        DEBUG = True
     
    app.config.from_object(Config)
    

    十一、扩展

    Flask 还支持许多扩展,用于数据库交互(如 Flask-SQLAlchemy)、用户认证(如 Flask-Login)、文件上传(如 Flask-WTF)等。

    十二、示例完整应用

    from flask import Flask, request, render_template, redirect, url_for, session, make_response
     
    app = Flask(__name__)
    app.secret_key = 'your_secret_key'  # 用于会话管理
     
    @app.route('/')
    def index():
        return 'Welcome to Flask!'
     
    @app.route('/greet', methods=['POST'])
    def greet():
        name = request.form['name']
        return f'Hello, {name}!'
     
    @app.route('/login', methods=['POST'])
    def login():
        session['username'] = request.form['username']
        return redirect(url_for('profile'))
     
    @app.route('/logout')
    def logout():
        session.pop('username', None)
        return redirect(url_for('index'))
     
    @app.route('/profile')
    def profile():
        username = session.get('username', 'Guest')
        return f'Profile page for {username}'
     
    @app.route('/custom_response')
    def custom_response():
        response = make_response("This is a custom response")
        response.headers['X-Special-Header'] = 'Some value'
        return response
     
    if __name__ == '__main__':
        app.run(debug=True)
    

    这些只是 Flask 的一些核心功能,Flask 还有更多高级特性和扩展,可以根据需求进行探索和使用。

    2、Flask 实现网页版美颜效果

    初始化设计好的网页界面 index.html

    代码实现

    import os
    from flask import Flask
    from flask import request
    from flask import render_template
    from datetime import timedelta
    import cv2
    
    value = 20
    
    def Beauty(path, filename):
        img = cv2.imread(path)
        img_res = cv2.bilateralFilter(img, value, value * 2, value / 2)
        filename = './out/{}'.format(filename)
        cv2.imwrite(filename, img_res)
        # cv2.imshow('img', img_res)
        # cv2.waitKey(0)
        return filename
    
    app = Flask(__name__)
    # # 设置静态文件缓存过期时间
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
    ALLOWED_EXTENSIONS = set(['bmp', 'png', 'jpg', 'jpeg'])
    UPLOAD_FOLDER = r'./static/'
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        return render_template('index.html')
    
    @app.route('/beauty', methods=['GET', 'POST'])
    def beauty():
        if request.method == 'POST':
            file = request.files['image']
            print(file)
            if file and allowed_file(file.filename):
                path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
                file.save(path)
                output = Beauty(path, file.filename)
                print(output)
                return render_template('index.html', output = output)
            else:
                return render_template('index.html', alert = '文件类型必须是图片!')
        else:
            return render_template('index.html')
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    运行显示结果如下

     * Running on http://127.0.0.1:5000
    

    我们在浏览器中打开此链接

    选择文件,点击上传,默认的文件夹路径配置为 UPLOAD_FOLDER = r'./static/',可以将图片提前放到配置的文件夹目录下

    显示添加成功后

    可以在保存的目录下查看结果,filename = './out/{}'.format(filename),可以看到保存在的是在 out 文件夹下

    输入

    输出

    输入

    输出

    输入

    输出

    磨皮效果明显

    3、参考

  • 十来行代码,用Python做一个迷你美图秀秀

  • 代码目录:
    链接: https://pan.baidu.com/s/11ALwPkknz61V5ugXLznThQ?pwd=596q
    提取码: 596q

  • 4、附录——Django、Flask、FastAPI

    Python 三大框架 Django, Flask, FastAPI 到底哪个最强!

    Django、Flask 和 FastAPI 都是 Python 编程语言中非常受欢迎的 Web 框架,它们各自具有独特的特点和适用场景。

    Django:适合需要全面功能和内置支持的大型应用,提供了一整套工具和约定,适合快速开发和部署。

    Flask:适合需要高度自定义和灵活性的项目,轻量且易于上手,但需要开发者自行选择和配置工具。

    FastAPI:适合构建高性能、高并发的API服务,具备现代异步编程支持和自动文档生成。

    作者:bryant_meng

    物联沃分享整理
    物联沃-IOTWORD物联网 » 【python】Flask

    发表回复