Python Cloud Advocate at Microsoft
Formerly: UC Berkeley, Coursera, Khan Academy, Google
Find Pamela online at:
Mastodon | @pamelafox@fosstodon.org |
@pamelafox | |
GitHub | www.github.com/pamelafox |
Website | pamelafox.org |
Python Cloud Advocate at Microsoft
Executive Director of Girls Programming Network, CEO/Founder of ConnectEd Code
Find Renee online at:
@noble_renee | |
GitHub | github.com/reneenoble |
Website | reneenoble.com |
linkedin.com/in/noblerenee/ |
To GET:
To POST:
A client sends an HTTP request:
GET /index.html HTTP/1.1
Host: www.example.com
The server sends back an HTTP response:
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 208
<!DOCTYPE html>
<html>
<head>
<title>Example Domain</title>
</head>
<body>
<h1>Example Domain</h1>
<p>This domain is to be used for illustrative examples in documents.</p>
</body>
</html>
The most commonly used codes:
Code | Meaning |
---|---|
200 | OK |
301 | Moved Permanently |
404 | Not Found |
500 | Server Error |
See more codes at HTTPcats.com or Wikipedia: List of HTTP status codes.
Webpages bring together three kinds of files/languages:
HTML contains the content and structure of your webpage in tags like these:
Headings
<h1>Web Development - Chapter 1</h1>
Paragraphs
<p>Today I am learning about webp development.</p>
Lists
<ul>
<li>Topic 1 - What is the Web</li>
<li>Topic 2 - Web Dev Frameworks</li>
<li>Topic 3 - Deploying to Azure</li>
</ul>
HTML captures content, puts it in semantic chunks, and creates hierarchy.
There are a lot of tags to use to:
CSS uses rules to set target elements to style.
Targets can be set with:We could style headings and paragraphs like this:
h1 {
font-family: "Roboto", sans-serif;
color: rgb(240, 50, 132);
}
p {
background-color: yellow;
}
CSS can do a lot of things!
JavaScript is code that dynamically accesses and updates the page content to make it more interactive.
It can do these things and many more:
The most basic server just serves up HTML and multimedia files from a file system.
Servers are also used for features that require persistent data or more security than allowed in the client:
For the frontend:
For the backend:
The http module in the Python standard library can run a basic server.
⚠️ It is not recommended for production.
It's handy for learning and local development, however...
A file server serves up files and folders according to their path in the file system. Also known as a static server.
Run a file server from any folder:
python3 -m http.server 8080
👩🏼💻 Repo: github.com/pamelafox/python-simple-server-example/
The server code is in server.py.
Uses the http
module to dynamically generate responses.
Run the server:
python3 server.py
Don't reinvent the wheel!
People make websites all the time, so we have tools that make it simpler.
Web frameworks have features like:Different frameworks offer different features and levels of complexity.
Python has a few modern web frameworks that are popular:
Flask, an external package, is a lightweight framework for server requests and responses.
Apps written in Flask:
👩🏼💻 Repo: github.com/Azure-Samples/simple-flask-server-appservice
Most server code is in app.py. Uses Flask to generate responses for each route.
Run the server:
python3 -m flask run --port 50505 --debug
Handle GET requests to "/about" route:
@app.get("/about")
def index():
return 'About Us'
Handle query parameters:
@app.get("/search")
def hello():
query = request.args.get("query")
return f"Searching for: {query}!"
Handle path parameters:
@app.get("/book/<id>")
def hello(name):
return f"Book with ID {id}!"
Handle POST requests:
@app.post("/submit")
def submit():
return "Thanks for submitting!"
Handle form data:
@app.post("/submit")
def submit():
name = request.form.get("name")
return f"Thanks for submitting, {name}!"
Handle JSON data:
@app.post("/submit")
def submit():
data = request.get_json()
name = data.get("name")
return f"Thanks for submitting, {name}!"
Flask uses Jinja2 templates to render HTML.
Variables:
<h1>{{ title }}</h1>
Conditionals:
{% if user %}
<p>{{ user.name }}</p>
{% else %}
<p>Logged out</p>
{% endif %}
Loops:
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Online development: Github account
Local development (option 2):
Local development:
Using this repo:
github.com/Azure-Samples/simple-flask-server-appservice
aka.ms/flask-appservice
🙋🏼♀️🙋🏾♀️🙋🏽♀️ Let us know if you need any help! 🙋🏻♀️🙋🏽♂️🙋🏿♀️
Jinja2 supports template inheritance.
Base template:
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
Child template:
{% extends "base.html" %}
{% block content %}
<h1>About Us</h1>
{% endblock %}
Using this repo:
github.com/Azure-Samples/simple-flask-server-appservice
or your own app from the previous exercise.
🙋🏼♀️🙋🏾♀️🙋🏽♀️ Let us know if you need any help! 🙋🏻♀️🙋🏽♂️🙋🏿♀️
Use a launch configuration to run the Flask app in debug mode.
Quart is the asynchronous version of Flask.
@app.get("/")
async def index():
return await render_template("index.html")
Quart is useful when apps have slow I/O or network calls:
@app.route('/')
async def chat():
return await openai_client.chat.completions.create(
messages=[{"role": "user", "content": "Write a haiku"}]
)
We need async to build modern web apps that support concurrency.
A web app without async:
A web app with async can handle new requests while waiting for an I/O op:
Any app with slow network requests, DB queries, or file reads can benefit.
See also: FastAPI tutorial on async
Install Quart:
pip install quart
Change the app construction:
from quart import Quart
app = Quart(__name__)
Change routes to async:
@app.route('/')
async def index():
Change API/DB calls to async.
Repo | Description |
---|---|
azure-search-openai-demo | RAG chat app using OpenAI |
openai-chat-app-quickstart | Simple chat app using OpenAI |
openai-chat-app-entra-auth-local | Simple chat app using OpenAI and user auth with Quart-Session |
When your website is hosted on a server, it means other users on the Internet can access it.
Many possible hosts:
Consider:
Azure Container Apps | Azure Functions | |||
Azure Kubernetes Service | Container Management | Azure App Service | Serverless | |
Environment | Containers | PaaS | ||
Cloud | Azure |
For Flask, App Service is easiest way to get started.
Databases | PostGreSQL, MySQL, CosmosDB, ... |
---|---|
Storage | Blob Storage, Files, Archive Storage, ... |
Networking | DNS Zone, Virtual Network, VPN Gateway, ... |
Caching | CDN, Front Door, ... |
Security | Key Vault, Security Center, ... |
Machine Learning | Translator, Bot Service, Computer Vision, ... |
...and more! |
Using the Azure Dev CLI:
azd up
azd up
. If prompted, login to your Azure account.
azd down
to un-deploy the app (so that you don't waste cloud resources unnecessarily).