Share
Explore

w24 The PYFlask App The Calculator March 25

Learning outcomes:
You will submit this code by providing the LINK to your GITHUB Repository.
Create a GitHUB REPOSITORY for this Class.
Make a file in your GITHUB Repository: Upload your GIT REPO URL by putting it into a text file, named as StudentName_STUDENTID.txt
Upload to

Purpose of this Lab:
Grab the HTML form fields and process them in the back end Python Program
Next we will hook this up to a database
This is the starting point of your project
Below are the step-by-step worksteps to make the provided code work:

### Step 1: Install Flask
If you haven't installed Flask, you can do so by running the following command in your terminal or command prompt:
```bash
pip install Flask
```

### Step 2: Create the Flask App
Create a new file, for example, `app.py`, and copy the provided Flask application code into this file.

### Step 3: Create the HTML Template
Create a new folder named `templates` in the same directory as your `app.py` and create a new file named `index.html` inside the `templates` folder. Copy the provided HTML template code into this file.

### Step 4: Run the Flask App
Save your files and run the application by executing the following command in your terminal or command prompt:
```bash
python app.py
```
After running the application, you can open your web browser and go to `http://127.0.0.1:5000/` to access the calculator web form.

### Step 5: Use the Calculator
Once the web form is loaded in your web browser, you can input two values and select an operator (+, -, /, *) to perform the calculation. When you submit the form, the result of the calculation will be displayed on the HTML page.

By following these worksteps, you will successfully create a web server using Flask with a calculator feature that allows users to input values and perform calculations.
megaphone
Flask is a lightweight and extensible web application framework for Python. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. Flask is based on the WSGI (Web Server Gateway Interface) toolkit and Jinja2 template engine, providing the essential tools and libraries for building web applications and services.
Here are some key characteristics and features of Flask:
1. **Simplicity**: Flask is designed to be simple and easy to use, making it an ideal framework for beginners to get started with web development in Python.
2. **Modularity**: It is built with a modular design, allowing developers to choose the components they need to build their applications without being forced into a particular way of doing things.
3. **Extensibility**: Flask provides a solid foundation and allows for the integration of various extensions and libraries to add functionality as needed, making it flexible for building diverse types of web applications.
4. **Routing**: Flask uses a simplistic routing mechanism, making it easy to map URLs to Python functions and methods.
5. **Template Engine**: It incorporates the Jinja2 template engine, enabling the creation of dynamic and reusable HTML templates with a familiar and accessible syntax.
6. **Development Server**: Flask comes with a built-in development server for testing and debugging applications locally.
7. **Community and Ecosystem**: Flask has an active and supportive community, resulting in a wide range of extensions and resources available for developers.
Overall, Flask provides a solid foundation for building web applications, RESTful APIs, and other web services in a concise, flexible, and elegant manner, making it a popular choice for Python developers.

Python Coding Lab: Building a Web Server with Flask

In this coding lab, we will focus on creating a simple web server using Python Flask framework. We will set up an HTML page with a form where users can input data. The data entered in the form will be captured by the backend and displayed back on the HTML page.
#### Lab Instructions:
1. **Install Flask**: - If you haven't already installed Flask, you can do so by running `pip install Flask` in your terminal or command prompt.
2. **Create the Flask App**: - Create a new Python file, for example, `app.py`, and set up the Flask application with the following code:
```python from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': user_data = { 'name': request.form['name'], 'email': request.form['email'] } return render_template('index.html', user=user_data) return render_template('index.html')
if __name__ == '__main__': app.run(debug=True) ```
3. **Create the HTML Template**: - Create a new folder named `templates` in the same directory as your `app.py` and create a new HTML file named `index.html` inside the `templates` folder.
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Form</title> </head> <body> <h1>User Form</h1> <form method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name"><br><br> <label for="email">Email:</label> <input type="email" id="email" name="email"><br><br> <button type="submit">Submit</button> </form> {% if user %} <h2>User Data:</h2> <p>Name: {{ user.name }}</p> <p>Email: {{ user.email }}</p> {% endif %} </body> </html> ```
4. **Run the Flask App**: - Save your files and run the Flask application by executing `python app.py` in your terminal. - Open your web browser and go to `http://127.0.0.1:5000/` to access the web form.
#### Lab Outcome: - You have successfully created a web server using Flask where users can input their name and email in a form. The submitted data is captured by the backend and echoed back on the HTML page.
This coding lab provides a basic foundation for building web applications using Flask and handling form submissions. Feel free to expand and enhance this lab further based on your learning objectives.

megaphone

To extend the Flask web application to include a basic calculator, we can modify the existing code to handle the input of two values and an operator (+, -, /, *) from the user. The backend will then perform the calculation and echo the result back to the HTML page. Below are the steps to achieve this:

image.png
image.png
image.png
```
### Running the Flask App: After making these changes, you can save the files and run the application by executing `python app.py` in your terminal. Then, open your web browser and go to `http://127.0.0.1:5000/` to access the calculator web form.
### Outcome: You have now extended the Flask web application to include a basic calculator. Users can input two values and select an operator, and the result of the calculation will be displayed on the HTML page. This enhancement demonstrates how Flask can be used to build simple yet powerful web applications.

To extend your Flask application to store form results in a MongoDB database, you'll need to perform a few steps:

1. **Install MongoDB Driver**: You'll need to install `pymongo`, the MongoDB driver for Python. You can install it using pip:

```
pip install pymongo
```

2. **Database Setup**: Assuming your MongoDB server is already running on `localhost` with the default port `27017`, you can create a seed program to set up your database and collection.

Here's a simple seed program that creates a database named `calculatorDB` and a collection named `calculations`:

```python
from pymongo import MongoClient

def seed_database():
client = MongoClient('localhost', 27017) # Connect to MongoDB server
db = client.calculatorDB # Create a database named 'calculatorDB'
db.calculations.drop() # Drop the collection if it already exists
db.create_collection('calculations') # Create a new collection named 'calculations'
print("Database and collection created successfully.")

if __name__ == '__main__':
seed_database()
```

Run this script once to initialize your database and collection.

3. Integrate MongoDB with Flask App

Modify your Flask application to insert calculation results into the MongoDB database.

Here's an updated version of your `app.py` to include MongoDB integration:

```python
from flask import Flask, request, render_template
from pymongo import MongoClient
import datetime

app = Flask(__name__)
client = MongoClient('localhost', 27017)
db = client.calculatorDB

@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
try:
value1 = float(request.form['value1'])
value2 = float(request.form['value2'])
operator = request.form['operator']
result = calculate(value1, value2, operator)

# Insert the calculation into MongoDB
db.calculations.insert_one({
'value1': value1,
'value2': value2,
'operator': operator,
'result': result,
'timestamp': datetime.datetime.now()
})
except ValueError:
result = "Invalid input"
except Exception as e:
result = str(e)
return render_template('index.html', result=result)
return render_template('index.html')

# Rest of your Flask app...

if __name__ == '__main__':
app.run(debug=True)
```

In this version, every time a calculation is performed and submitted via your form, the details along with the result are stored in the `calculations` collection of your `calculatorDB` database in MongoDB.

Ensure that MongoDB is running on your host, and the MongoDB Python driver is installed in your environment. Also, handle the MongoDB connection appropriately, closing it when not needed, especially in a production environment. This example keeps it simple for educational purposes.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.