Lecture 3
Practical examples of AI-assisted development in Flask APIs, library integration, documentation, and data analysis
This work is licensed under CC BY-NC-SA 4.0
© Way-Up 2025
# Sample of AI-generated code
from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todos.db'
app.config['JWT_SECRET_KEY'] = 'your-secret-key' # Change in production!
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=1)
jwt = JWTManager(app)
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
tasks = db.relationship('Task', backref='owner', lazy=True)
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.String(200))
completed = db.Column(db.Boolean, default=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# ... authentication routes and task CRUD endpoints would follow
# AI recommended WeasyPrint and provided this integration code
from django.http import HttpResponse
from django.template.loader import render_to_string
from weasyprint import HTML, CSS
from weasyprint.text.fonts import FontConfiguration
def generate_invoice_pdf(request, order_id):
# Get the order from the database
order = Order.objects.get(id=order_id)
# Render the HTML template with context
html_string = render_to_string('invoices/invoice_template.html', {
'order': order,
'company_name': 'Your Company',
'company_address': '123 Business St, City',
'company_logo_url': request.build_absolute_uri('/static/images/logo.png'),
})
# Configure WeasyPrint with fonts
font_config = FontConfiguration()
css = CSS(string='''
@page { margin: 1cm; }
body { font-family: 'Helvetica', sans-serif; }
.invoice-table { width: 100%; border-collapse: collapse; }
.invoice-table th, .invoice-table td { border: 1px solid #ddd; padding: 8px; }
''', font_config=font_config)
# Generate PDF
html = HTML(string=html_string, base_url=request.build_absolute_uri('/'))
pdf = html.write_pdf(stylesheets=[css], font_config=font_config)
# Create HTTP response with PDF
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = f'filename="invoice_{order_id}.pdf"'
return response
# Original code without docstrings
def process_time_series(data, window_size=10, method='mean', min_periods=None):
if method not in ['mean', 'median', 'min', 'max', 'std']:
raise ValueError(f"Method {method} not supported")
if min_periods is None:
min_periods = window_size // 2
if method == 'mean':
return data.rolling(window=window_size, min_periods=min_periods).mean()
elif method == 'median':
return data.rolling(window=window_size, min_periods=min_periods).median()
elif method == 'min':
return data.rolling(window=window_size, min_periods=min_periods).min()
elif method == 'max':
return data.rolling(window=window_size, min_periods=min_periods).max()
elif method == 'std':
return data.rolling(window=window_size, min_periods=min_periods).std()
# AI-generated documented version
def process_time_series(data, window_size=10, method='mean', min_periods=None):
"""
Process time series data using a rolling window operation.
Parameters
----------
data : pandas.Series or pandas.DataFrame
The time series data to process.
window_size : int, default 10
Size of the rolling window.
method : {'mean', 'median', 'min', 'max', 'std'}, default 'mean'
The statistical method to apply to the rolling window.
min_periods : int, optional
Minimum number of observations required to have a value.
If None, defaults to window_size // 2.
Returns
-------
pandas.Series or pandas.DataFrame
Processed time series data with the same shape as input.
Raises
------
ValueError
If the specified method is not supported.
Examples
--------
>>> import pandas as pd
>>> data = pd.Series([1, 2, 3, 4, 5])
>>> process_time_series(data, window_size=3, method='mean')
0 NaN
1 NaN
2 2.0
3 3.0
4 4.0
dtype: float64
"""
if method not in ['mean', 'median', 'min', 'max', 'std']:
raise ValueError(f"Method {method} not supported")
if min_periods is None:
min_periods = window_size // 2
if method == 'mean':
return data.rolling(window=window_size, min_periods=min_periods).mean()
elif method == 'median':
return data.rolling(window=window_size, min_periods=min_periods).median()
elif method == 'min':
return data.rolling(window=window_size, min_periods=min_periods).min()
elif method == 'max':
return data.rolling(window=window_size, min_periods=min_periods).max()
elif method == 'std':
return data.rolling(window=window_size, min_periods=min_periods).std()
from langchain.agents import create_sql_agent
from langchain.agents.agent_toolkits import SQLDatabaseToolkit
from langchain.sql_database import SQLDatabase
from langchain.llms import OpenAI
import matplotlib.pyplot as plt
import pandas as pd
from langchain.tools import Tool
from langchain.agents import initialize_agent
# Connect to database
db = SQLDatabase.from_uri("postgresql://user:password@localhost:5432/customer_db")
llm = OpenAI(temperature=0)
# Create SQL toolkit
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
# Create visualization tool
def create_visualization(data_description, query_result):
"""Creates appropriate visualization based on data and description."""
df = pd.DataFrame(query_result)
if "over time" in data_description.lower() or "trend" in data_description.lower():
plt.figure(figsize=(10, 6))
plt.plot(df.iloc[:, 0], df.iloc[:, 1])
plt.title(f"Trend Analysis: {data_description}")
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig("trend_analysis.png")
return "trend_analysis.png"
elif "comparison" in data_description.lower() or "between" in data_description.lower():
plt.figure(figsize=(10, 6))
plt.bar(df.iloc[:, 0], df.iloc[:, 1])
plt.title(f"Comparison: {data_description}")
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig("comparison_analysis.png")
return "comparison_analysis.png"
# Add more visualization types as needed
return "No visualization created."
viz_tool = Tool(
name="Visualization",
func=create_visualization,
description="Useful for creating visualizations from query results"
)
# Combine tools and create agent
tools = toolkit.get_tools() + [viz_tool]
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
# Example usage
analysis_request = """
I need to understand how our customer retention rates have changed over the last 12 months,
broken down by customer segment. Also, compare the average purchase value between retained
and churned customers. Generate appropriate visualizations and a summary of insights.
"""
result = agent.run(analysis_request)