Skip to content

Commit

Permalink
Merge pull request #35 from hack4impact-calpoly/19-Link-Backend-MongoDB
Browse files Browse the repository at this point in the history
19-Link-Backend-MongoDB
  • Loading branch information
oli-lane authored Feb 13, 2024
2 parents 1fa6347 + f84b276 commit 2e72232
Show file tree
Hide file tree
Showing 6 changed files with 218 additions and 23 deletions.
17 changes: 17 additions & 0 deletions backend/api/mongodb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from pymongo.mongo_client import MongoClient
from dotenv import load_dotenv
import os
import certifi

def get_mongo_client():
load_dotenv('../../.env.local') #allows access of env variables from .env
URI = os.getenv('MONGO_URI')

try:
client = MongoClient(URI, tlsCAFile=certifi.where())
client.admin.command('ping') # confirm connection to db
except Exception as e:
print(f"Error connecting to MongoDB: {e}")
client = None

return client
45 changes: 33 additions & 12 deletions backend/api/src/app.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,56 @@
from chalice import Chalice
import mongodb
from dotenv import load_dotenv
from routes.slo_county import slo_county_blueprint


# Load .env file
load_dotenv()

app = Chalice(app_name="api")
app.register_blueprint(slo_county_blueprint)

client = mongodb.get_mongo_client()


@app.route("/")
def index():
return {"hello": "world"}


# The view function above will return {"hello": "world"}
# whenever you make an HTTP GET request to '/'.
#

# dummy endpoint retuns the data of the first user doc in users collection
@app.route("/test")
def test_endpoint():
db = client["test"]
collection = db["users"]
doc = collection.find_one()

if(doc is not None):
return {
"id":str(doc["_id"]),
"email":doc["email"],
"password":doc["password"]
}

# dummy post method
@app.route('/users', methods=['POST'])
def create_user():
try:
# This is the JSON body the user sent in their POST request.
user_as_json = app.current_request.json_body
collection = client["test"]["users"]

collection.insert_one(user_as_json)

except Exception as e:
print(f"Failed to post: {e}")

# Here are a few more examples:
#
# @app.route('/hello/{name}')
# def hello_name(name):
# # '/hello/james' -> {"hello": "james"}
# return {'hello': name}
#
# @app.route('/users', methods=['POST'])
# def create_user():
# # This is the JSON body the user sent in their POST request.
# user_as_json = app.current_request.json_body
# # We'll echo the json body back to the user in a 'user' key.
# return {'user': user_as_json}
#
# See the README documentation for more examples.
#
#
Loading

0 comments on commit 2e72232

Please sign in to comment.