【python】Flask

文章目录

  • [1、Flask 介绍](#1、Flask 介绍)
  • [2、Flask 实现网页版美颜效果](#2、Flask 实现网页版美颜效果)
  • 3、参考

1、Flask 介绍

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

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

一、Flask 应用对象

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

python 复制代码
from flask import Flask
app = Flask(__name__)

二、路由和视图函数

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

python 复制代码
@app.route('/')
def hello_world():
    return 'Hello, World!'

三、请求对象

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

python 复制代码
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 状态码和头信息。

python 复制代码
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:一个签名的字典对象,用于跨请求存储信息。

python 复制代码
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。

python 复制代码
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):生成一个重定向响应。

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

八、URL 生成

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

python 复制代码
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 状态码。

python 复制代码
@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):加载配置。

python 复制代码
class Config:
    DEBUG = True
 
app.config.from_object(Config)

十一、扩展

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

十二、示例完整应用

python 复制代码
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

代码实现

python 复制代码
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)

运行显示结果如下

python 复制代码
 * Running on http://127.0.0.1:5000

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

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

显示添加成功后

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

输入

输出

输入

输出

输入

输出

磨皮效果明显

3、参考

相关推荐
神仙别闹5 分钟前
基于Python+Neo4j实现新冠信息挖掘系统
开发语言·python·neo4j
navyDagger6 分钟前
GAN生成对抗网络数学原理解释并实现MNIST数据集生产(附代码演示)
人工智能·python
没有梦想的咸鱼185-1037-166310 分钟前
【降尺度】ChatGPT+DeepSeek+python+CMIP6数据分析与可视化、降尺度技术与气候变化的区域影响、极端气候分析
python·chatgpt·数据分析
berryyan13 分钟前
傻瓜教程安装Trae IDE用AI撰写第一个AKShare接口脚本
python·trae
灏瀚星空30 分钟前
从基础到实战的量化交易全流程学习:1.3 数学与统计学基础——概率与统计基础 | 基础概念
笔记·python·学习·金融·概率论
Hellohistory35 分钟前
HOTP 算法与实现解析
后端·python
猫猫头有亿点炸35 分钟前
C语言大写转小写2.0
c语言·开发语言
伊织code36 分钟前
cached-property - 类属性缓存装饰器
python·缓存·cache·装饰器·ttl·property·cached-property
A达峰绮44 分钟前
设计一个新能源汽车控制系统开发框架,并提供一个符合ISO 26262标准的模块化设计方案。
大数据·开发语言·经验分享·新能源汽车
明明跟你说过1 小时前
深度学习常见框架:TensorFlow 与 PyTorch 简介与对比
人工智能·pytorch·python·深度学习·自然语言处理·tensorflow