Skip to content

Commit a451ab9

Browse files
authored
Add files via upload
1 parent d8d45d2 commit a451ab9

File tree

7 files changed

+202
-0
lines changed

7 files changed

+202
-0
lines changed

readme.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
## simple_flask_server
2+
- server1.py: Simple Flask server
3+
- server2.py: Flask server with set response status code
4+
- server3.py: Flask server processing input arguments
5+
- server4.py: Flask server with dynamic URLs (GET /count, GET /person/id, and DELETE /person/id endpoints)
6+
- server5.py: Flask server parsing JSON from request body
7+
- server6.py: Flask server with custom error handler
8+
9+
### Required framework:
10+
- Flask
11+
12+
(Practice projects as part of the IBM course “Developing AI Applications with Python and Flask”.)

server1.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Basic structure of a Flask server
2+
3+
# Import the Flask class from the flask module
4+
from flask import Flask
5+
6+
# Create an instance of the Flask class, passing in the name of the current module
7+
app = Flask(__name__)
8+
9+
# Define a route for the root URL ("/")
10+
@app.route('/')
11+
def index():
12+
# Function that handles requests to the root URL
13+
# Return a plain text response
14+
return "Hello, Flask!"
15+
16+
# Run the server
17+
if __name__ == '__main__':
18+
app.run(debug=True)

server2.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Flask server with set response status code
2+
3+
from flask import Flask, make_response
4+
5+
# Create an instance of the Flask class, passing in the name of the current module
6+
app = Flask(__name__)
7+
8+
# Define a route for the root URL ("/")
9+
@app.route("/")
10+
def index():
11+
# Function that handles requests to the root URL
12+
# Return a plain text response
13+
return "Hello, Flask!"
14+
15+
# Define a route for the "/no_content" URL
16+
@app.route("/no_content")
17+
def no_content():
18+
# Create a dictionary with a message and return it with a 204 No Content status code
19+
return ({"message": "No content found"}, 204)
20+
21+
# Define a route for the "/exp" URL
22+
@app.route("/exp")
23+
def index_explicit():
24+
# Create a response object with the message "Hello, Flask!"
25+
resp = make_response({"message": "Hello, Flask!"})
26+
# Set the status code of the response to 200
27+
resp.status_code = 200
28+
# Return the response object
29+
return resp
30+
31+
# Run the server
32+
if __name__ == '__main__':
33+
app.run(debug=True)

server3.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Flask server processing input arguments
2+
3+
from flask import Flask, request
4+
app = Flask(__name__)
5+
6+
# The data is generated with Mockaroo (https://www.mockaroo.com/)
7+
data = [{"id":1,"first_name":"Baxy","last_name":"Escalera","email":"[email protected]","ip_address":"107.160.207.177"},
8+
{"id":2,"first_name":"Marigold","last_name":"Tillyer","email":"[email protected]","ip_address":"80.162.216.11"},
9+
{"id":3,"first_name":"Ware","last_name":"Jenson","email":"[email protected]","ip_address":"117.133.217.112"},
10+
{"id":4,"first_name":"Joline","last_name":"Phette","email":"[email protected]","ip_address":"54.54.173.177"}]
11+
12+
# Create an end point that returns the person’s data to the client in JSON format
13+
@app.route("/name_search")
14+
def name_search():
15+
# Get the argument 'q' from the query parameters of the request
16+
query = request.args.get('q')
17+
# Check if the query parameter 'q' is missing
18+
if not query:
19+
# Return a JSON response with a message indicating 'q' is missing and a 422 Unprocessable Entity status code
20+
return {"message": "Query parameter 'q' is missing"}, 422
21+
# Iterate through the 'data' list to look for the person whose first name matches the query
22+
for person in data:
23+
if query.lower() in person["first_name"].lower():
24+
# If a match is found, return the person as a JSON response with a 200 OK status code
25+
return person
26+
# If no match is found, return a JSON response with a message indicating the person was not found and a 404 Not Found status code
27+
return {"message": "Person not found"}, 404
28+
29+
# Run the server
30+
if __name__ == '__main__':
31+
app.run(debug=True)
32+
33+
# Test: curl -X GET -i -w '\n' "localhost:5000/name_search?q=Joline"

