-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
253 lines (208 loc) · 7.67 KB
/
app.py
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, Float
from flask_marshmallow import Marshmallow
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
from flask_mail import Mail, Message
import os
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'planets.db')
app.config['JWT_SECRET_KEY'] = 'super-secret' # change this in a real time application or on production
app.config['MAIL_SERVER'] = 'smtp.mailtrap.io'
app.config['MAIL_PORT'] = 2525
app.config['MAIL_USERNAME'] = 'b8fcade6c9e5bc'
app.config['MAIL_PASSWORD'] = '6ec6b7931c7b71'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)
jwt = JWTManager(app)
mail = Mail(app)
@app.cli.command('db_create')
def db_create():
db.create_all()
print('Database created!')
@app.cli.command('db_drop')
def db_drop():
db.drop_all()
print('Database dropped!')
@app.cli.command('db_seed')
def db_seed():
mercury = Planet( planet_name='Mercury',
planet_type='Class D',
home_star='Sol',
mass=3.258e23,
radius=1516,
distance=35.98e6)
venus = Planet( planet_name='Venus',
planet_type='Class K',
home_star='Sol',
mass=4.867e24,
radius=3760,
distance=67.24e6)
earth = Planet( planet_name='Earth',
planet_type='Class M',
home_star='Sol',
mass=5.972e24,
radius=3959,
distance=92.96e6)
db.session.add(mercury)
db.session.add(venus)
db.session.add(earth)
test_user = User( first_name='William',
last_name='Herschel',
email='[email protected]',
password='P@ssw0rd')
db.session.add(test_user)
db.session.commit()
print('Database seeded !')
@app.cli.command('db_close')
def db_close():
db.session.close_all()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/super_simple')
def super_simple():
return jsonify(message='Hello from the Planetary API.')
@app.route('/parameters')
def parameters():
name = request.args.get('name')
age = int(request.args.get('age'))
if age < 18:
return jsonify(message="Sorry " + name + " you are not old enough."), 401
else:
return jsonify(message="Welcome " + name + " you are old enough!")
@app.route('/url_variables/<string:name>/<int:age>')
def url_variables(name: str, age: int):
if age < 18:
return jsonify(message="Sorry " + name + " you are not old enough."), 401
else:
return jsonify(message="Welcome " + name + " you are old enough!")
@app.route('/planets', methods=['GET'])
def planets():
planets_list = Planet.query.all()
result = planets_schema.dump(planets_list)
return jsonify(result)
@app.route('/register', methods=['POST'])
def register():
email = request.form['email']
test = User.query.filter_by(email=email).first()
if test:
return jsonify(message='That email already exists. '), 409
else:
first_name = request.form['first_name']
last_name = request.form['last_name']
password = request.form['password']
user = User(first_name=first_name, last_name=last_name, email=email, password=password)
db.session.add(user)
db.session.commit()
return jsonify(message='User created succesfully !'), 201
@app.route('/login', methods=['POST'])
def login():
if request.is_json:
email = request.json['email']
password = request.json['password']
else:
email = request.form['email']
password = request.form['password']
test = User.query.filter_by(email=email, password=password).first()
if test:
access_token = create_access_token(identity=email)
return jsonify(message='Login Succesfull', access_token=access_token)
else:
return jsonify(message='Bad email or password'), 401
@app.route('/retrieve_password/<string:email>', methods=['GET'])
def retrieve_password(email: str):
user = User.query.filter_by(email=email).first()
if user:
msg = Message('Your planetary API password is ' + user.password, sender='[email protected]', recipients=[email])
mail.send(msg)
return jsonify(message='Password sent to ' + email)
else:
return jsonify(message='That email does not exist'), 404
@app.route('/planet_details/<int:planet_id>', methods=['GET'])
def planet_details(planet_id: int):
planet = Planet.query.filter_by(planet_id=planet_id).first()
if planet:
result = planet_schema.dump(planet)
return jsonify(result)
else:
return jsonify(message='That planet doesnt exist'), 404
@app.route('/add_planet', methods=['POST'])
@jwt_required()
def add_planet():
planet_name = request.form['planet_name']
planet_exists = Planet.query.filter_by(planet_name=planet_name).first()
if planet_exists:
return jsonify(message='There is already a planet by this name'), 409
else:
planet_type = request.form['planet_type']
home_star = request.form['home_star']
mass = float(request.form['mass'])
radius = float(request.form['radius'])
distance = float(request.form['distance'])
new_planet = Planet( planet_type=planet_type,
home_star=home_star,
mass=mass,
radius=radius,
distance=distance)
db.session.add(new_planet)
db.session.commit()
return jsonify(message='You added a planet succesfully'), 201
@app.route('/update_planet', methods=['PUT'])
@jwt_required()
def update_planet():
planet_id = int(request.form['planet_id'])
planet = Planet.query.filter_by(planet_id=planet_id).first()
if planet:
planet.planet_name = request.form['planet_name']
planet.planet_type = request.form['planet_type']
planet.home_star = request.form['home_star']
planet.mass = float(request.form['mass'])
planet.radius = float(request.form['radius'])
planet.distance = float(request.form['distance'])
db.session.commit()
return jsonify(message='You updated a planet'), 202
else:
return jsonify(message='That planet does not exist'), 404
@app.route('/remove_planet/<int:planet_id>', methods=['DELETE'])
@jwt_required()
def remove_planet(planet_id: int):
planet = Planet.query.filter_by(planet_id=planet_id).first()
if planet:
db.session.delete(planet)
db.session.commit()
return jsonify(message='You deleted a planet'), 202
else:
return jsonify(message='This planet does not exist'), 404
# Database models
class User(db.Model):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
email = Column(String, unique=True)
password = Column(String)
class Planet(db.Model):
__tablename__ = 'planets'
planet_id = Column(Integer, primary_key=True)
planet_name = Column(String)
planet_type = Column(String)
home_star = Column(String)
mass = Column(Float)
radius = Column(Float)
distance = Column(Float)
class UserSchema(ma.Schema):
class Meta:
fields = ('id', 'first_name','last_name', 'email', 'password')
class PlanetSchema(ma.Schema):
class Meta:
fields = ('planet_id', 'planet_name', 'planet_type', 'home_star', 'mass', 'radius', 'distance')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
planet_schema = PlanetSchema()
planets_schema = PlanetSchema(many=True)
if __name__ == '__main__' :
app.run()