Adding source code files for Chapter 10

This commit is contained in:
muassif
2021-06-30 12:36:33 +04:00
committed by GitHub
parent 360b7f1420
commit 4d0965b634
19 changed files with 640 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
#app1.py: routing in a Flask application
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
@app.route('/greeting')
def greeting():
return 'Greetings from Flask web app!'
@app.route('/hello/<name>')
def hello_user(name):
return f'Hello {name}!'
if __name__ == '__main__':
app.run()
+22
View File
@@ -0,0 +1,22 @@
#app2.py: map request with method type
from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['GET'])
def req_with_get():
return "Received a get request"
@app.post('/submit')
def req_with_post():
return "Received a post request"
@app.route('/submit2', methods = ['GET', 'POST'])
def both_get_post():
if request.method == 'POST':
return "Received a post request 2"
else:
return "Received a get request 2"
if __name__ == '__main__':
app.run()
+17
View File
@@ -0,0 +1,17 @@
#app3.py: rendering static and dynamic contents
from flask import Flask, render_template, url_for, redirect
app = Flask(__name__)
@app.route('/hello')
def hello():
hello_url = url_for ('static', filename='app3.html')
return redirect(hello_url)
@app.route('/greeting')
def greeting():
msg = "Hello from Python"
return render_template('app3.html', greeting=msg)
if __name__ == '__main__':
app.run()
+25
View File
@@ -0,0 +1,25 @@
#app4.py: extracting parameters from different requests
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/hello')
@app.route('/hello/<fname> <lname>')
def hello_user(fname=None, lname=None):
return render_template('app4.html', name=f"{fname} {lname}")
@app.get('/submit')
def process_get_request_data():
fname = request.args['fname']
lname = request.args.get('lname', '')
return render_template('app4.html', name=f"{fname} {lname}")
@app.post('/submit')
def process_post_request_data():
fname = request.form['fname']
lname = request.form.get('lname','')
#lname = request.form['lname']
return render_template('app4.html', name=f"{fname} {lname}")
if __name__ == '__main__':
app.run()
+56
View File
@@ -0,0 +1,56 @@
#app5.py: interacting with db for create, delete and list objects
from flask import Flask, request, render_template, redirect
from flask_sqlalchemy import SQLAlchemy
from werkzeug.exceptions import HTTPException
import json
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///student.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
grade = db.Column(db.String(20), nullable=True)
def __repr__(self):
return '<Student %r>' % self.name
@app.get('/list')
def list_students():
student_list = Student.query.all()
return render_template('app5.html', students=student_list)
@app.get('/add')
def add_student():
fname = request.args['fname']
lname = request.args.get('lname', '')
grade = request.args.get('grade','')
student = Student(name=f"{fname} {lname}", grade=grade)
db.session.add(student)
db.session.commit()
return redirect("/list")
@app.get('/delete/<int:id>')
def del_student(id):
todelete = Student.query.filter_by(id=id).first()
db.session.delete(todelete)
db.session.commit()
return redirect("/list")
@app.errorhandler(HTTPException)
def page_not_found(error):
print(error)
response = error.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": error.code,
"name": error.name,
"description": error.description,
})
return response
if __name__ == '__main__':
app.run()
+36
View File
@@ -0,0 +1,36 @@
#app6.py: error and exception handling
import json
from flask import Flask, render_template, abort
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
@app.get('/')
def hello():
return 'Hello World!'
@app.route('/greeting')
def greeting():
x = 10/0
return 'Greetings from Flask web app!'
@app.errorhandler(404)
def page_not_found(error):
return render_template('error404.html'), 404
@app.errorhandler(500)
def internal_error(error):
return render_template('error500.html'), 500
@app.errorhandler(HTTPException)
def generic_handler(error):
error_detail = json.dumps({
"code": error.code,
"name": error.name,
"description": error.description,
})
return render_template('error.html', err_msg=error_detail), error.code
if __name__ == '__main__':
app.run()
+10
View File
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1> Hello World from a static file </h1>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic contents demo</title>
</head>
<body>
{% if greeting %}
<h1> {{ greeting }}!</h1>
{% endif %}
</body>
</html>
+16
View File
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic contents demo</title>
</head>
<body>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, whoever you are!</h1>
{% endif %}
</body>
</html>
+30
View File
@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Students from database</title>
</head>
<body>
<h2>Students</h2>
{% if students|length > 0 %}
<table>
<thead>
<tr>
<th scope="col">SNo</th>
<th scope="col">name</th>
<th scope="col">grade</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
<td scope="row">{{student.id}}</td>
<td>{{student.name}}</td>
<td>{{student.grade}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</body>
</html>
+10
View File
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error page</title>
</head>
<body>
<h3>{{ err_msg }}</h3>
</body>
</html>
+10
View File
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error page</title>
</head>
<body>
<h3>The page you request does not exist. Please check your URL.</h3>
</body>
</html>
+10
View File
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error page</title>
</head>
<body>
<h3>There is an internal server problem. Please try again later.</h3>
</body>
</html>