You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.1 KiB
52 lines
1.1 KiB
from flask import Flask
|
|
from pymongo import MongoClient
|
|
|
|
app = Flask(__name__)
|
|
client = MongoClient("mongodb://localhost:27019/")
|
|
db = client["back"]
|
|
collection = db["users"]
|
|
|
|
|
|
# 测试
|
|
@app.route("/")
|
|
def hello():
|
|
return "Hello World!"
|
|
|
|
|
|
# 新增用户
|
|
@app.route("/insert")
|
|
def insert_data():
|
|
user = {"name": "John Doe", "age": 25, "city": "New York"}
|
|
collection.insert_one(user)
|
|
return "Data inserted successfully!"
|
|
|
|
|
|
# 查询用户
|
|
@app.route("/query")
|
|
def query_data():
|
|
users = collection.find()
|
|
result = ""
|
|
for user in users:
|
|
result += f"Name: {user['name']}, Age: {user['age']}, City: {user['city']}<br>"
|
|
return result
|
|
|
|
|
|
# 更新用户
|
|
@app.route("/update")
|
|
def update_data():
|
|
query = {"name": "John Doe"}
|
|
new_data = {"$set": {"age": 30, "city": "San Francisco"}}
|
|
collection.update_one(query, new_data)
|
|
return "Data updated successfully!"
|
|
|
|
|
|
# 删除用户
|
|
@app.route("/delete")
|
|
def delete_data():
|
|
query = {"name": "John Doe"}
|
|
collection.delete_one(query)
|
|
return "Data deleted successfully!"
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run()
|
|
|