当前位置:网站首页>Flask----应用案例
Flask----应用案例
2022-06-27 19:04:00 【laufing】
需求
- 创建app, 并使用配置文件配置mysql
- 创建一个apps目录, 内部创建一个users目录,users目录下创建user蓝图,并注册到app
- 为user蓝图配置路由;原生路由/info 返回info.html; restful api 路由/user/mobile 返回json数据。
- 为app配置跨域(使用flask_cors)
案例代码
- app.py
from flask import Flask
from flask import request, session, current_app, g
from flask_restful import Api, Resource
from flask_sqlalchemy import SQLAlchemy
from apps.users.user_app import user_app
from apps.users import models
from flask_cors import CORS
app = Flask(__name__)
# 配置app
app.config.from_pyfile("settings.py")
# 初始化数据库连接
db = SQLAlchemy(app)
# api接口, 蓝图中有自己的api对象
api = Api(app)
# 注册蓝图, 蓝图即扩展的应用,内部的路由也会放入url_map
app.register_blueprint(user_app)
if __name__ == "__main__":
print("xxx:", app.url_map)
# 配置跨域, 已测试
CORS(app, supports_credentials=True,
origins=["http://localhost:8080",],
methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["x-requested-with", 'content-type', 'authorization', "author"],
expose_headers="*")
app.run(host="localhost", port=5000, debug=True)
- user_app.py
from flask import request, render_template
from flask import Blueprint
from flask import jsonify
user_app = Blueprint("user", __name__,
static_folder="static/users", # 暂时没有办法访问静态文件
template_folder="templates/users")
@user_app.route("/info", methods=["GET", "POST"], endpoint="userInfo")
def userInfo():
if request.method == "GET":
return render_template("users/info.html")
else:
return "没有页面"
from flask_restful import Api, Resource
# 为蓝图实例化api对象,添加restful api
api = Api(user_app)
class UserResource(Resource):
def get(self):
res = jsonify({
"code": 200,
"msg": "1733532..."
})
return res
api.add_resource(UserResource, "/user/mobile")
- manage.py
from app import app, db
from app import user_app
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)
if __name__ == "__main__":
manager.run()
- settings.py
# 使用pymysql
import pymysql
pymysql.install_as_MySQLdb()
# 配置数据库, 有如上代码,就不能mysql+pymysql
# SQLALCHEMY_DATABASE_URI = "mysql+pymysql://lauf:[email protected]:3306/"
SQLALCHEMY_DATABASE_URI = "mysql://lauf:[email protected]:3306/flask_625"
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
- models.py
边栏推荐
- KDD 2022 | 图“预训练、提示、微调”范式下的图神经网络泛化框架
- 基于微信小程序的高校毕业论文管理系统#毕业设计
- Galaxy Kirin system LAN file sharing tutorial
- SQL Server for循环用法
- Industry case | see the operation of bank digital transformation from the king of retail
- SQL server for circular usage
- 分享|智慧环保-生态文明信息化解决方案(附PDF)
- Share an experience of self positioning + problem solving
- Serveur mandataire SQUID
- SQL audit platform permission module introduction and account creation tutorial
猜你喜欢

Massive data attended the Lanzhou opengauss meetup (ECOLOGICAL NATIONAL trip) activity, enabling users to upgrade their applications with enterprise level databases

一套系统,减轻人流集中地10倍的通行压力
![[STL programming] [common competition] [Part 1]](/img/ce/4d489e62d6c8d16134262b65d4b0d9.png)
[STL programming] [common competition] [Part 1]

What is a low code development platform? Why is it so hot now?

Use the storcli tool to configure raid. Just collect this article

灵活的IP网络测试工具——— X-Launch

基于微信小程序的高校毕业论文管理系统#毕业设计

Openharmony hisysevent dotting and calling practice of # Summer Challenge (L2)

GFS distributed file system

SQL Server for循环用法
随机推荐
基于微信小程序的高校党员之家服务管理系统系统小程序#毕业设计,党员,积极分子,学习,打卡,论坛
MySQL performance optimization index function, hidden, prefix, hash index usage (2)
[STL programming] [common competition] [Part 3]
白嫖红队goby&POC,叫你如何白嫖?
Implementation string mystring
Navicat premium connection problem --- host 'XXXXXXXX' is not allowed to connect to this MySQL server
MYSQL 性能优化 index 函数,隐藏,前缀,hash 索引 使用方法(2)
Runmaide medical opened the offering: without the participation of cornerstone investors, the amount of loss doubled
CocosCreator播放音频并同步进度
Cloud native Security Guide: learn kubernetes attack and defense from scratch
Character interception triplets of data warehouse: substrb, substr, substring
eval函数,全局、本地变量
College graduation thesis management system based on wechat applet graduation design
"Good voice" has been singing for 10 years. How can the Chinese language in the starry sky sing well in HKEx?
Recommended practice sharing of Zhilian recruitment based on Nebula graph
划重点!国产电脑上安装字体小技巧
Love number experiment | Issue 7 - Financial Crisis Analysis Based on random forest
The meta universe virtual digital human is closer to us | Sinovel interaction
1027 Colors in Mars
分享一次自己定位 + 解决问题的经历