You will design and build a web-based appointment booking system using Python (Flask) for the backend, HTML/CSS/JavaScript for the frontend, and integrate a basic AI recommendation feature to enhance user experience. You will also learn UI design fundamentals to create a user-friendly interface.
This unit consists of two major components:Individual Exercises
- Listed below. 100/80/60 Quizzes will be given.
Group project (20% of final mark)
- In groups, you will develop a modern web app using Flask and Python. This project will continue throughout the whole unit. Details will be given soon.
You need to be comfortable using HTML and CSS in this unit.
Do the following tutorials:
- To learn HTML/CSS basics: code along with HTML and CSS Crash Course.
- To learn how to use external CSS: read how to include an external CSS file. For this unit, all CSS must be included in an external CSS file (separation of languages). The previous video does not do this, rather it shows you how to add CSS to the top of the HTML document.
- To learn responsive design: code along with Simple Responsive Design.
Lesson in class: How to utilize these resources now that you understand HTML, CSS and responsive design.
Useful HTML Resources- Valid HTML5 document (Explanation)
- Intro to HTML 5 Tutorials at w3Schools.
- HTML Validator
- HTML Reference
Flask is a lightweight, flexible, and free Python web framework that's commonly used to build web applications, APIs, and microservices. It's considered a microframework because it provides a minimal core set of functionalities and relies on extensions for more advanced features. Flask is suitable for both beginners and experienced developers, making it a popular choice for web development projects.
Jinja2 is a powerful and popular template engine for the Python programming language. It allows you to create dynamic HTML, XML, or other markup formats by embedding placeholders (called variables or tags) in a template file, which are then replaced with actual data at runtime.
Complete these steps- Install the VSCode Extension "Python" from Microsoft
- Install flask: in the command line type
py -m pip install flask - Watch and code along with this Flask tutorial playlist
- Note: To run a Flask App in VS Code:
- Using windows command line, run the python flask app. This starts the local web server from the folder containing the app.
If everything goes well, it will look something like this:
H:\Documents\CompSci 12\Flask Project> py myflaskapp.py * Serving Flask app 'myflaskapp' * Debug mode: on WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000 Press CTRL+C to quit * Restarting with stat * Debugger is active! * Debugger PIN: 141-699-995 - Go to a browser and type
http://127.0.0.1:5000/. - This should show your current app running.
- Using windows command line, run the python flask app. This starts the local web server from the folder containing the app.
If everything goes well, it will look something like this:
Overview
In this project, you will build a Flask web application that learns from study habits and generates personalized study recommendations.
You will build the app using Flask and Jinja2. Your app will allow a user to log study sessions using a web form and store the data in a JSON file.
Things you need to know:- w3 schools tutorial on HTML Forms
- How to Use Web Forms in a Flask App
- Watch What is JSON?
- Reading and Writing JSON to a file in Python:
- Read Reading and Writing Json to a File in Python OR
- Watch and program with: How To Use JSON In Python AND Watch Reading and Writing to Files from Python
- Getting Started with a Jinja2 Template
1. HTML Form
Create an HTML form with the following fields:
- Subject (Finite List of Subjects) - drop list of subjects
- Duration (minutes) - discrete time durations (30, 45, 60, 90, 120) drop list, radio buttons or discrete slider
- Time of day (Morning, Afternoon, Evening, Night) - drop list or radio buttons
- Mood / energy level (Low, Medium, High) - drop list or radio buttons
- Whether the session was effective (Yes / No) - radio buttons
- A Submit button
The form should send the data to your Flask server using POST.
2. Flask Routing & Form Handling
Your Flask app must:
- Include a route that displays the form
- Include a route that processes the submitted data
- Capture all the form values correctly (subject, duration, time of day, mood, effective)
3. Save Sessions to a JSON File
When a user submits the form, save the session to a JSON file called: study_sessions.json
In a future version of this assignment, the data will be used to train a decision tree classifier, which is better trained with numerical data instead of string data. Therefore store each value for duration, time_of_day, mood and effective, as an integer. We will also be using this Machine Learning model to make predictions, are predictions will be faster, and more realistic, with meaningful options for duration (30, 45, 60, 90, 120).
Each entry will use this exact structure:
{"subject": int, "duration": int, "time_of_day": int, "mood": int, "effective": int}
Every time a new sessions is logged:
- Load existing appointments from the JSON file
- Append the new appointment
- Write the updated list back to the file
4. Display All Study Sessions
After a study session is added, load a new page that:
- Uses Jinja2 to loop through the list of entries.
It might look something like:
{% for s in sessions %} <li>{{ s.subject }}: {{ s.duration }} minutes in the {{ s.time_of_day }}, mood: {{ s.mood }}, Effective: {{s.effective}} </li> {% endfor %} - Improve the look, and displays all saved sessions in a clear list or table with words replacing the numerical values of subject, time_of_day, mood, and effectiveness.
Assessment (Total: 20 marks)
1. HTML Form (5 marks)
- 5 marks – Form includes required elements, and a Submit button; labels are clear; layout is clean and fully functional.
- 4 marks – Form works with one minor issue (missing label, minor formatting flaw).
- 2–3 marks – Form loads but is incomplete or somewhat unclear.
- 1 mark – Form is mostly non-functional or missing major elements.
- 0 marks – No usable form.
2. Flask Routing & Form Handling (5 marks)
- 5 marks – Routes are properly set up; form POST request is handled correctly; input values are captured with no errors.
- 4 marks – Routing works with minor flaws (naming, limited validation, small logic issues).
- 2–3 marks – Basic form-handling works but may be inconsistent or partially incorrect.
- 1 mark – Attempt made, but form data is not captured correctly.
- 0 marks – Routes do not function; no form processing.
3. JSON File Storage (exact structure required) (5 marks)
JSON structure must match exactly as described.
- 5 marks – App loads existing JSON data, appends the new session, and writes the updated list back correctly in the required structure.
- 4 marks – JSON storage works with a small issue (minor formatting inconsistency, small structural issue).
- 2–3 marks – JSON file is used but has errors (overwriting, wrong keys, partial data loss).
- 1 mark – File is created but not written/loaded correctly.
- 0 marks – No JSON file interaction.
4. Displaying Sessions with Jinja2 (5 marks)
- 5 marks – App loads all sessions from the JSON file and displays them clearly using a Jinja2 loop.
- 4 marks – Data displays correctly with minor formatting issues.
- 2–3 marks – Some sessions display, but output is incomplete or messy.
- 1 mark – Attempt made but display has major errors.
- 0 marks – No session list displayed.
In Python, scikit-learn can be used to train a simple ML models including linear regression and classification.
Benefits of the Scikit Model- No need for cloud APIs or authentication
- All runs locally — safe and fast
- Small data sets are enough
Watch Decision and Classification Trees, Clearly Explained
Add a Decision Tree Classifier
In this assignment, you will use real machine learning (ML) to help your app make smarter recommendations over time.
Your goal is to use the historical appointment data your users have submitted to train a Decision Tree Classifier. It turns your project into an app that becomes smarter the more it is used.
Read about How a Decision Tree Classifier works.
Why Not Just Use Rule Based Logic (aka If-Statements, Sorts etc)?
At first, this problem looks easy to solve with rules.
For example:
- “If I’m tired, studying doesn’t work.”
- “Math is better in the morning.”
But real study habits are more complicated.
The Problem With Rules
Every new factor multiplies the number of cases you need to handle:
- Subject
- Duration
- Time of day
- Mood
With just a few options, you already have hundreds of combinations.
If your habits change, you must:
- Rewrite rules
- Add new conditions
- Debug logic
That’s not scalable.
What a Decision Tree Does Differently
A DecisionTreeClassifier:
- Learns patterns automatically from data
- Updates its logic when new data is added
- Makes predictions on situations it has never seen before
You don’t tell it what works. It figures that out.
Why This Matters
This is the difference between:
- Programming instructions (traditional code)
- Programming learning systems (machine learning)
If-statements follow rules. Decision trees discover rules.
That difference is why machine learning exists — and why it is required for this assignment.
Install Scikit
Install scikit:
py -m pip install scikit-learn
Prepare Your Data
Transform your session data into training data (X)
For example, sessions become:
X = [
[2, 45, 3, 4],
[1, 30, 1, 2],
[3, 60, 4, 5]
]
Create labels (y)
y = [1, 0, 1]
Loading This Data From JSON
Example list of entries:
data = [
{"subject":2, "duration":45, "time_of_day":3, "mood":4, "effective":1},
{"subject":1, "duration":30, "time_of_day":1, "mood":2, "effective":0}
]
Convert to X and y:
X = []
y = []
for entry in data:
X.append([
entry["subject"],
entry["duration"],
entry["time_of_day"],
entry["mood"]
])
y.append(entry["effective"])
Train your model
Read about How to code a DecisionTreeClassifier using SciKitLearn.
from sklearn.tree import DecisionTreeClassifier model = DecisionTreeClassifier() model.fit(X, y)
Visualize the trained model by showing the decision tree
from sklearn.tree import export_text feature_names = ["subject", "duration", "time_of_day", "mood"] tree_rules = export_text(model, feature_names=feature_names) print(tree_rules)
Add This to Your Flask App
- Load study session data from your JSON file
- Convert it into X and y
- Train your DecisionTreeClassifier
- Print the Decision Tree rules in a preformatted text element under the list of all study sessions.
The key idea: Your model should improve as more appointments get booked.
Assessment (Total: 10 marks)
ML Integration (5 marks)
- 9-10 marks – Correctly loads JSON appointment history, extracts features, creates labels, trains a model, and uses it in Flask, shows Decision Tree; updates as data grows.
- 7-8 marks – Model trains and works but has minor logic or feature-extraction issues.
- 3–6 marks – Attempts training but model is incorrect or inconsistently used.
- 1-2 marks – Minimal attempt; model is not functional.
- 0 marks – No ML integration.
ML-Based Recommendations (No Rules Allowed)
Your app will generate recommendations only using model predictions. We will be using "What-if" predictions, which are essentially brute-force.
The recommendations must:
- Be based on the trained DecisionTreeClassifier
- Adapt automatically as more data is collected
- Change without modifying any recommendation logic code
Learn the following skills to complete the required additions to Study Buddy.
Skill 1: How to Make a Prediction for Selected Subject/Duration/Time of Day/Mood
In scikit-learn, model.predict(X) is a fundamental method used to generate predicted outputs (targets) for a given set of input data X after the model has been trained.
model.predict(X) a 2D list, even for one item. For example, if subject=2, duration=50, time_of_day=3, and mood=4, pass it [[2, 50, 3, 4]]:
new_session = [[2, 50, 3, 4]] # subject=2, duration=50, time_of_day=3, mood=4 prediction = model.predict(new_session)[0] print(prediction)Output will be
1 for effective or 0 for ineffective.
Skill 2: Get Probability Instead of Just yes/no
In scikit-learn, the predict_proba() function is designed to give the probability estimates for each class label in a classification task. This is particularly useful in applications where understanding the confidence of a prediction is as important as the prediction itself.
probs = model.predict_proba(new_session) print(probs)Example output:
[[0.25 0.75]] meaning 25% not effective, 75% effective.
This gives you the ability to give recommendations like "This study session has a 75% chance of being effective."
Note: If you have less than 100 data points, or data that lacks variability, it may only give 0% and 100% values. The more complex your decision tree, the more likely these values will be interesting.
Skill 3: Get Specific Recommendations
For a given subject, try all variations to find better options
recommendations = []
# try all options for a current["subject"] and current["mood"]
for duration in [30, 45, 60, 90]:
for time in [1, 2, 3, 4]: # morning, afternoon, evening, night
test_session = [[
current["subject"],
duration,
time,
current["mood"]
]]
result = model.predict(test_session)[0]
if result == 1:
recommendations.append((duration, time))
This might output [(60, 3), (60, 4), (90, 3)] which would suggest that for this subject and mood, studying 60-90 min in the evening is best.
Skill 4: Use Probabilities for Smarter Recommendations
best_options = []
# try all options for a given subject and mood
for duration in [30,45,60,90]:
for time in [1,2,3,4]:
probs = model.predict_proba([[current["subject"], duration, time, current["mood"]]])
effectiveness_chance = probs[0][1] # probability of effective
best_options.append((duration, time, effectiveness_chance))
# sort by highest success
best_options.sort(key=lambda x: x[2], reverse=True)
print(best_options[:3])
This might output [(60, 3, 0.91), (90, 3, 0.88), (60, 4, 0.82)] and the recommendation could be "For this subject and mood, your best study session is 60 minutes in the evening (91% effective)".
Skill 5: Analyze Feature Importance
After you've trained the model model.fit() use model.feature_importances_ to figure out which features mattered most and provide insight to the user. The model.feature_importances_ attribute provides a score for each input feature based on its contribution to the model's predictions.
In scikit-learn, this attribute is available in tree-based models like Random Forest and Decision Tree.
features = ["subject", "duration", "time_of_day", "mood"]
importances = model.feature_importances_
for name, score in zip(features, model.feature_importances_):
print(name, ":", round(score, 3))
Sample Output:
subject : 0.102 duration : 0.547 time_of_day : 0.251 mood : 0.1Use this to show things like:
- Duration mattered more than time of day.
- Mood had little impact in my data/
What To Add To Your Study Buddy App:
1. Study Session Analysis
Add to your app a new route that has a form that allows the user to enter hypothetical study conditions:
- Subject
- Duration
- Time of day
- Mood / energy level
The app responds with the predicted effectiveness (%) of the user’s current study session.
Predicted Effectiveness: 22%
2. What If
Add to your app a new route that has a form that allows the user to enter a subject and a mood.
The app then shows the top 3 most effective study session combinations generated using what-if predictions (duration + time of day), including predicted probability
Best Study Sessions for Math when mood is low: 60 minutes in the evening — 91% effective 90 minutes in the evening — 88% effective 60 minutes at night — 82% effective
3. Feature Importance
Just above the decision tree, show what the model has learned from your data.
Duration was the most important factor (0.55) Time of day was second most important (0.25) Mood had little impact (0.10) Subject had minimal impact (0.10)
Assessment (/10)
All required functionality added and is working. Be able to show different results for Study Session Analysis and What If.
Step 1: Watch and program along with
It covers:- Additional SciKit Algorithms
- Assessing accuracy of predictions
- Saving your model
Step 2: Complete this Exercise
In this exercise, you’ll build a new feature in your Flask app to test how accurate your AI model from Study Buddy Assignment 1 is using the data you've collected in study_sessions.json.
- Use 20% of your study session data as test data
- Train your AI model on the remaining 80%
- Show the accuracy of the predictions
- Display the result on a web page
app.py with a New Route- Open your
app.pyfile. - Add this import at the top if it isn’t already there:
from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import pandas as pd # Tool for encoding string labels into numbers from sklearn.preprocessing import LabelEncoder - Define the following variables if you plan on using
LabelEncoder# Encoders to convert categorical values into numeric labels mood_encoder = LabelEncoder() time_encoder = LabelEncoder() subject_encoder = LabelEncoder() - Then scroll down and add this new route:
@app.route('/test-ai')
def test_ai():
sessions = load_sessions()
if len(sessions) < 10:
flash("Not enough data to test the model. Please log at least 10 sessions.")
return redirect('/log')
# Convert to DataFrame
df = pd.DataFrame(sessions)
# ONLY USE THIS IF YOUR DATA IS STRING DATA: Encode text columns into numbers
# Note: you may have named your features differently
df['mood'] = mood_encoder.fit_transform(df['mood'])
df['time_of_day'] = time_encoder.fit_transform(df['time_of_day'])
df['subject'] = subject_encoder.fit_transform(df['subject'])
df['effective'] = df['effective'].map({"Yes": 1, "No": 0})
# Split into 80% train and 20% test
X = df[['duration', 'time_of_day', 'mood', 'subject']]
y = df['success']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train and test the model
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
accuracy = round(accuracy_score(y_test, predictions) * 100, 2)
return render_template('test_ai_accuracy.html', accuracy=accuracy, total=len(sessions))
Create a New TemplateCreate a file called test_ai_accuracy.html in your templates/ folder:
<!DOCTYPE html>
<html>
<head>
<title>AI Accuracy Test</title>
</head>
<body>
<h1>AI Model Accuracy Report</h1>
<p>Tested on 20% of {{ total }} logged sessions.p>
<h2>Accuracy: {{ accuracy }}%h2>
<p><a href="{{ url_for('home') }}">Back to Home</a></p>
</body>
</html>
Try It Out- Make sure you have at least 10 study sessions logged.
- Run your Flask app.
- Visit
/test-aiin your browser (e.g.http://127.0.0.1:5000/test-ai) - You should see a page like this:
AI Model Accuracy Report
Tested on 20% of 25 logged sessions.
Accuracy: 84.00%
Add a Link to Your HomepageIf you want a link from your home page:
<p><a href="{{ url_for('test_ai') }}">Evaluate AI Accuracy</a></p>
What’s Going On?- 80% of your data is used to train the model.
- 20% is used to test how well the model performs on new data.
- You see how often the model predicted correctly — that’s the accuracy.
You now have a simple way to measure how effective your DecisionTreeClassifier is using real user data.
Step 3: Test Another Machine Learning Model and Compare Results
You have already trained and used a Decision Tree model. In this part of the assignment, you will train a second machine learning model using the same study session data and compare the results.
- Research other models: Random Forest, Logistic Regression, K-Nearest Neighbors (KNN)
- After researching them, choose ONE of these models to implement in your project. Note: Last year, many got the same results when comparing Random Forest and Decision Trees. I suggest not using Random Forest.
- Train a second model using the same dataset you used for your Decision Tree.
- Your new program should now have: a Decision Tree AND a second ML Model
- Generate Recommendations: Use both models to generate recommendations for effective study sessions. Examples:
best time of day to study,
best session length,
moods associated with effective studying,
subjects where success rates are highest.
Display recommendations from BOTH models on your website so they can be compared.
Example:
Model Recommendation ----- ---------------- Decision Tree Short evening math sessions are most effective KNN Medium-length evening sessions work best when mood is focused
- Compare Accuracy: Evaluate how accurate each model is.
You must:
- split your data into training and testing sets,
- calculate the accuracy score for: the Decision Tree and your second model,
- display both accuracy scores on your website.
Example:
Model Accuracy ------ --------- DecisionTree 78% Logistic Regression 84%
How Much Data Does Machine Learning Actually Need?
In previous assignments, you trained machine learning models and used them to generate predictions and recommendations.
In this assignment, you will investigate an important real-world machine learning question:
How much data is needed before a machine learning model becomes reasonably accurate and stable?
You will experimentally test how dataset size affects model performance.
This assignment is about:
- experimentation
- analysis
- comparing models
- understanding the relationship between data and accuracy
You are no longer simply using machine learning.
You are now studying how machine learning behaves.
Your Task
You will:
- Train two different machine learning models
- Train them on different dataset sizes
- Measure and compare their accuracy
- Determine approximately when each model becomes “reasonably stable”
- Analyze which model performs better with limited data
Models to Compare
Use the same two models from Study Buddy 4.
Examples:
DecisionTreeClassifierRandomForestClassifier
(Use the exact models you previously compared.)
Step 1 — Create Multiple Dataset Sizes
You must train your models using multiple dataset sizes. 1 row = 1 study session
Use this generated data for this experiment: Study Sessions 500.json.
Use at least:
- 10 rows
- 25 rows
- 50 rows
- 100 rows
- 150 rows
- 200 rows
- increment by 50 until all available rows
You may test additional sizes if desired.
Important
Do NOT manually create separate datasets by hand.
Instead, use:
- random sampling
Example:
# randomly select a small subset (size 25) of your data
X_sample, _, y_sample, _ = train_test_split(
X,
y,
train_size=25,
random_state=42
)
Step 2 — Train and Test Both Models
For EACH dataset size:
- Train both models
- Test both models
Record:
- training accuracy - training accuracy is measured by checking how well the model predicts the SAME data it was trained on
- testing accuracy
Example:
train_accuracy = model.score(X_train, y_train)
test_accuracy = model.score(X_test, y_test)
print("Training Accuracy:", train_accuracy)
print("Testing Accuracy:", test_accuracy)
X_train, y_train- data used to train the modelX_test, y_test- unseen data used to evaluate the model
You should end up with a table similar to this:
| Dataset Size | DT Train | DT Test | RF Train | RF Test | | ------------ | -------- | ------- | -------- | ------- | | 10 | 1.00 | 0.52 | 0.95 | 0.55 | | 25 | 0.96 | 0.67 | 0.91 | 0.71 | | 50 | 0.89 | 0.79 | 0.87 | 0.82 | | 100 | 0.85 | 0.83 | 0.86 | 0.85 | | Full dataset | 0.84 | 0.85 | 0.85 | 0.86 |
(Your results will be different.)
Step 3 — Create Graphs
Create at least one graph showing how accuracy changes as dataset size increases.
Your graph(s) should help answer questions such as:
- Which model improves faster?
- Which model stabilizes first?
- Does additional data eventually stop helping much?
You may use:
- Excel or Google Sheets
- matplotlib
- pandas plotting
- another graphing library
Step 4 — Analyze the Results
In a Google Doc, answer the following questions:
- Compare the overall performance of the two models. Cite specific metrics from your final runs to justify which model achieved better results.
- Analyze how each model handled small datasets. Contrast their initial performance and explain how the limitations of small data samples affected each algorithm differently.
- Examine the learning curves as data scales. Which model demonstrated the highest growth rate as more data was added, and what does this suggest about how that specific algorithm scales?
- Identify the stability threshold. Pinpoint the approximate dataset size where each model’s performance plateaued or stabilized. What specific trend in your visualization indicates this stability?
- Evaluate the models for overfitting on restricted data. Look closely at your small dataset trials. What evidence (such as gaps between training and testing metrics) suggests that either model was overfitting?
- Identify the point of diminishing returns. Did adding more data eventually yield only marginal performance gains? Use your data points to explain where this slowdown occurred and why it happens in machine learning.
- Select a deployment model for the Study Buddy application. Based entirely on your findings, justify which model you would choose. Address the specific constraints of the application (e.g., performance vs. dataset size) to support your decision.
For these questions, a simple choice or one-sentence answer reflects an Emerging depth of analysis. To achieve a Proficient or Extending evaluation, every answer must follow the Claim-Evidence-Reasoning model: State your conclusion, cite specific data points or metrics from your charts, and explain the technical reason behind the behavior.
Important Concept
There is usually NO exact “minimum amount” of data required for machine learning.
Instead, you are estimating:
the approximate dataset size at which model performance becomes reasonably stable.
This is a scientific investigation, not a search for one exact answer.
What You Should Notice
As dataset size increases:
- accuracy may improve quickly at first
- then improve more slowly
- eventually level off
Different models may:
- require different amounts of data
- react differently to small datasets
- overfit differently
Assessment
You must PRINT and submit:
- The table
- Graph(s) - At least one graph visualizing:
- dataset size
- model accuracy
- Questions AND Answers
In previous assignments, your machine learning model was retrained every time the Flask server restarted. In a real-world application, this is inefficient and wastes processing time.
For this assignment, you will redesign your Study Buddy machine learning system so that:
- the trained model is saved locally
- the application loads the saved model when the server starts
- the model is only retrained when new study session data is added
You are not being given step-by-step instructions for this assignment. Part of the challenge is researching how Flask applications and machine learning systems handle persistent models and updating data.
Your job is to investigate, experiment, and build a working solution.
Assignment Requirements
1. Save the Trained Model LocallyAfter training the model:
- save the trained machine learning model to a file on the server
- the model file should persist after the Flask app stops running
When the server restarts:
- your application should load the saved model instead of retraining immediately
Your application should determine when retraining is necessary. Retraining is only required if a new submission is added.
If no data has changed, the previously saved model should continue to be used.
3. Continue Making PredictionsYour application must still: predict whether study sessions are effective, generate recommendations, and display results on the website.
The prediction system should work whether the model was: freshly trained or loaded from storage
4. Demonstrate Understanding Through ResearchYou are expected to independently research topics related to:
- Flask application structure
- persistent storage of machine learning models
- retraining workflows
- scikit-learn model reuse
- detecting when data changes
- loading and saving files in Python
You may use:
- official documentation
- tutorials
- videos
- forums
- AI tools
However, you must understand and be able to explain your solution.
The final step to Study Buddy it to put it online. Use the instructions below to host it at Python Anywhere.
How to publish a Flask app to Python Anywhere
Watch Easy Flask App Deployment with PythonAnywhere | Beginner's Step-by-Step Guide. OR follow these instructions:1. Prepare Your Flask App
Let’s assume you have a basic app structure like this:
myapp/
├── app.py
├── data.json
├── templates/
│ └── index.html
└── static/
Example app.py:
from flask import Flask, request, jsonify
import json
import os
app = Flask(__name__)
DATA_FILE = os.path.join(os.path.dirname(__file__), 'data.json')
@app.route('/')
def index():
return 'Hello from Flask!'
@app.route('/add', methods=<'POST'>)
def add_data():
new_entry = request.get_json()
with open(DATA_FILE, 'r') as f:
data = json.load(f)
data.append(new_entry)
with open(DATA_FILE, 'w') as f:
json.dump(data, f, indent=4)
return jsonify({'status': 'success', 'data': new_entry})
2. Sign Up and Create a Web App on PythonAnywhere
- Go to https://www.pythonanywhere.com and sign up or log in.
- On the Dashboard, click Web > Add a new web app.
- Choose Manual configuration > Flask > your Python version (e.g., 3.10).
3. Upload Your Files
- In the Files tab, create a folder (e.g.,
myapp/) and upload yourapp.py,data.json,templates/, andstatic/folders/files. - Make sure
data.jsonhas write permissions (you can leave it as-is; you’re the only user).
4. Configure the WSGI File
Go to Web > [your app ] > WSGI configuration file.
Edit the file to look like this (adjust the path to your folder):
import sys
import os
path = '/home/yourusername/myapp'
if path not in sys.path:
sys.path.append(path)
from app import app as application
5. Reload and Test
- Go back to the Web tab and click Reload.
- Visit your app’s URL (e.g.,
yourusername.pythonanywhere.com) to confirm it’s running. - Send a POST request to
/add(using Postman or JavaScript) to test the JSON writing.
Important Notes
- Free PythonAnywhere accounts cannot receive external HTTP requests to
/addunless you're making the request from a client hosted on PythonAnywhere (e.g., your own JS frontend on the same domain). - PythonAnywhere allows write access to files in your home directory, so writing to
data.jsonis okay. - You must avoid using absolute paths; use
os.path.join(os.path.dirname(__file__), 'data.json')to make sure it works on their file system.
Please take the time to complete the following course evaluation. It will be used for future course offerings.
Course Evaluation