python 公司管理系统动态增删改查代码
时间: 2024-09-21 22:08:24 浏览: 62
Python 的公司管理系统通常涉及到数据库操作、用户管理、权限控制等功能,这里提供一个简单的例子,我们将使用 Flask 框架和 SQLAlchemy 数据库 ORM 来展示基本的 CRUD (创建(Create), 更新(Update), 删除(Delete) 和查询(Read) 功能。
首先,确保已安装 Flask-SQLAlchemy 和 Flask:
```bash
pip install flask flask-sqlalchemy
```
然后,创建一个基础模型 `Company`:
```python
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Company(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
address = db.Column(db.Text)
def __repr__(self):
return f"Company(id={self.id}, name={self.name})"
# 初始化数据库连接
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///companies.db'
db.create_all()
```
接下来,设置 Flask 应用和路由:
```python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/companies', methods=['GET'])
def get_companies():
companies = Company.query.all()
return jsonify([company.to_dict() for company in companies])
@app.route('/api/companies/<int:company_id>', methods=['GET'])
def get_company(company_id):
company = Company.query.get_or_404(company_id)
return jsonify(company.to_dict())
@app.route('/api/companies', methods=['POST'])
def create_company():
data = request.get_json()
new_company = Company(name=data['name'], address=data['address'])
db.session.add(new_company)
db.session.commit()
return jsonify(new_company.to_dict()), 201
@app.route('/api/companies/<int:company_id>', methods=['PUT'])
def update_company(company_id):
data = request.get_json()
company = Company.query.get_or_404(company_id)
company.name = data['name']
company.address = data['address']
db.session.commit()
return jsonify(company.to_dict())
@app.route('/api/companies/<int:company_id>', methods=['DELETE'])
def delete_company(company_id):
company = Company.query.get_or_404(company_id)
db.session.delete(company)
db.session.commit()
return '', 204
if __name__ == '__main__':
app.run(debug=True)
```
现在你可以通过 HTTP 请求来操作公司的数据:
- GET `/api/companies`:获取所有公司信息
- GET `/api/companies/1`:获取指定ID的公司信息
- POST `/api/companies`:创建新公司
- PUT `/api/companies/1`:更新公司信息
- DELETE `/api/companies/1`:删除公司
阅读全文