Chapter 10: Dynamic Website Hosting (PHP, Python, Node.js with MySQL)
10.4 Python (Flask) with MySQL
Here Flask defines the Python routes and Gunicorn can run them as a WSGI application. A front server forwards HTTP to Gunicorn. Unlike PHP-FPM, this path does not use FastCGI.
इथे Flask मध्ये Python routes लिहितो आणि Gunicorn ते WSGI app म्हणून चालवतो. Front server Gunicorn कडे HTTP ने requests पाठवतो. या setup मध्ये FastCGI वापरत नाही.
यहाँ Flask में Python routes लिखते हैं और Gunicorn उन्हें WSGI app की तरह चलाता है। Front server Gunicorn को HTTP से requests भेजता है। इस setup में FastCGI इस्तेमाल नहीं होता।
Install Python tools
cat /etc/os-release
python3 --version
python3 -m venv --help
Prepare a project-local Flask application
Choose a fresh project directory. An approved managed release may live under /opt with a dedicated service account. Check actual permissions, SELinux policy and the unit’s working directory.
From the fresh learner workspace, use this project-local environment.
python3 -m venv .venv
.venv/bin/python -m pip --version
# Prepare an approved local secret or managed credential outside source control.
# Use the reviewed app.py and templates/students.html below.
Test it manually
# Run in the foreground with the approved practice settings.
.venv/bin/gunicorn --bind 127.0.0.1:18805 app:app
Run with Gunicorn as a systemd service
# Inspect only the owned unit after preparing it through the approved setup.
systemctl cat student-flask-lab.service
Use an explicit dedicated service identity and project path. Verify the full unit and credential mechanism before applying the owned service definition.
Ravindra Bagale's Tip
Keep database credentials outside the source tree and public root. Use an approved protected credential mechanism, and leave secret values out of Git and diagnostic output.
Ravindra Bagale's Tip – मराठी
Database credentials source tree आणि public root च्या बाहेर ठेवा. मंजूर protected credential पद्धत वापरा. Git आणि diagnostic output मध्ये secret values देऊ नका.
Ravindra Bagale's Tip – हिंदी
Database credentials को source tree और public root के बाहर रखो। मंजूर protected credential तरीका इस्तेमाल करो। Git और diagnostic output में secret values मत डालो।
Lab
Chala, khalcha Gunicorn lab kara. Health, readiness ani data route vegle tapaasa. Assigned unit asel tar tyachi runtime ani boot state tapaasa. Shared machine reboot karaychi garaj nahi.
Serve the practice student list with Flask and a managed WSGI process
A campus project team needs the same stored student records in a browser table and a structured API. Both views should read the same approved practice database. The team also wants to demonstrate adding a single synthetic row from a local development exercise. Flask can map each HTTP operation to a Python function and choose how to present the current rows. Gunicorn can then run the imported application behind the planned front web server. The managed sample keeps writes disabled and verifies the two read formats and a readiness query.
Use the appdb.students table built in the database setup lesson. Its initial rows are synthetic. The request code does not create schema or administer users. A dedicated app role can list the intended rows, and the local form exercise additionally needs the INSERT grant. For a hosted read-only service, provision only its required read access. Treat application and database configuration as separate from the files a visitor receives.
The main teaching point is connection lifetime. The first database-backed route creates one connection for that request's application context. Other helpers in the same context can use it. Flask closes it when the context ends, including on the error path. A lightweight health check can reply without opening that connection, while a database readiness check verifies the configured table with the runtime account. These routes give operators different evidence.
Distinguish Flask routes, WSGI workers and their upstream HTTP
Flask is a Python web framework. A route tells it which function handles a request such as GET /api/students. The function gets the request data and returns a representation. WSGI is a Python interface through which a supported server invokes the application. Gunicorn can listen for HTTP, convert the incoming request into a WSGI call, and send back the application's response. In the one-host managed arrangement the reverse proxy forwards HTTP to Gunicorn on the approved loopback listener. That differs from sending FastCGI to PHP-FPM.
Run the app directly in a local environment for the development test. Flask's built-in development server makes it easy to observe requests but is not the service choice for production. In the managed example Gunicorn imports app:app from your working directory. The first app means the Python module app.py. The second is the Flask object exported by that module. Importing it does not run the block reserved for direct Python execution. We use that distinction to keep the optional write lab separate from the hosted read mode.
| Component | What it does | What you can verify |
|---|---|---|
| Front proxy | Receives the named HTTP or HTTPS request and applies the configured upstream route. | Frontend host, status and matching app path. |
| Gunicorn | Runs Flask in a WSGI worker and returns its response. | Actual listener, successful import and worker or request log. |
| Flask route | Chooses HTML, JSON or the configured error result. | Expected method, media type, row marker and status. |
| PyMySQL connection | Executes the approved query as the runtime account. | Correct database, permit scope, row result and cleanup. |
Eventually a load balancer or deployment platform may own parts of the front layer. Verify where a public client reaches TLS and how the backend is selected in that design. A successful loopback app request remains useful evidence about the Flask process and database, while the actual public route has additional forwarding and network checks. Never infer that the local HTTP binding must be exposed publicly to make the site's ordinary request work.
Build a reproducible Python environment for the approved release
Use a supported Python interpreter on the assigned machine and verify its version. Work in a fresh project directory rather than modifying another Python service's packages. A virtual environment gives the project its own interpreter command paths and installed libraries. Creating it does not source your database variables or start any server. Check the approved package source and compatible dependency versions for the chosen Python and MySQL or MariaDB server. Record the versions accepted by your exercise so it can be recreated later.
python3 --version
python3 -m venv .venv
.venv/bin/python -m pip install Flask 'PyMySQL[rsa]' gunicorn
.venv/bin/python -m pip show Flask PyMySQL gunicorn
Run the commands from the fresh project directory. The optional PyMySQL RSA dependencies can be required for supported MySQL authentication paths, depending on the server plugin and connection transport. Consult the connector documentation for your security setup and use TLS verification when the approved database design requires it. The managed service should use the virtual environment's explicit executable, not whichever python or gunicorn happens to be first in a login shell. The example uses a basic compatible connector configuration for a local approved database link.
Keep the source, its template and the reviewed dependency list together. Store deployment configuration and secret material outside the public root and versioned code. The local process below accepts a practice password from its shell for the duration of that exercise. The managed process can use a protected systemd credential file; long-lived infrastructure should use its approved secret mechanism. The sample can read the db-password credential supplied in CREDENTIALS_DIRECTORY. It falls back to explicitly supplied local environment configuration when no such directory is present.
Write the routes and tie the database session to the request context
Save this source as app.py in the project root. It reads the same schema as the other chapter languages. The hosted mode starts with all write routes disabled and the development form must be explicitly enabled. The health route checks that Python is handling requests. The readiness route exercises the app's database connection and the table it expects. Both are diagnostic choices. A real deployment may restrict access to health and readiness endpoints according to what they reveal and who needs them.
import os
import secrets
from hmac import compare_digest
from pathlib import Path
import pymysql
from flask import Flask, abort, g, jsonify, redirect, render_template
from flask import request, session, url_for
app = Flask(__name__)
app.config.update(LAB_WRITES=False, MAX_CONTENT_LENGTH=4096)
class DatabaseConfigError(RuntimeError):
pass
def db_password():
directory = os.getenv("CREDENTIALS_DIRECTORY")
if directory:
try:
return (Path(directory) / "db-password").read_text(
encoding="utf-8"
).rstrip("\r\n")
except OSError as error:
raise DatabaseConfigError("Credential unavailable") from error
return os.getenv("DB_PASSWORD", "")
def get_db():
if "db" not in g:
user = os.getenv("DB_USER", "")
password = db_password()
try:
port = int(os.getenv("DB_PORT", "3306"))
except ValueError as error:
raise DatabaseConfigError("Invalid database port") from error
if not user or not password or not 1 <= port <= 65535:
raise DatabaseConfigError("Incomplete database settings")
g.db = pymysql.connect(
host=os.getenv("DB_HOST", "127.0.0.1"),
port=port,
user=user,
password=password,
database=os.getenv("DB_NAME", "appdb"),
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor,
connect_timeout=4,
read_timeout=5,
write_timeout=5,
autocommit=False,
)
return g.db
@app.teardown_appcontext
def close_db(error):
connection = g.pop("db", None)
if connection is not None:
connection.close()
@app.errorhandler(DatabaseConfigError)
@app.errorhandler(pymysql.MySQLError)
def database_unavailable(error):
app.logger.warning("Student list: database request unavailable")
return {"error": "Student data temporarily unavailable"}, 503
@app.after_request
def prevent_storage(response):
response.headers["Cache-Control"] = "no-store"
return response
def read_students():
with get_db().cursor() as cursor:
cursor.execute("SELECT id, name, city FROM students ORDER BY id")
return cursor.fetchall()
@app.get("/")
def student_list():
token = None
if app.config["LAB_WRITES"]:
if "lab_token" not in session:
session["lab_token"] = secrets.token_hex(24)
token = session["lab_token"]
return render_template("students.html", rows=read_students(), token=token)
@app.get("/api/students")
def api_students():
return jsonify(read_students())
@app.get("/health")
def health():
return {"status": "ok"}
@app.get("/ready")
def ready():
with get_db().cursor() as cursor:
cursor.execute("SELECT id FROM students LIMIT 1")
cursor.fetchone()
return {"status": "ready"}
def field(name, maximum):
values = request.form.getlist(name)
if len(values) != 1:
abort(422)
value = values[0].strip()
if not value or len(value) > maximum:
abort(422)
return value
@app.post("/add")
def add_student():
if not app.config["LAB_WRITES"]:
abort(403)
expected = session.get("lab_token", "")
candidate = request.form.get("form_token", "")
if not expected or not candidate.isascii() or not compare_digest(expected, candidate):
abort(403)
name, city = field("name", 100), field("city", 50)
connection = get_db()
with connection.cursor() as cursor:
cursor.execute("INSERT INTO students (name, city) VALUES (%s, %s)", (name, city))
connection.commit()
return redirect(url_for("student_list"), code=303)
if __name__ == "__main__":
app.config["LAB_WRITES"] = os.getenv("ENABLE_LOCAL_FORM") == "1"
if app.config["LAB_WRITES"]:
app.secret_key = secrets.token_hex(32)
app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Strict")
app.run(host="127.0.0.1", port=int(os.getenv("LAB_PORT", "18804")),
debug=False, use_reloader=False)
The app creates a connection only when a data route asks for one. Flask's g object here belongs to the application context associated with the request. It is not a global connection to share among all worker processes or threads. The teardown function removes and closes it. The cursor used by a query is scoped by its own context manager. The local insert commits explicitly before returning the redirect. If an exception prevents that commit, the connection is closed and incomplete transactions do not represent a successful confirmed registration. Some failures around commit can leave the client uncertain whether the server acted, so a production retry policy needs its own safeguards.
The SQL in the insert is a template with placeholders. PyMySQL receives the values in a separate tuple for driver parameter handling. The percent placeholders are not an instruction to use Python string substitution. Keep table names and queries in application code. Validation checks the form's expected shape and sizes independently. The database account controls what the connection can perform. Protecting the query structure and selecting acceptable operation parameters are different responsibilities within the same request.
Render the same data as HTML and JSON
Create a directory named templates beside app.py and put this file at templates/students.html. It belongs to Flask's application inputs. A front web server should not publish the project directory just because it contains this template. The program calls the template engine with a list of row dictionaries. The template repeats one row per database result. An empty collection can render a meaningful empty table, while an unavailable database is handled as its own response before rendering.
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Flask student list</title></head>
<body>
<h1>Flask practice students</h1>
<table>
<caption>Synthetic rows from the practice database</caption>
<thead><tr><th scope="col">ID</th><th scope="col">Name</th>
<th scope="col">City</th></tr></thead>
<tbody>
{% for student in rows %}
<tr><td>{{ student.id }}</td><td>{{ student.name }}</td>
<td>{{ student.city }}</td></tr>
{% else %}
<tr><td colspan="3">No practice students yet.</td></tr>
{% endfor %}
</tbody>
</table>
{% if token %}
<h2>Add a synthetic student</h2>
<form method="post" action="{{ url_for('add_student') }}">
<input type="hidden" name="form_token" value="{{ token }}">
<label>Name <input name="name" maxlength="100" required></label>
<label>City <input name="city" maxlength="50" required></label>
<button type="submit">Add student</button>
</form>
{% endif %}
</body>
</html>
Jinja renders the values into an HTML template. Flask's normal autoescaping for an HTML template handles text characters for the surrounding context. Do not mark untrusted stored values safe to bypass it. The API uses the same query and serializes the rows as JSON, a different representation. One endpoint speaks to a browser page, and the other speaks to a client that expects structured data. Confirm both match the approved public fields. A data-management application would need separate policy for which users may read its records at all.
The practice form's token is tied to a signed Flask session cookie in the isolated local process. Such a cookie can be readable by the client even though signatures protect its integrity. Keep credentials and sensitive data out of it. The development program generates a random local signing key at each launch, so a session from an earlier run may no longer work. The app uses a cookie only for the optional local exercise and does not implement authentication. Production write or identity features require independent design and authorization.
Lab one. Verify request, commit and read behaviour on loopback
Prerequisites are the Python virtual environment, your saved source and template, and the approved MySQL or MariaDB training schema and account. Keep the local form exercise confined to your own synthetic database. Use the actual port and credentials assigned by the setup lab. From the fresh project root run the following in a shell that supports its prompt. The write flag applies to the direct development server only, and the program binds to loopback with debug mode disabled.
(
set -eu
export DB_HOST=127.0.0.1 DB_PORT=3306 DB_NAME=appdb DB_USER=appuser
printf '%s' 'Practice DB password: ' >&2
IFS= read -r -s DB_PASSWORD
printf '\n' >&2
export DB_PASSWORD
export ENABLE_LOCAL_FORM=1 LAB_PORT=18804
.venv/bin/python app.py
)
The variables in the practice shell describe the intended server, database and identity. The prompt leaves the value out of the displayed command and the shell keeps it only for this process invocation. Use an approved local secret mechanism instead if your environment requires one. No service needs a public binding for this check. A port collision calls for a new high local test port, not a stop to another server. The path app.py and the template should both belong to the fresh project.
curl --noproxy '*' --include http://127.0.0.1:18804/health
curl --noproxy '*' --include http://127.0.0.1:18804/ready
curl --noproxy '*' --include http://127.0.0.1:18804/api/students
Expect health 200 with status: ok, readiness 200 with status: ready, and a JSON array containing the known initial rows. Open the root URL from the same local browser session that will submit the form. Enter a unique synthetic marker, for example “Flask Club & Test”, and a city. The form submit uses its embedded token and the browser's own session cookie. Inspect the network result. The POST should produce 303, followed by a GET that shows the row. The independently requested JSON list should return the same stored value. A subsequent normal GET must leave the stored count unchanged.
For a rejection check, use an empty field or a missing token only against your own isolated sample session. Verify 422 for a field validation failure after a valid token, or 403 when the token check refuses the request. Check that the matching synthetic row count did not change. If the database is unavailable, health can continue to respond while readiness and data requests return 503. Do not interrupt a real database to cause this effect. You can test with an intentionally missing setting in a separately launched copy of the local app.
Stop the process from its own terminal when finished and verify the local port is no longer listening. Its signed local session becomes invalid when the app's ephemeral signing key is gone. The database may be needed for the next chapter exercise; remove only your authorized practice row through the designated role or retire the whole scratch fixture it belongs to. The app role does not have permission to delete rows. Keep the seed table and its scope under the original exercise's owner.
Run the read-only app through Gunicorn with the intended identity
Run Gunicorn as the approved ordinary account, from the project root with its virtual environment. The app:app import leaves the direct Python execution block unused, so the local write feature stays disabled. The master process manages workers that handle WSGI requests. A worker count is a capacity choice rather than a universal requirement. Multiple processes have independent application state and may each open a database connection for a request. Begin with the instructor's assigned capacity and compare real demand before changing the process count.
# With the approved runtime settings already supplied to this shell:
.venv/bin/gunicorn --workers 2 --bind 127.0.0.1:18805 \
--access-logfile - app:app
Run in the foreground for the first exercise so that startup and worker messages remain visible and you can stop only this terminal's process. This command requires the intended app import, template and dependency paths. Test health and database access separately. If the app is loaded from another working directory, Gunicorn can fail its import or pick a different module. Check the command and its starting directory rather than trying to work around it by changing global imports. Use the exact virtual environment executable.
For a retained approved Linux deployment, set up an owned unit, for example student-flask-lab.service. The example uses systemd's file credential mechanism on compatible versions. Put the actual password in an approved root-managed private file outside the release. The manager can provide the named credential to the process and declare its directory. Use a dedicated service account pre-provisioned by the lab owner and provide a release it can read. If the platform has another secret facility, follow its authorized integration and verify the app can read it without exposing it to unrelated service accounts.
[Unit]
Description=Practice Flask student list
After=network.target
[Service]
Type=exec
User=studentflask
Group=studentflask
WorkingDirectory=/opt/student-flask-lab
Environment=DB_HOST=127.0.0.1
Environment=DB_PORT=3306
Environment=DB_NAME=appdb
Environment=DB_USER=appuser
LoadCredential=db-password:/etc/student-flask-lab/db-password
ExecStart=/opt/student-flask-lab/.venv/bin/gunicorn --workers 2 --bind 127.0.0.1:18805 --access-logfile - app:app
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
The unit specifies a same-host service that listens only on loopback. App packages are not placed under any web root. Review startup order and dependencies for the assigned service. After=network.target orders relative to that target when it participates. It cannot prove a specific database authenticated a connection. A separately managed database may become ready later. The chosen platform can use readiness and deployment policy to decide whether normal traffic should go to this process yet. Use functional checks instead of declaring success at the first worker boot message.
Stage and validate only the new unit under the training host's administrative process. Use systemd's manager reload when changing a unit definition and an appropriate service start or restart to apply the new command. Keep boot enablement a separate planned action. Inspect active state, journal and actual binding after applying the unit. There is no need to reboot a shared host to test a web application. If an isolated training machine specifically calls for a boot test, capture the approved before state and verify the expected service and data afterwards.
Lab two. Compare process health, database readiness and the user request
Use the read-only Gunicorn process from the preceding stage or its approved managed service. The commands below assume the same-host loopback address. A separate gateway test should use the actual assigned name and route. First check that no development form is present at the managed root URL. Then inspect the three endpoints. Compare the process state and the data response rather than manually opening a database as root and treating that as an application test.
curl --noproxy '*' --include http://127.0.0.1:18805/health
curl --noproxy '*' --include http://127.0.0.1:18805/ready
curl --noproxy '*' --include http://127.0.0.1:18805/api/students
curl --noproxy '*' --include http://127.0.0.1:18805/
The live worker should return health 200, readiness 200 and the expected student data through both representations. Readiness verifies permission to run its small query and the presence of its expected schema. It can succeed on an empty table. The business check still needs the expected seed marker if the exercise requires it. A prohibited POST to the managed form route gets 403 without changing the database. If using a reverse proxy, repeat the approved external request after verifying that it routes to the same app and required path.
If only health works, verify the actual credential and connector inputs for the intended process, then run the runtime account's test query over the same transport. A CLI query under a different user can be useful for diagnosis but does not confirm the app's session. If readiness works and the page fails, inspect the expected template and query representation and read the app logs near the request. When the app succeeds directly and the public route fails, compare the proxy's upstream host, port and path. Keep the first failing condition and the known-good control.
End a foreground practice by stopping only that process. For an owned managed unit, restore or retire just its prepared settings under the host's approved procedure. Remove the temporary credential only when no related service needs it, and keep the shared practice database intact if later labs use it. Test the previous dependent routes after an authorized shared activation. The acceptance notes should explain what was actually tested inside Gunicorn and which network or service-manager checks belong only to the learner's own managed deployment.
Make the different health signals useful to an operator
The health route answers a deliberately limited question. It verifies that an HTTP request reached a process which imported the app and ran that view. It avoids opening a SQL session. The readiness route tries a small query against the table expected by this version of the application. It checks more dependencies but still does not guarantee the table has a particular record, the template can render it or every authorized feature succeeds. The full browser and API checks then verify a typical read across the actual data path.
| Endpoint | Positive result covers | Follow-up when another check fails |
|---|---|---|
/health | Running listener, Flask import and minimal route. | Compare the app's connection or template if a data request fails. |
/ready | The worker can open a session and run its table query. | Check the actual query, rows and response formatting if the real operation still fails. |
/api/students | The sample table query and JSON representation. | Check the expected marker and compare the rendered browser view or front route. |
/ | The runtime, expected rows and Jinja template for the list. | Check the actual delivery path if a separate browser or proxy sees something else. |
In deployment, map each health signal to the policy that consumes it. A process supervisor might restart a crashed service. A traffic manager might use readiness to avoid routing to a worker exposed to an unavailable dependency. A recurring shutdown or restart after any transient dependency fault can make another failure mode worse. Choose thresholds and monitoring under the platform's design, with a clear limit to each signal. A health endpoint does not need to print private versions, account details or connection data to an external reader.
For a local proof, launch a separate foreground copy with no database password. Its lightweight health view can still return 200, and its data calls return a limited 503 body. The managed service is not affected. Restore the expected local configuration and verify all three relevant responses. This distinguishes the service being absent from a present, responsive app that cannot use a database dependency. Do not purposely remove credentials from an active shared service to make this comparison.
Reason about connections and transactions across workers
Flask's application context gives an ordinary request a place to hold its connection. A helper can reuse it if several queries in that request belong to the same operation. Other workers have separate contexts, so they might open different database connections. Sharing a connection object at module import would put state into an unsuitable lifetime, especially with multiple worker processes and concurrent visits. Keep the unit of work explicit. The view uses a local cursor, and the application teardown closes its session even when the route finishes with an error.
The local write uses autocommit disabled and calls commit after the parameterized INSERT succeeds. The redirect is created after this point. Without an explicit commit, closing the connection can roll back a pending insert. The next clean GET might then show zero new rows despite a page that looked like a successful submission. Verify the database state after the redirect. If the insert fails before commit, review which error happened and ensure that the user receives a response that does not claim a successful write.
A single accepted write and a subsequent repeated GET are independent. The GET reads the row and does not repeat the insert. A client retry of POST is another event. A production service may need an operation identifier and a defined storage or transaction rule if the same logical registration must only occur once. Consider the case where the connection breaks during commit and the client does not know the outcome. A blind retry can create another row in this sample because names are not unique. This is distinct from redirecting a normal browser refresh.
For a real service, measure how many simultaneous app requests can need database connections. Adding workers can increase pressure on the database even though each individual request cleans up. A pool can reuse connections and carry different concurrency settings. Calculate the total across the service and decide when requests should wait or fail. For this beginner example predictable open, use and close behaviour is easier to verify. Keep production sizing and connection timeout values explicit when extending it. The default timeouts in the practice source keep a misconfigured data route from waiting indefinitely during a demo.
Diagnose which code and environment the managed service started
A trainee launches a project successfully from one terminal and then sees an import failure in the service journal. The service's working directory might differ. The PATH inherited by the CLI test can also point to a virtual environment that the installed unit never uses. Check the full path to Gunicorn, the selected working directory, and read access for the dedicated user to the app module and template. The process executing the file needs the inputs no matter where the person who installed it saved their shell variables.
A release under /opt can be a useful site-specific location when the host owner intends it. That name does not automatically grant SELinux permission or make systemd use it. Check the actual host's permissions, labels and configured execution policy. Keep the project files protected from ordinary runtime writes unless the application genuinely needs to update them. In the example the application writes into the database through its specified SQL role. Runtime changes to the packaged code and template are outside the normal HTTP operation.
Once an exec error is resolved, a successful fork of Gunicorn workers is still only a stage. Request health, then readiness and then the real JSON and HTML behavior. A template missing from the installed release can fail only the HTML path. A database credential may be missing from both data routes. An invalid public proxy mapping can keep all those local routes out of reach from a remote client. Build one comparison for each possibility, and choose the smallest change supported by the result.
Keep managed secret changes separate from code deployment
The sample can read a protected credential path supplied by systemd. The manager loads the source through its authorized access and provides a credential file for the service's lifetime. CREDENTIALS_DIRECTORY points to that directory, without containing the password itself. An approved service can use an alternate secret facility. In either case do not put the value in the unit's visible command, an installed source file or version control. Describe where the secret is managed and which role may retrieve it.
A new credential might require starting a new process or an approved renewal path to load a changed value. Plan that separately from changing the code. Verify the runtime account and data query after rotating the test credential, and protect the original access until the new path has been approved. If the application cannot read the credential file, fix the intended secret projection or service identity rather than loosening all file permissions. Keep a scoped deployment record that identifies the setting by name and confirms its test result without capturing its contents.
Testing a compatible MySQL or MariaDB app can involve versions or plugins different from a colleague's machine. A local app test may use a simple approved loopback connection. A private remote database can require a protected transport, certificate authority data and host verification. Use the connector's supported parameters for the intended connection, and validate them using the same deployed code and role. Do not declare a successful local test a proof of encryption or authentication on a route it never exercised.
Diagnose a working JSON route and a failing browser table
Imagine the API response shows three known rows and the browser gets an internal error on /. Begin by comparing which components both routes share. They use the same Gunicorn process, Flask application context, connection settings and query. The browser route additionally needs the named template in Flask's configured template directory. Look at the controlled app error and check whether that template file was included in the installed release with the intended name and readable mode. Fix the release input rather than changing the SQL credentials that already worked on the API.
The opposite case is also possible. The table renders the markers correctly but a client describes an API failure. Compare the API's exact URI and assigned content type. A proxy may route a prefix differently, or the client can be reading HTML returned by an intervening default page. Compare the direct local endpoint with the managed route and inspect the returned JSON structure. Ask whether the consumer expects a list of row dictionaries or a wrapper object with a property named students. A template success cannot establish that another client receives its required representation.
When checking an unexpected response, inspect the method and route as well as its JSON fields. The sample uses GET for the read views and POST for the optional local add operation. A wrong method can produce a Flask refusal before that view reaches the database. A local development GET can succeed for the list even if a new client attempts an unsupported write. Confirm which mode was launched, then compare the actual application code and environment. A stronger demonstration explicitly proves which methods are supported in each mode.
For a report distinguish data values from execution details. The returned city and name are approved synthetic fields. The database address, account settings and internals of error stack traces are operator information. Use one expected synthetic row to correlate the HTML and JSON response. Do not present private settings as part of the API payload. If the log indicates a dependency failure, support the claim with a readiness response and a scoped database client check under the matching role.
Make a package update distinguishable from a runtime change
Suppose the application installed successfully after a dependency update on a laptop, but its production service still uses the old virtual environment. A package installation and the process's actual interpreter are different things. Check which executable the service uses and whether its working directory selects the intended app release. The active worker might still import an older module or still be using different dependencies from the newly prepared stage. Record the verified versions and process path in the release note instead of only recording the command you used to install them.
Deploy the app and its template together because a partial file transfer can leave the two representations inconsistent. Run a syntax or import check in the new scope, then request the distinct paths through the new worker. An active supervisor does not verify that every request shape is represented. Check the seed query, resource list and document rendering as separate acceptance results. If you restore an earlier code release, verify that it still expects the table columns the database now provides. The database schema is independently managed and may not be restored by the Python rollback.
For an isolated test restore the previous prepared dependency and source pair by choosing its complete private stage. Run it at an approved local binding and compare the expected old result without changing a shared running host. For a managed rollback follow the site owner's validated way to select the exact old version and retest its own controls. If a duplicate DB session remains after repeated requests, compare the teardown scope and process state. A test that only sees one request succeed is insufficient to demonstrate resource cleanup during real repeated work.
One useful extended fixture test is to make five fresh data requests and inspect the number of active connections for the synthetic app account after all responses complete. The request-level example should close its session after each ordinary request. In a later design with connection pooling, some retained idle sessions would be expected, so use the documented pooling policy to interpret the result. The useful distinction is the planned resource lifetime and observed process behavior. It gives you an explainable operating requirement when another person changes the worker count or connector.
Record response time and the dependency you actually checked
A simple readiness response can take longer than health because it establishes a database session and executes a statement. Record the route, HTTP result and expected payload together, and check which timeout applied if the request fails. In the practice sample each connection has a bounded connection and read setting. A monitoring probe could have its own shorter deadline, which is a separate observation. If an early deadline triggers, compare the real service and database timing before adjusting unrelated worker or network configuration.
Interview questions with explained answers
What does app:app mean in the Gunicorn command?
Before the colon is the importable module name. After it is the callable application object in that module. Gunicorn imports the object and runs it through WSGI. It does not start the development-only code guarded by the direct-execution check.
Why attach the SQL connection to Flask's application context?
A route can share a connection with helpers during one request without sharing it among unrelated workers. The teardown handler closes it at the end. Neither a global connection nor leaving it open after errors matches that lifetime.
Why does health return 200 while readiness returns 503?
The basic view can execute without opening a database connection. Readiness tests a specific data dependency and reports when it cannot proceed. The two observations narrow the failure to the dependency or its configuration.
How do you know an insert happened before the user got success?
Verify the transaction commits before forming the response. Check the subsequent approved read in the same database and verify the expected marker and row count. A status on its own does not prove the write persisted.
How can the same rows appear as HTML and JSON safely?
Use an explicit query for the intended fields. Render the data with the template engine's appropriate escaping for HTML, and use a real JSON serializer for the API. The data-limiting and access policy apply to both routes.
Check your understanding
Gunicorn imports the application, and the local form flag is set in the process environment. Which code enables the form?
Show answer
Only the direct
python app.pybranch can enable this local form. The imported object starts read-only and rejects that write route.The shell query worked and the API gets 503. Which process and settings do you inspect?
Show answer
Check the deployed worker's actual connector, role, transport, target database and credential integration. A shell may use a different path or user.
Why close a query cursor and the server session separately?
Show answer
A cursor belongs to the query work, while the request can reuse its connection. The context teardown ends that session when the request's work is finished.
The write returns a redirect but no row is visible. Which persistence step belongs in the investigation?
Show answer
Check that the intended statement succeeded and committed in the correct database before building the redirect, then compare the subsequent read.
Why keep a readiness check and a known-row acceptance check?
Show answer
The readiness query verifies dependency access and a table contract. It may pass on an empty table, while the business check also verifies the actual data and response.
Independent practice tasks
Draw the Python worker and DB session lifecycle for
/healthand/api/students. Mark why one uses no database connection.Run the local synthetic form checks and record the status and row count for an invalid and valid request. Explain what changed between the commit and subsequent GET.
Prepare a short unit handoff with the actual executable, working directory, credential source name and three expected probe outcomes. Keep the secret value out of the report.
Revision cards
- WSGI
- The Python interface a compatible server uses to call the Flask application for a request.
- Gunicorn import
- Use the exact interpreter environment, module name and app object for the managed process.
- Request context lifetime
- Acquire a connection on demand and close it when the app context ends.
- Commit before returning
- Confirm a change through the chosen database transaction and verify it with a separate read.
- Health and readiness
- One can prove a running app path while the other exercises a specific dependency.
- Managed credential
- Supply the credential via the authorized service mechanism and verify only presence and operation in diagnostics.
Official sources
- Python virtual environments
- Flask application context and teardown
- Flask Jinja rendering and autoescaping
- Flask request, routes, handlers and session API
- Flask managed deployment
- Flask Gunicorn import and binding
- Gunicorn worker and deployment documentation
- Python WSGI interface
- Current PyMySQL package and authentication instructions
- PyMySQL query parameters and commits
- Systemd execution and credential settings
- Systemd unit start and restart behaviour
- MySQL table and runtime grants
- MySQL transaction and commit statements
- HTTP status and redirect semantics