-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
83 lines (63 loc) · 2.42 KB
/
app.py
File metadata and controls
83 lines (63 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from flask import Flask, render_template, request
import json
from urllib.request import urlopen, Request
from psycopg2 import sql
import connection
app = Flask(__name__)
def api(page):
webURL = Request("https://swapi.co/api/planets?page=" + str(page), headers={'User-Agent': 'Mozilla/5.0'}) # This will return a string containing the data in JSON format
data = urlopen(webURL).read()
response_data = json.loads(data.decode('utf-8')) # parse the JSON and convert it into a dict
print(response_data['results'])
return response_data['results']
@app.route('/')
@app.route('/')
def root():
if request.args.get('page'):
page = int(request.args.get('page'))
else:
page = 1
results = getPlanets(page)
#print(execute_query("SELECT * from users"))
return render_template("index.html", results=results, page = page)
@app.route('/residents', methods=["POST"])
def residents():
planet_residents = []
planet_id = request.form.get("index")
planet = getPlanet(planet_id)
print(planet)
for resident in planet["residents"]:
print("res: " + resident)
planet_residents.append(get_api_url(resident))
# print(residents)
return render_template("residents.html", residents=planet_residents, planet=planet["name"])
def getPlanet(id):
webURL = Request("https://swapi.co/api/planets/" + str(id), headers={
'User-Agent': 'Mozilla/5.0'}) # This will return a string containing the data in JSON format
data = urlopen(webURL).read()
response_data = json.loads(data.decode('utf-8')) # parse the JSON and convert it into a dict
# print(response_data)
return response_data
def get_api_url(url):
print("url: " + url)
webURL = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) # This will return a string containing the data in JSON format
data = urlopen(webURL).read()
response_data = json.loads(data.decode('utf-8')) # parse the JSON and convert it into a dict
# print(response_data)
return response_data
def getPlanets(page):
plantes = api(page)
# print(len(plantes))
return plantes
# @connection.connection_handler
def execute_query(cursor, query):
if query.startswith("SELECT"):
cursor.execute(
sql.SQL(query)
)
result = cursor.fetchall()
else:
result = cursor.execute(query)
return result
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000)