server4.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Flask server with dynamic URLs (GET /count, GET /person/id, and DELETE /person/id endpoints)
2+
3+
from flask import Flask, request
4+
app = Flask(__name__)
5+
6+
data = [{"id":"3b58aade-8415-49dd-88db-8d7bce14932a","first_name":"Baxy","last_name":"Escalera","email":"[email protected]","ip_address":"107.160.207.177"},
7+
{"id":"d64efd92-ca8e-40da-b234-47e6403eb167","first_name":"Marigold","last_name":"Tillyer","email":"[email protected]","ip_address":"80.162.216.11"},
8+
{"id":"66c09925-589a-43b6-9a5d-d1601cf53287","first_name":"Ware","last_name":"Jenson","email":"[email protected]","ip_address":"117.133.217.112"},
9+
{"id":"a3d8adba-4c20-495f-b4c4-f7de8b9cfb15","first_name":"Joline","last_name":"Phette","email":"[email protected]","ip_address":"54.54.173.177"}]
10+
11+
# Create GET /count endpoint
12+
@app.route("/count")
13+
def count():
14+
try:
15+
# Attempt to return a JSON response with the count of items in 'data'
16+
return {"data count": len(data)}, 200
17+
except NameError:
18+
# If 'data' is not defined and raises a NameError
19+
return {"message": "data not defined"}, 500
20+
21+
# Create GET /person/id endpoint
22+
@app.route("/person/<var_name>")
23+
def find_by_uuid(var_name):
24+
# Iterate through the 'data' list to search for a person with a matching ID
25+
for person in data:
26+
# Check if the 'id' field of the person matches the 'var_name' parameter
27+
if person["id"] == str(var_name):
28+
# Return the person as a JSON response if a match is found
29+
return person
30+
31+
# Return a JSON response with a message and a 404 Not Found status code if no matching person is found
32+
return {"message": "Person not found"}, 404
33+
34+
# Create DELETE /person/id endpoint
35+
@app.route("/person/<uuid:id>", methods=['DELETE'])
36+
def delete_by_uuid(id):
37+
# Iterate through the 'data' list to search for a person with a matching ID
38+
for person in data:
39+
# Check if the 'id' field of the person matches the 'id' parameter
40+
if person["id"] == str(id):
41+
# Remove the person from the 'data' list
42+
data.remove(person)
43+
# Return a JSON response with a message confirming deletion and a 200 OK status code
44+
return {"message": f"Person with ID {id} deleted"}, 200
45+
# If no matching person is found, return a JSON response with a message and a 404 Not Found status code
46+
return {"message": "person not found"}, 404
47+
48+
# Run the server
49+
if __name__ == '__main__':
50+
app.run(debug=True)
51+
52+
# Test GET /count endpoint: curl -X GET -i -w '\n' "localhost:5000/count"
53+
# Test GET /person/id endpoint: curl -X GET -i localhost:5000/person/66c09925-589a-43b6-9a5d-d1601cf53287
54+
# Test DELETE /person/id endpoint:
55+
# - Delete: curl -X DELETE -i localhost:5000/person/66c09925-589a-43b6-9a5d-d1601cf53287
56+
# - Check:

server5.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Flask server parsing JSON from request body
2+
3+
from flask import Flask, request
4+
app = Flask(__name__)
5+
6+
data = [{"id":"3b58aade-8415-49dd-88db-8d7bce14932a","first_name":"Baxy","last_name":"Escalera","email":"[email protected]","ip_address":"107.160.207.177"},
7+
{"id":"d64efd92-ca8e-40da-b234-47e6403eb167","first_name":"Marigold","last_name":"Tillyer","email":"[email protected]","ip_address":"80.162.216.11"},
8+
{"id":"66c09925-589a-43b6-9a5d-d1601cf53287","first_name":"Ware","last_name":"Jenson","email":"[email protected]","ip_address":"117.133.217.112"},
9+
{"id":"a3d8adba-4c20-495f-b4c4-f7de8b9cfb15","first_name":"Joline","last_name":"Phette","email":"[email protected]","ip_address":"54.54.173.177"}]
10+
11+
@app.route("/person", methods=['POST'])
12+
def add_by_uuid():
13+
new_person = request.json
14+
if not new_person:
15+
return {"message": "Invalid input parameter"}, 422
16+
# code to validate new_person ommited
17+
try:
18+
data.append(new_person)
19+
except NameError:
20+
return {"message": "data not defined"}, 500
21+
return {"message": f"{new_person['id']}"}, 200
22+
23+
# Run the server
24+
if __name__ == '__main__':
25+
app.run(debug=True)
26+
27+
# Test:
28+
# curl -X POST -i -w '\n' \
29+
# --url http://localhost:5000/person \
30+
# --header 'Content-Type: application/json' \
31+
# --data '{
32+
# "id": "0z7e61b4-6b27-87ed-00eb-0662ac139993",
33+
# "first_name": "Peter",
34+
# "last_name": "Parker",
35+
# "email": "[email protected]",
36+
# "ip_address": "24.54.173.177"
37+
# }'

server6.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Flask server with custom error handler
2+
3+
from flask import Flask
4+
app = Flask(__name__)
5+
6+
@app.errorhandler(404)
7+
def api_not_found(error):
8+
# Custom error handler for 404 Not Found errors
9+
return {"message": "API not found"}, 404
10+
11+
# Run the server
12+
if __name__ == '__main__':
13+
app.run(debug=True)

0 commit comments

Comments
 (0)