Skip to content

Instantly share code, notes, and snippets.

@Leeaandrob
Created September 28, 2023 13:43
Show Gist options
  • Save Leeaandrob/8919ddbd2fda9d781a3de8f579e38c1e to your computer and use it in GitHub Desktop.
Save Leeaandrob/8919ddbd2fda9d781a3de8f579e38c1e to your computer and use it in GitHub Desktop.
app_mongodb.py
import json
from flask import Flask, request, Response
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient("mongodb://localhost:27017")
news_c = client.portal.news
@app.route("/", methods=["GET"])
def root():
return "WORKING"
@app.route("/healthcheck", methods=["GET"])
def healthcheck():
return "WORKING1"
@app.route("/api/v1/news", methods=["POST"])
def create():
body = request.get_json(force=True)
post = body["post"]
news_c.insert_one(post)
return Response(post, status=201, mimetype="application/json")
@app.route("/api/v1/news", methods=["GET"])
def newsList():
posts = [{"name": p.get("name"), "description": p.get("description"), "thumbnail": p.get("thumbnail"), "_id": p.get("_id").__str__()} for p in news_c.find()]
return Response(json.dumps(posts), status=200, mimetype="application/json")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
@Leeaandrob
Copy link
Author

Ficando para aprendizado o:

find by id -> achar um documento usando _id (ObjectID) como argumento
deleteOne -> deletar um documento com base no _id (ObjectId) como argumento
updateOne -> atualizar um documento como base no _id (ObjectId) como argumento

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment