From ee24ff427c8f9df5904dc519b97bcea5156c9406 Mon Sep 17 00:00:00 2001 From: bloombar Date: Tue, 11 Oct 2022 22:53:03 -0400 Subject: [PATCH] mongodb fix --- README.md | 13 +++--- app.py | 46 +++++++------------ credentials.py | 25 ---------- instructions.md | 45 ------------------ ux-design/flask-example-app-wireframes.drawio | 1 - ux-design/flask-example-app-wireframes.svg | 3 -- 6 files changed, 24 insertions(+), 109 deletions(-) delete mode 100644 credentials.py delete mode 100644 instructions.md delete mode 100644 ux-design/flask-example-app-wireframes.drawio delete mode 100644 ux-design/flask-example-app-wireframes.svg diff --git a/README.md b/README.md index 89af4cd..3c3dd36 100644 --- a/README.md +++ b/README.md @@ -27,10 +27,8 @@ A file named `.env` is necessary to run the application. This file contains sens An example file named `env.example` is given. Copy this into a file named `.env` and edit the values to match your database. If following the instructions and using Docker to run the database, the values should be: ``` -MONGO_HOST=localhost:27017 -MONGO_USER=admin -MONGO_PASSWORD=secret -MONGO_DBNAME=web-app-example-db +MONGO_DBNAME=example +MONGO_URI="mongodb://admin:secret@localhost:27017/example?authSource=admin&retryWrites=true&w=majority" ``` The other values can be left alone. @@ -71,5 +69,8 @@ pip3 install -r requirements.txt ### Run the app -1. start flask with `flask run` - this will output an address at which the app is running locally, e.g. https://127.0.0.1:5000. Visit that address in a web browser. -1. in some cases, the command `flask` will not be found when attempting `flask run`... you can alternatively launch it with `python3 -m flask run --host=0.0.0.0 --port=10000`. +- define two environment variables from the command line: + - on Mac, use the commands: `export FLASK_APP=app.py` and `export FLASK_ENV=development`. + - on Windows, use `set FLASK_APP=app.py` and `set FLASK_ENV=development`. +- start flask with `flask run` - this will output an address at which the app is running locally, e.g. https://127.0.0.1:5000. Visit that address in a web browser. +- in some cases, the command `flask` will not be found when attempting `flask run`... you can alternatively launch it with `python3 -m flask run --host=0.0.0.0 --port=10000`. diff --git a/app.py b/app.py index 0c56600..0d65d03 100644 --- a/app.py +++ b/app.py @@ -1,32 +1,38 @@ #!/usr/bin/env python3 from flask import Flask, render_template, request, redirect, url_for, make_response -from markupsafe import escape +from dotenv import dotenv_values + import pymongo import datetime from bson.objectid import ObjectId -import os -import subprocess +import sys # instantiate the app app = Flask(__name__) # load credentials and configuration options from .env file # if you do not yet have a file named .env, make one based on the template in env.example -import credentials -config = credentials.get() +config = dotenv_values(".env") # turn on debugging if in development mode if config['FLASK_ENV'] == 'development': # turn on debugging, if in development app.debug = True # debug mnode -# make one persistent connection to the database -connection = pymongo.MongoClient(config['MONGO_HOST'], 27017, - username=config['MONGO_USER'], - password=config['MONGO_PASSWORD'], - authSource=config['MONGO_DBNAME']) -db = connection[config['MONGO_DBNAME']] # store a reference to the database + +# connect to the database +cxn = pymongo.MongoClient(config['MONGO_URI'], serverSelectionTimeoutMS=5000) +try: + # verify the connection works by pinging the database + cxn.admin.command('ping') # The ping command is cheap and does not require auth. + db = cxn[config['MONGO_DBNAME']] # store a reference to the database + print(' *', 'Connected to MongoDB!') # if we get here, the connection worked! +except Exception as e: + # the ping command failed, so the connection is not available. + # render_template('error.html', error=e) # render the edit template + print(' *', "Failed to connect to MongoDB at", config['MONGO_URI']) + print('Database connection error:', e) # debug # set up the routes @@ -121,24 +127,6 @@ def delete(mongoid): db.exampleapp.delete_one({"_id": ObjectId(mongoid)}) return redirect(url_for('read')) # tell the web browser to make a request for the /read route. -@app.route('/webhook', methods=['POST']) -def webhook(): - """ - GitHub can be configured such that each time a push is made to a repository, GitHub will make a request to a particular web URL... this is called a webhook. - This function is set up such that if the /webhook route is requested, Python will execute a git pull command from the command line to update this app's codebase. - You will need to configure your own repository to have a webhook that requests this route in GitHub's settings. - Note that this webhook does do any verification that the request is coming from GitHub... this should be added in a production environment. - """ - # run a git pull command - process = subprocess.Popen(["git", "pull"], stdout=subprocess.PIPE) - pull_output = process.communicate()[0] - # pull_output = str(pull_output).strip() # remove whitespace - process = subprocess.Popen(["chmod", "a+x", "flask.cgi"], stdout=subprocess.PIPE) - chmod_output = process.communicate()[0] - # send a success response - response = make_response('output: {}'.format(pull_output), 200) - response.mimetype = "text/plain" - return response @app.errorhandler(Exception) def handle_error(e): diff --git a/credentials.py b/credentials.py deleted file mode 100644 index 1831055..0000000 --- a/credentials.py +++ /dev/null @@ -1,25 +0,0 @@ -import os - -# load the credentials from the .env file -def get(): - """ - Load the configuration settings from the .env file. - :returns: a dictionary of credentials and configuration settings - """ - # open the .env configuration file - APP_ROOT = os.path.join(os.path.dirname(__file__)) # refers to application_top - dotenv_path = os.path.join(APP_ROOT, '.env') - # loop through each line and add to dictionary - f = open(dotenv_path, encoding='utf_8') - config = {} # empty dictionary - for line in f: - # split by = - line=line.strip() # remove line break - # remove any comment from the line - if '#' in line: - line = line[:line.find('#')] - setting = line.split('=') # split key and value apart - if len(setting) == 2: - key, value = setting - config[key] = value - return config diff --git a/instructions.md b/instructions.md deleted file mode 100644 index 82d0c1e..0000000 --- a/instructions.md +++ /dev/null @@ -1,45 +0,0 @@ -# Flask-MongoDB Web App - -In this assignment you will create a web app that relies upon a MongoDB database. - -## Example app - -An example web app has been included in this repository for your reference - see [how to setup and run that example web app](./setup.md). - -## Getting started - -It is **highly** recommended that you start by [setting up the example app](./setup.md). Get this example up-and-running before modifying the code in any way. - -To speed up development, you may want to have two copies of the example app running: one locally on your own computer and one on the **i6** web server. The example app setup instructions contain some guidance for setting up both remote and local instances of the app. - -## Requirements - -### Basic requirements - -You will create a web app that must... - -1. be written in Python, using [flask](https://flask.palletsprojects.com/en/1.1.x/) and [pymongo](https://pymongo.readthedocs.io/en/stable/index.html). -1. be deployed (i.e. published) to NYU CS Department's web server and MongoDB server, **i6**.cims.nyu.edu and **class-mongodb**.cims.nyu.edu, respectively. -1. allow the user to interact with data from the database in an intuitive and effortless manner, not requiring the user to understand any technical details of computer programming or databases. -1. involve each of the basic operations of **CRUD** on documents in the database, triggered by user interactions. -1. be well-designed with a clear consistency of design from one web page to the next. -1. represent an amount of effort appropriate for an assignment of this duration and number of developers. -1. do something useful and/or interesting. - -### Documentation requirements - -Delete the contents of the `README.md` file and replace with a well-written, nicely-formatted Markdown document describing your app. Include at least the following: - -- the title of your app -- a simple description of your app -- a link to the deployed copy of your app -- the full names, NYU Net IDs, and links to GitHub accounts of any collaborators with whom you worked on this app - -## Submit your work - -Use Visual Studio Code to perform git `stage`, `commit` and `push` actions to submit. These actions are all available as menu items in Visual Studio Code's Source Control panel. - -1. Type a short note about what you have done to the files in the `Message` area, and then type `Command-Enter` (Mac) or `Control-Enter` (Windows) to perform git `stage` and `commit` actions. -1. Click the `...` icon next to the words, "Source Control" and select "Push" to perform the git `push` action. This will upload your work to your repository on GitHub.com. - -![Pushing work in Visual Studio Code](./images/vscode_stage_commit_push.png) diff --git a/ux-design/flask-example-app-wireframes.drawio b/ux-design/flask-example-app-wireframes.drawio deleted file mode 100644 index ccf131a..0000000 --- a/ux-design/flask-example-app-wireframes.drawio +++ /dev/null @@ -1 +0,0 @@ -7VxbU9s6EP41eWzHt5jkEQKUh3KmU+hw+tRRbCXR4FiuLUNyfv3R1Y4tOTEQxwHCTAte67qXb1crWQN3slx9S0GyuMUhjAaOFa4G7uXAoT+uS38xylpQ7DPLEpR5ikJJKwl36D8oiapYjkKYVQoSjCOCkioxwHEMA1KhgTTFz9ViMxxVe03AHGqEuwBEOvUBhWQhqKOhVdJvIJovVM+2mt8SqMKSkC1AiJ83SO7VwJ2kGBPx13I1gRHjnuKLqHfd8LYYWApj0qbC3zj7CWbBj+tfaXDz4Dzc/hnZX2QrTyDK5YTlYMlacSDFeRxC1og1cC+eF4jAuwQE7O0zFTqlLcgyok82/VMflOoBpgSuNkhykN8gXkKSrmkR+XYk+bWuPj6X3C9oiw3Ou74kAinxedFyyRT6h+TLC3jkaDy6WoFlQvnjWNcRyB7p7/Mk0RhH50uq3JmhKJrgCKf0OcYxLXcBIjSP6WNAGQYp/YIxClH9O5cvligMWYtGzldlM8MxkRZk++pZjod1n5EUP0I1gIHjWvynV7F5XUnN1aT2AKOANs4RhP23YH/CQpQzKUqQJF/pr/sFylgfWVF0IS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FteIjCwl5nS3UHB3XTVbfm5MnJTrb6FHd8MEOhj+WFrGKRUt5r6179Dw== \ No newline at end of file diff --git a/ux-design/flask-example-app-wireframes.svg b/ux-design/flask-example-app-wireframes.svg deleted file mode 100644 index 2fee164..0000000 --- a/ux-design/flask-example-app-wireframes.svg +++ /dev/null @@ -1,3 +0,0 @@ - - -
Example Flask App
Example Flask App
Welcome to the example flask app. This is the home page.  Here are few links to example pages you might find interesting.
Welcome to the example flask app....
  • a page that displays information pulled from a MongoDB database collection
  • a page with a form you can submit to create a new record in a MongoDB collection
