Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FYI - Reproduce Web App Exercise #17

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@
.env

__pycache__


.vscode
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: gunicorn "web_app:create_app()"
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ python -m app.daily_briefing
APP_ENV="production" COUNTRY_CODE="US" ZIP_CODE="20057" python -m app.daily_briefing
```

Running the web app:

```sh
FLASK_APP=web_app flask run
```

## Testing

Expand Down
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ pandas
requests
sendgrid==6.6.0

Flask
gunicorn

#
# TEST
#
Expand Down
26 changes: 26 additions & 0 deletions web_app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# web_app/__init__.py

import os
from dotenv import load_dotenv
from flask import Flask

from web_app.routes.home_routes import home_routes
from web_app.routes.book_routes import book_routes
from web_app.routes.weather_routes import weather_routes

load_dotenv()

SECRET_KEY = os.getenv("SECRET_KEY", default="super secret") # set this to something else on production!!!

def create_app():
app = Flask(__name__)
app.config["SECRET_KEY"] = SECRET_KEY

app.register_blueprint(home_routes)
app.register_blueprint(book_routes)
app.register_blueprint(weather_routes)
return app

if __name__ == "__main__":
my_app = create_app()
my_app.run(debug=True)
26 changes: 26 additions & 0 deletions web_app/routes/book_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@



# web_app/routes/book_routes.py

from flask import Blueprint, jsonify

book_routes = Blueprint("book_routes", __name__)

@book_routes.route("/api/books")
@book_routes.route("/api/books.json")
def list_books():
print("BOOKS...")
books = [
{"id": 1, "title": "Book 1", "year": 1957},
{"id": 2, "title": "Book 2", "year": 1990},
{"id": 3, "title": "Book 3", "year": 2031},
] # some dummy / placeholder data
return jsonify(books)

@book_routes.route("/api/books/<int:book_id>")
@book_routes.route("/api/books/<int:book_id>.json")
def get_book(book_id):
print("BOOK...", book_id)
book = {"id": book_id, "title": f"Example Book", "year": 2000} # some dummy / placeholder data
return jsonify(book)
29 changes: 29 additions & 0 deletions web_app/routes/home_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# web_app/routes/home_routes.py

from flask import Blueprint, request, render_template

home_routes = Blueprint("home_routes", __name__)

@home_routes.route("/")
@home_routes.route("/home")
def index():
print("HOME...")
#return "Welcome Home"
return render_template("home.html")

@home_routes.route("/about")
def about():
print("ABOUT...")
#return "About Me"
return render_template("about.html")

@home_routes.route("/hello")
def hello_world():
print("HELLO...", dict(request.args))
# NOTE: `request.args` is dict-like, so below we're using the dictionary's `get()` method,
# ... which will return None instead of throwing an error if key is not present
# ... see also: https://www.w3schools.com/python/ref_dictionary_get.asp
name = request.args.get("name") or "World"
message = f"Hello, {name}!"
#return message
return render_template("hello.html", message=message)
48 changes: 48 additions & 0 deletions web_app/routes/weather_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# web_app/routes/weather_routes.py

from flask import Blueprint, request, jsonify, render_template, redirect, flash

from app.weather_service import get_hourly_forecasts

weather_routes = Blueprint("weather_routes", __name__)

@weather_routes.route("/weather/forecast.json")
def weather_forecast_api():
print("WEATHER FORECAST (API)...")
print("URL PARAMS:", dict(request.args))

country_code = request.args.get("country_code") or "US"
zip_code = request.args.get("zip_code") or "20057"

results = get_hourly_forecasts(country_code=country_code, zip_code=zip_code)
if results:
return jsonify(results)
else:
return jsonify({"message":"Invalid Geography. Please try again."}), 404

@weather_routes.route("/weather/form")
def weather_form():
print("WEATHER FORM...")
return render_template("weather_form.html")

@weather_routes.route("/weather/forecast", methods=["GET", "POST"])
def weather_forecast():
print("WEATHER FORECAST...")

if request.method == "GET":
print("URL PARAMS:", dict(request.args))
request_data = dict(request.args)
elif request.method == "POST": # the form will send a POST
print("FORM DATA:", dict(request.form))
request_data = dict(request.form)

country_code = request_data.get("country_code") or "US"
zip_code = request_data.get("zip_code") or "20057"

results = get_hourly_forecasts(country_code=country_code, zip_code=zip_code)
if results:
flash("Weather Forecast Generated Successfully!", "success")
return render_template("weather_forecast.html", country_code=country_code, zip_code=zip_code, results=results)
else:
flash("Geography Error. Please try again!", "danger")
return redirect("/weather/form")
10 changes: 10 additions & 0 deletions web_app/templates/about.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% extends "bootstrap_layout.html" %}
{% set active_page = "about" %}

{% block content %}

<h1>About Me</h1>

<p>This is a paragraph on the "about" page.</p>

{% endblock %}
97 changes: 97 additions & 0 deletions web_app/templates/bootstrap_layout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

<title>Hello, world!</title>
</head>
<body>

<!--
FLASH MESSAGING
https://flask.palletsprojects.com/en/1.1.x/patterns/flashing/
https://getbootstrap.com/docs/4.3/components/alerts/
-->
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<!--
BOOTSTRAP ALERTS
https://getbootstrap.com/docs/5.0/components/alerts/#dismissing
-->
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert" style="margin-bottom:0;">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}

<!--
SITE NAVIGATION & BOOTSTRAP NAV
https://jinja.palletsprojects.com/en/2.11.x/tricks/
https://getbootstrap.com/docs/5.0/components/navbar/
-->
{% set nav_links = [
('/about', 'about', 'About'),
('/hello', 'hello', 'Hello'),
('/weather/form', 'weather_form', 'Weather Form')
] -%}
{% set active_page = active_page|default('home') -%}
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container-fluid">
<a class="navbar-brand" href="/">My Web App</a>

<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
{% for href, page_id, link_text in nav_links %}
{% if page_id == active_page %}
{% set is_active = "active" -%}
{% else %}
{% set is_active = "" -%}
{% endif %}

<li class="nav-item">
<a class="nav-link {{ is_active }}" href="{{href}}">{{link_text}}</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</nav>

<div class="container" style="margin-top:2em;">

<!--
PAGE CONTENTS
-->
<div id="content">
{% block content %}
{% endblock %}
</div>

<footer style="margin-top:2em; margin-bottom:2em;">
<hr>
&copy; Copyright 2021 [Your Name Here] |
<a href="https://github.com/prof-rossetti/intro-to-python/blob/main/exercises/web-app/README.md">Source</a>

</footer>
</div>

<!-- Bootstrap JS Bundle -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
<script type="text/javascript">

console.log("Thanks for the page visit!")

</script>
</body>
</html>
10 changes: 10 additions & 0 deletions web_app/templates/hello.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% extends "bootstrap_layout.html" %}
{% set active_page = "hello" %}

{% block content %}

<h1>{{ message }}</h1>

<p>This is a paragraph on the "hello" page.</p>

{% endblock %}
10 changes: 10 additions & 0 deletions web_app/templates/home.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% extends "bootstrap_layout.html" %}
{% set active_page = "home" %}

{% block content %}

<h1>Welcome Home</h1>

<p>This is a paragraph on the "home" page.</p>

{% endblock %}
35 changes: 35 additions & 0 deletions web_app/templates/layout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Web App</title>
</head>
<body>

<!-- SITE NAVIGATION -->
<div class="container">
<nav>
<h1><a href="/">My Web App</a></h1>
<ul>
<li><a href="/about">About</a></li>
<li><a href="/hello">Hello</a></li>
</ul>
</nav>
<hr>

<!-- PAGE CONTENTS -->
<div id="content">
{% block content %}
{% endblock %}
</div>

<!-- FOOTER -->
<footer>
<hr>
&copy; Copyright 2021 [Your Name Here] |
<a href="https://github.com/prof-rossetti/daily-briefings-py">Source Code</a> |
<a href="https://github.com/prof-rossetti/intro-to-python/blob/main/exercises/web-app/README.md">Exercise Instructions</a>
</footer>
</div>

</body>
</html>
18 changes: 18 additions & 0 deletions web_app/templates/weather_forecast.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{% extends "bootstrap_layout.html" %}
{% set active_page = "weather_forecast" %}

{% block content %}

<h2>Weather Forecast for {{ results["city_name"] }}</h2>

<p>Zip Code: {{ zip_code }}</p>

<!-- TODO: consider using a table instead of a list -->
<!-- TODO: consider adding images using the provided icon urls -->
<ul>
{% for forecast in results["hourly_forecasts"] %}
<li>{{ forecast["timestamp"] }} | {{ forecast["temp"] }} | {{ forecast["conditions"].upper() }}</li>
{% endfor %}
</ul>

{% endblock %}
23 changes: 23 additions & 0 deletions web_app/templates/weather_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{% extends "bootstrap_layout.html" %}
{% set active_page = "weather_form" %}

{% block content %}

<h2>Weather Form</h2>

<p>Request an hourly forecast for your zip code...</p>

<form action="/weather/forecast" method="POST">

<label>Country Code:</label>
<input type="text" name="country_code" placeholder="US" value="US">
<br>

<label>Zip Code:</label>
<input type="text" name="zip_code" placeholder="20057" value="20057">
<br>

<button>Submit</button>
</form>

{% endblock %}