Flask入门到实战:3天搭建AI网站(附完整代码)!
Flask入门到实战3天搭建AI网站附完整代码前言上一篇《3个让Python代码提速10倍》获得了很多朋友的认可阅读量突破500感谢大家的支持有读者私信问我「学了Python基础怎么做成网站」今天用3天时间从零开始教你用Flask搭建一个AI抠图网站。不需要前端基础复制代码就能跑。Day 1Flask基础30分钟1.1 安装Flaskpip install flask1.2 第一个Hello World创建文件 app.pyfrom flask import Flaskapp Flask(name)app.route(‘/’)def hello():return ‘Hello, Flask!’ifname ‘main’:app.run(debugTrue)运行python app.py打开浏览器访问控制台打印的地址看到「Hello, Flask!」就成功了。1.3 路由和参数app.route(‘/user/’)def user(name):return f’你好, {name}!’访问 /user/张三显示「你好, 张三!」Day 2模板和文件上传1小时2.1 HTML模板创建文件夹 templates里面创建 index.htmlAI抠图上传图片自动抠图上传2.2 渲染模板from flask import render_templateapp.route(‘/’)def index():return render_template(‘index.html’)2.3 接收文件上传from flask import requestimport osUPLOAD_FOLDER ‘uploads’os.makedirs(UPLOAD_FOLDER, exist_okTrue)app.route(‘/upload’, methods[‘POST’])def upload():if ‘image’ not in request.files:return ‘没有选择文件’file request.files[image] if file.filename : return 文件名为空 filepath os.path.join(UPLOAD_FOLDER, file.filename) file.save(filepath) return f文件已保存: {filepath}Day 3接入AI抠图API2小时3.1 申请百度API访问百度智能云官网注册账号实名认证创建应用获取API Key和Secret Key开通「图像分割」服务3.2 调用API抠图import requestsimport base64def get_access_token(api_key, secret_key):url ‘https://aip.baidubce.com/oauth/2.0/token’params {‘grant_type’: ‘client_credentials’,‘client_id’: api_key,‘client_secret’: secret_key}response requests.post(url, paramsparams)return response.json()[‘access_token’]def remove_bg(image_path, access_token):url ‘https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg’with open(image_path, rb) as f: img_base64 base64.b64encode(f.read()).decode() params {image: img_base64} headers {Content-Type: application/x-www-form-urlencoded} response requests.post( url ?access_token access_token, dataparams, headersheaders ) result response.json() if foreground in result: img_data base64.b64decode(result[foreground]) output_path image_path.replace(., _nobg.) with open(output_path, wb) as f: f.write(img_data) return output_path return None3.3 完整的上传抠图接口app.route(‘/remove-bg’, methods[‘POST’])def remove_bg_api():if ‘image’ not in request.files:return {‘error’: ‘没有选择文件’}, 400file request.files[image] filepath os.path.join(UPLOAD_FOLDER, file.filename) file.save(filepath) access_token get_access_token(你的API_KEY, 你的SECRET_KEY) result_path remove_bg(filepath, access_token) if result_path: return { success: True, message: 抠图成功, output: result_path } else: return { success: False, message: 抠图失败 }, 500部署上线4.1 本地测试python app.py访问本地地址上传图片测试。4.2 服务器部署推荐阿里云ECS或腾讯云轻量服务器pip install flask requests gunicorngunicorn -w 4 -b 0.0.0.0:8000 app:app4.3 配置Nginx反向代理server {listen 80;server_name your_domain.com;location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }}完整代码GitHub仓库github.com/qy-jscai/flask-ai-remove-bg包含完整app.pyHTML模板部署脚本README教程总结3天学习内容Day 1Flask基础Hello WorldDay 2模板和文件上传Day 3接入AI API完成抠图功能不需要前端基础复制代码就能跑。有问题欢迎在评论区交流往期推荐《3个让Python代码提速10倍的小技巧》《用Python 3行代码做AI抠图》《0成本搭建AI抠图网站》关注我持续分享Python实战技巧