a page that displays information pulle...
The source code for this example app is available on GitHub.
The source code for this example app is avai...
This page shows information pulled from a MongoDB database collection.  Click here to add a new record to this collection.
This page shows information pulle...
The source code for this example app is available on GitHub.
The source code for this example app is avai...
Example Flask App
Example Flask App
Posted by Aanchal at 20:44 on 11 March 2021.
Edit.   Delete
Posted by Aanchal at 20:44 on 11...
Ut iusto repellendus ex delectus non vitae. Nihil molestiae magni dicta quo et expedita molestiae maxime.
Ut iusto repellendus ex delectus...
Posted by Aanchal at 19:21 on 11 March 2021.
Edit.   Delete
Posted by Aanchal at 19:21 on 11...
Ut iusto repellendus ex delectus non vitae. Nihil molestiae magni dicta quo et expedita molestiae maxime.
Ut iusto repellendus ex delectus...
Create a new record in the MongoDB database collection.
Create a new record in the MongoD...
The source code for this example app is available on GitHub.
The source code for this example app is avai...
Example Flask App
Example Flask App
Your name:
Your name:
Message:
Message:
Post
Post
Cancel
Cancel
Edit a record in the MongoDB database collection.
Edit a record in the MongoDB data...
The source code for this example app is available on GitHub.
The source code for this example app is avai...
Example Flask App
Example Flask App
Aanchal
Aanchal
Your name:
Your name:
Ut iusto repellendus ex delectus non vitae. Nihil molestiae magni dicta quo et expedita molestiae maxime.
Ut iusto repellendus...
Message:
Message:
Save
Save
Cancel
Cancel
Home page
Links to the Read page and the Create page.
Home page...
Read page
All posts are displayed in descending order of creation.  Clicking the Edit link for any post leads to the Update page, where that post is auto-filled into the form.  Clicking delete link deletes that post from the database and reloads this page.
Read page...
Create page
Filling in the form and submitting creates a new record in the database and returns the browser to the Read page.  Clicking cancel simply returns to the Read page.
Create page...
Update page
The form is auto-filled with a particular record.  Clicking to save updates that record and returns the browser to the Read page, where the new record shows up.
Update page...
Viewer does not support full SVG 1.1
\ No newline at end of file