lincms- flask连接mysql数据库 书写接口
时间: 2024-09-23 20:09:45 浏览: 76
python-flask-mysql.rar
Lincms是一个基于Flask框架的轻量级内容管理系统,如果你想要使用它连接MySQL数据库并书写API接口,通常步骤如下:
1. **安装依赖**:
- 安装Flask:`pip install Flask`
- 安装Flask-SQLAlchemy用于数据库操作:`pip install Flask-SQLAlchemy`
- 如果需要处理SQLAlchemy ORM,安装`sqlalchemy-utils`等辅助库:`pip install sqlalchemy-utils`
2. **配置数据库**:
在`config.py`文件中设置数据库连接信息:
```python
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://username:password@localhost/db_name'
SQLALCHEMY_TRACK_MODIFICATIONS = False
```
3. **模型定义**:
创建数据库模型,例如用户和文章:
```python
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
```
4. **创建路由和API接口**:
使用Flask-Restful库创建API资源(如资源类`ApiResource`):
```python
from flask_restful import Resource, reqparse
class UserList(Resource):
def get(self):
return User.query.all()
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True)
class UserCreate(Resource):
def post(self):
args = parser.parse_args()
new_user = User(name=args['name'])
db.session.add(new_user)
db.session.commit()
return {'status': 'success'}, 201
```
5. **初始化应用和API**:
在`main.py`中,注册资源和启动Flask应用:
```python
from flask import Flask
from myapp import resources as api_resources
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
api = Api(app)
api.add_resource(UserList, '/api/users')
api.add_resource(UserCreate, '/api/users/<string:name>')
```
6. **运行应用**:
`if __name__ == '__main__':
app.run(debug=True)`
阅读全文