Skip to content

Commit 981d203

Browse files
committed
added exercises
1 parent f857397 commit 981d203

File tree

2 files changed

+79
-23
lines changed

2 files changed

+79
-23
lines changed

README.md

Lines changed: 78 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Flask Routes
1+
# Flask Take Home Exercises
22

33
This creates an application instance
44
__name__ is used to determine the root path of the application folder
@@ -22,43 +22,38 @@ def my_first_route():
2222
return "<h1> Hello World! </h1>"
2323
```
2424
You can have multiple routes. So for instance, the code below would run on http://127.0.0.1:5000/route/aria,
25-
"aria" in this case is the parameter name, which can be anything you want. This is taken asn a input into the function my_second_route, and then the name is printed to the screen.
25+
"aria" in this case is the parameter name, which can be anything you want. This is taken as an a input into the function my_second_route, and then the name is printed to the screen.
2626

2727
```python
2828
@app.route('/route/<name>')
2929
def my_second_route(name):
3030
return name
3131
```
3232

33-
**Problem 1: Write a route that takes a first name, last name, and graduating year in the route**
33+
**Problem 1**
34+
**Write a route that takes a first name, last name, and graduating year in the route. If this route is hit, wit print out the line "<firstname> <lastname> will graduate in <graudating_year>"**
3435

3536

36-
So, what are we using Flask for and why are routes useful.
37+
So, what are we using Flask for and why are routes useful ... to build at API.
3738

3839
An API, or Application Programming Interface, is a set of subroutine definitions, protocols, and tools for building application software. It defines communication between various software components.
3940

4041
Lets give an example. Let's say on the frontend you want to display all a list of names that are stored in your database. You are going to send a GET request that will be sent to one of these routes that you define in Flask. The function to handle the route will understand that you are trying to get some information, retrieve it from the database, and set in back to the frontend in a json format.
4142

42-
```python
43-
@app.route('/get_users', methods=['GET'])
44-
def get_all_users():
45-
if request.method == 'GET':
46-
# Accesses the database and gets a list of names stored in the variable called data
47-
# (ignore how you access the database for now, we'll come back to it)
48-
return jsonify({'status': 'success', 'data': ['aria', 'tim', 'varun', 'alex']})
49-
else:
50-
return jsonify({"status": "failed")
51-
```
5243

5344
The GET request is part of a protocol called REST, which stands for Representational State Transfer.
5445

5546
There are many types of requests, put the most important ones are:
56-
GET: gets information from a database
57-
POST: adds information to a database
58-
PUT: modifies information in a database
59-
DELETE: deletes information in a database
6047

61-
From the nnb project, you can see an example of a get request that uses postgress database. Maps.query.all() goes into postgress, finds the table labeled Maps, and gets everything. The data is then put into a list and turned into a json object. If it fails, it will send the correct error message
48+
GET: gets information from a database
49+
50+
POST: adds information to a database
51+
52+
PUT: modifies information in a database
53+
54+
DELETE: deletes information in a database
55+
56+
From the nnb project from last semester, you can see an example of a get request that uses postgress database. Maps.query.all() goes into postgress, finds the table labeled Maps, and gets everything. The data is then put into a list and turned into a json object. If it fails, it will send the correct error message
6257
```python
6358
#Gets all maps
6459
@app.route('/maps', methods=['GET'])
@@ -73,11 +68,71 @@ def getallyears():
7368
return jsonify({"status": "failed", "message": "Endpoint, /years, needs a GET request"})
7469
```
7570

71+
Here's a POST request example from the same project
72+
```python
73+
#Add a map
74+
@app.route('/maps', methods=['POST'])
75+
# @login_required
76+
def addmapforyear():
77+
if request.method == 'POST':
78+
try:
79+
json_dict = json.loads(request.data)
80+
result = Maps(
81+
image_url = json_dict['image_url'],
82+
year = (int)(json_dict['year'])
83+
)
84+
db.session.add(result)
85+
db.session.commit()
86+
return jsonify({"status": "success", "message": "successfully added maps and year"})
87+
except Exception as ex:
88+
raise InvalidUsage('Error: ' + str(ex), status_code=404)
89+
else:
90+
return jsonify({"status": "failed", "message": "Endpoint, /maps, needs a GET or POST request"})
91+
```
92+
7693
Everything that I described above is what you're going to be working on in the Flask backend. This means figuring out how to design your database, and then define the API to make changes in your database.
7794

78-
**Problem 2: Download Postman, go to the url for get_all_users, and set a GET request. If you make the wrong type of request, you will get an error message**
7995

80-
Setting up the database and defining it is alot of work, so we'll leave that for your tech leads to teach you :P
81-
For now, we're going to try actually using a public API to get more familair with it.
8296

83-
**Problem 3: Write an endpoint that will take an input, search for that term on wikipeida using the API, and then return back a list of titles of the top matches**
97+
**Problem 2:**
98+
99+
**So instead of making you guys actually use a database, simply make an array called *users* thats global in your app.py file. Each element in the array is a user with a id, name, and age**
100+
101+
For example
102+
```json
103+
104+
users = [
105+
{
106+
"id": 1,
107+
"name": "Aria",
108+
"age": 19
109+
},
110+
{
111+
"id": 2,
112+
"name": "Tim",
113+
"age": 20
114+
},
115+
{
116+
"id": 1,
117+
"name": "Varun",
118+
"age": 23
119+
},
120+
{
121+
"id": 1,
122+
"name": "Alex",
123+
"age": 24
124+
}
125+
]
126+
```
127+
128+
**Then create a route for /get_all_users that will receive a GET request and return the list of all current users in a json format. It will return an error message for everything other than a GET request.**
129+
130+
**Next create a route called /add_user that will receieve a POST request. Inside the request data there will be a user with an id, name, and age. The function will take the request data and add a new user to the globale list of users. Also, add appropriate sucess/error responses in a json format.**
131+
132+
**Next create a route called /modify_user that will receieve a PUT request. In the request data have an id so they know which user is being modified, and then have a new name or age for the user. In the function, edit the user with that id in the global list of users. Also, add appropriate sucess/error responses in a json format.**
133+
134+
**Next create a route called /delete_user that will receieve a DELETE request and a name. The request data will have an id,and then that user is deleted from teh global array. Also, add appropriate sucess/error responses in a json format.**
135+
136+
**To test everything, download postman and make requests**
137+
138+
Setting up the database and defining it is alot of work, so we'll leave that for your tech leads to teach you. Also, for the course of this intro project, we're doing everything in app.py. In your projects though, you are going to organize the endpoints into different files, have a folder to define the models, and other files for the database connection.

app.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,6 @@ def get_all_users():
1717
return jsonify({'status': 'success', 'data': ['aria', 'tim', 'varun', 'alex']})
1818
else:
1919
return jsonify({"status": "failed")
20+
2021
if __name__ == '__main__':
2122
app.run(debug=True)

0 commit comments

Comments
 (0)