Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hw7 web Лоскутов Павел #571

Open
wants to merge 2 commits into
base: homework_07_web
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
141 changes: 141 additions & 0 deletions homeworks/homework_07_web/flights.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
from sqlalchemy import create_engine, MetaData, Table,\
Column, Integer, String, ForeignKey, select
from sqlalchemy.orm import sessionmaker, relationship, scoped_session
from sqlalchemy.sql.expression import update
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///C:\sqlitedbs\database.db', echo=True)
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()


class Flights(Base):
__tablename__ = 'flights'
id = Column(Integer, primary_key=True)
f_id = Column(Integer)
departure = Column(String)
arrival = Column(String)
flight_time = Column(String)
airport_id = Column(String, ForeignKey('airports.id'))
plane_id = Column(String, ForeignKey('planes.id'))
planes = relationship("Planes")
airports = relationship("Airports")

def __init__(self, f_id, departure, arrival, flight_time, airport, plane):
self.f_id = f_id
self.departure = departure
self.arrival = arrival
self.flight_time = flight_time
self.airport_id = airport
self.plane_id = plane

def __repr__(self):
return f"{self.departure}, {self.arrival}, {self.flight_time}, {self.airport_id}, {self.plane_id}"


class Planes(Base):
__tablename__ = 'planes'
id = Column(Integer, primary_key=True)
plane = Column(String)

def __init__(self, plane):
self.plane = plane

def __repr__(self):
return self.plane


class Airports(Base):
__tablename__ = 'airports'
id = Column(Integer, primary_key=True)
airport = Column(String)

def __init__(self, airport):
self.airport = airport

def __repr__(self):
return self.airport


Base.metadata.create_all(engine)


class Flightsdb():
def get(self, get_filter=None):
q = select([Flights.departure, Flights.arrival, Flights.flight_time,
Airports.airport, Planes.plane, Flights.f_id]) \
.where(Flights.airport_id == Airports.id).where(
Flights.plane_id == Planes.id)
if get_filter is None:
dct = [{
'id': i[5],
'departure': i[0],
'arrival': i[1],
'flight_time': i[2],
'airport': i[3],
'plane': i[4]
} for i in session.execute(q)]
return sorted(dct, key=lambda x: x['id'])
else:
for key in ['id', 'departure', 'arrival', 'flight_time', 'airport',
'plane']:
if get_filter.get(key) is None:
get_filter[key] = "%"
print(get_filter)
q = q.where(Flights.f_id.like(get_filter['id'])) \
.where(Flights.departure.like(get_filter['departure'])) \
.where(Flights.arrival.like(get_filter['arrival'])) \
.where(Flights.flight_time.like(get_filter['flight_time'])) \
.where(Airports.airport.like(get_filter['airport'])) \
.where(Planes.plane.like(get_filter['plane']))
dct = [{
'id': i[5],
'departure': i[0],
'arrival': i[1],
'flight_time': i[2],
'airport': i[3],
'plane': i[4]
} for i in session.execute(q)]
return dct

def append(self, item): # correct data
if item['id'] in [i[0] for i in
session.execute(select([Flights.f_id]))]:
return 1
else:
session.add(Airports(item['airport']))
session.add(Planes(item['plane']))
real_id = session.query(Airports.id)[-1][0] + 1
session.add(Flights(item['id'], item['departure'], item['arrival'],
item['flight_time'], real_id, real_id))
session.commit()

def pop(self, _id): # correct id
flight = session.query(Flights).filter_by(f_id=_id)[:]
if len(flight) == 0:
return 1
print(type(flight))
flight = flight[0]
session.delete(session.query(Airports).get(flight.airport_id))
session.delete(session.query(Planes).get(flight.plane_id))
session.delete(flight)
session.commit()
return 0

def update(self, item): # correct item
flight = session.query(Flights).filter_by(f_id=item.get('id'))[:]
if len(flight) == 0:
return 1
cur_id = item.pop('id')
flight = flight[0]
if item.get('airport') is not None:
session.query(Airports).filter(
Airports.id == flight.airport_id).update(
{'airport': item['airport']})
item.pop('airport')
if item.get('plane') is not None:
session.query(Planes).filter(Planes.id == flight.plane_id).update(
{'plane': item['plane']})
item.pop('plane')
session.query(Flights).filter(Flights.f_id == cur_id).update(item)
session.commit()
96 changes: 96 additions & 0 deletions homeworks/homework_07_web/logs.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
--------------------------------------
--------------------------------------
New session started: 2019-10-28 04:25:33.485702
--------------------------------------
Request: POST, Time: 2019-10-28 04:25:43.008817
Args: {'id': 3, 'departure': 'Tue, 12 Jun 2012 14:03:19 GMT', 'arrival': 'Tue, 12 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMD', 'plane': 'Airbus'} 2019-10-28 04:25:43.008817
Method: POST, Time: 2019-10-28 04:25:43.775501
Status: 200 , Reason: OK
--------------------------------------
New session started: 2019-10-28 04:30:39.876834
--------------------------------------
Request: POST, Time: 2019-10-28 04:30:49.148662
Args: {'id': 3, 'departure': 'Tue, 12 Jun 2012 14:03:19 GMT', 'arrival': 'Tue, 12 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMD', 'plane': 'Airbus'} 2019-10-28 04:30:49.148662
Method: POST, Time: 2019-10-28 04:30:49.971323
Status: 200 , Reason: OK
--------------------------------------
New session started: 2019-10-28 04:33:15.422749
--------------------------------------
Request: POST, Time: 2019-10-28 04:33:22.346935
Args: {'id': 3, 'departure': 'Tue, 12 Jun 2012 14:03:19 GMT', 'arrival': 'Tue, 12 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMD', 'plane': 'Airbus'} 2019-10-28 04:33:22.346935
Method: POST, Time: 2019-10-28 04:33:23.051320
Status: 200 , Reason: OK
Request: GET, Time: 2019-10-28 04:33:24.433728
Method: GET, Time: 2019-10-28 04:33:24.433728
Status: 404 , Reason: Flight with current mask ImmutableMultiDict([('airport', 'AMS')]) not found. Try another mask.
Request: PUT, Time: 2019-10-28 04:33:28.673025
Args: {'id': 3, 'departure': 'Tue, 12 Jun 2012 14:03:19 GMT', 'arrival': 'Tue, 12 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMD', 'plane': 'Airbus'} 2019-10-28 04:33:28.673025
Method: POST, Time: 2019-10-28 04:33:29.392194
Status: 200 , Reason: OK
Request: DELETE, id: 1, Time: 2019-10-28 04:33:29.795045
Method: DELETE, id: 1, Time: 2019-10-28 04:33:29.795045
Status: 400 , Reason: Bad id
--------------------------------------
New session started: 2019-10-28 04:43:33.344618
--------------------------------------
--------------------------------------
Request: POST, Time: 2019-10-28 04:43:36.269150
Args: {'id': 3, 'departure': 'Tue, 12 Jun 2012 14:03:19 GMT', 'arrival': 'Tue, 12 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMD', 'plane': 'Airbus'} 2019-10-28 04:43:36.270148
Method: POST, Time: 2019-10-28 04:43:37.357727
Status: 200 , Reason: OK
--------------------------------------
Request: GET, Time: 2019-10-28 04:43:37.364725
Method: GET, Time: 2019-10-28 04:43:37.364725
Status: 200 , Reason: OK
--------------------------------------
Request: PUT, Time: 2019-10-28 04:43:37.370730
Args: {'id': 3, 'departure': 'Tue, 13 Jun 2012 22:03:19 GMT', 'arrival': 'Tue, 14 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMS', 'plane': 'Airbus'} 2019-10-28 04:43:37.371737
Method: PUT, Time: 2019-10-28 04:43:38.035663
Status: 400 , Reason: Incorrect id
--------------------------------------
Request: DELETE, id: 1, Time: 2019-10-28 04:43:38.045469
Method: DELETE, id: 1, Time: 2019-10-28 04:43:38.045469
Status: 400 , Reason: Bad id
--------------------------------------
Request: POST, Time: 2019-10-28 04:44:29.502439
Args: {'id': 3, 'departure': 'Tue, 12 Jun 2012 14:03:19 GMT', 'arrival': 'Tue, 12 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMD', 'plane': 'Airbus'} 2019-10-28 04:44:29.503439
Method: POST, Time: 2019-10-28 04:44:30.230352
Status: 400 , Reason: Item already added
--------------------------------------
Request: GET, Time: 2019-10-28 04:44:30.236343
Method: GET, Time: 2019-10-28 04:44:30.236343
Status: 200 , Reason: OK
--------------------------------------
Request: PUT, Time: 2019-10-28 04:44:30.244341
Args: {'id': 3, 'departure': 'Tue, 13 Jun 2012 22:03:19 GMT', 'arrival': 'Tue, 14 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMS', 'plane': 'Airbus'} 2019-10-28 04:44:30.244341
Method: POST, Time: 2019-10-28 04:44:30.932233
Status: 200 , Reason: OK
--------------------------------------
Request: DELETE, id: 3, Time: 2019-10-28 04:44:30.939227
Method: DELETE, Time: 2019-10-28 04:44:30.939227
Status: 200 , Reason: OK
--------------------------------------
New session started: 2019-11-11 04:19:22.919954
--------------------------------------
--------------------------------------
Request: GET, Time: 2019-11-11 04:19:27.608728
Method: GET, Time: 2019-11-11 04:19:27.618725
Status: 200 , Reason: OK
--------------------------------------
Request: PUT, Time: 2019-11-11 04:19:34.705472
Args: {'id': 8, 'departure': 'Tue, 12 Jun 2012 14:03:19 GMT', 'arrival': 'Tue, 12 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMD', 'plane': 'Airbus'} 2019-11-11 04:19:34.705472
Method: POST, Time: 2019-11-11 04:19:35.781010
Status: 200 , Reason: OK
--------------------------------------
Request: POST, Time: 2019-11-11 04:19:40.464482
Args: {'id': 8, 'departure': 'Tue, 12 Jun 2012 14:03:19 GMT', 'arrival': 'Tue, 12 Jun 2012 14:03:11 GMT', 'flight_time': '14:34 GMT', 'airport': 'AMD', 'plane': 'Airbus'} 2019-11-11 04:19:40.464482
Method: POST, Time: 2019-11-11 04:19:41.180549
Status: 400 , Reason: Item already added
--------------------------------------
Request: DELETE, id: 1, Time: 2019-11-11 04:19:44.719726
Method: DELETE, id: 1, Time: 2019-11-11 04:19:44.728720
Status: 400 , Reason: Bad id
--------------------------------------
Request: DELETE, id: 8, Time: 2019-11-11 04:19:50.048805
Method: DELETE, Time: 2019-11-11 04:19:50.120404
Status: 200 , Reason: OK
158 changes: 158 additions & 0 deletions homeworks/homework_07_web/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
from flask import Flask, request, jsonify, abort
from validator import validator
from flights import Flightsdb
import datetime

app = Flask(__name__)

flights = Flightsdb()


@app.route('/flights', methods=['GET'])
def get_flights():
log_file = open('logs.txt', 'a')
print("--------------------------------------", file=log_file)
print("Request: GET, Time: ", datetime.datetime.now(), file=log_file)
arg_dct = request.args
fltr = {}
if len(arg_dct) == 0:
answ = flights.get()
if len(answ) == 0:
print("Method: GET, Time: ", datetime.datetime.now(),
file=log_file)
print("Status: ", 400, ", Reason: ",
"Empty list of flights. Append something"
" before using get-method.",
file=log_file)
log_file.close()
abort(400,
"Empty list of flights. Append something"
" before using get-method.")
print("Method: GET, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", 200, ", Reason: ", "OK", file=log_file)
log_file.close()
return jsonify(flights.get())
for t in arg_dct.keys():
if t in ['id', 'departure', 'arrival', 'flight_time', 'airport',
'plane']:
fltr[t] = arg_dct.get(t)
answ = flights.get(fltr)
if len(answ) == 0:
print("Method: GET, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", 404, ", Reason: ",
f"Flight with current mask {arg_dct} not found."
f" Try another mask.",
file=log_file)
log_file.close()
abort(404,
f'Flight with current mask {arg_dct} not found.'
f' Try another mask.')
print("Method: GET, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", 200, ", Reason: ", "OK", file=log_file)
log_file.close()
return jsonify(answ)


@app.route('/flights', methods=['POST'])
def post_flight():
log_file = open('logs.txt', 'a')
print("--------------------------------------", file=log_file)
print("Request: POST, Time: ", datetime.datetime.now(), file=log_file)
arg_dct = request.json
print(f"Args: {arg_dct}", datetime.datetime.now(), file=log_file)
if len(arg_dct) == 0:
print("Method: POST, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", 400, ", Reason: ", f"Bad args {arg_dct}",
file=log_file)
log_file.close()
abort(400, f"Bad args {arg_dct}")
res = validator('POST', arg_dct)
if res[0] == 200:
ans = flights.append(arg_dct)
if ans == 1:
print("Method: POST, Time: ", datetime.datetime.now(),
file=log_file)
print("Status: ", 400, ", Reason: ", "Item already added",
file=log_file)
log_file.close()
abort(400, "Item already added")
else:
print("Method: POST, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", res[0], ", Reason: ", res[1], file=log_file)
log_file.close()
abort(res[0], res[1])
print("Method: POST, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", 200, ", Reason: ", "OK", file=log_file)
log_file.close()
return jsonify({"data": arg_dct})


@app.route('/flights/<int:flight_id>', methods=['PUT'])
def put_flight(flight_id):
log_file = open('logs.txt', 'a')
print("--------------------------------------", file=log_file)
print("Request: PUT, Time: ", datetime.datetime.now(), file=log_file)
arg_dct = request.json
print(f"Args: {arg_dct}", datetime.datetime.now(), file=log_file)
if len(arg_dct) == 0:
print("Method: PUT, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", 400, ", Reason: ", f"Bad args {arg_dct}",
file=log_file)
log_file.close()
abort(400, f"Bad args {arg_dct}")
res = validator('PUT', arg_dct)
if res[0] == 200:
if arg_dct['id'] != flight_id:
print("Method: PUT, Time: ", datetime.datetime.now(),
file=log_file)
print("Status: ", 400, ", Reason: ", "Incorrect id", file=log_file)
log_file.close()
abort(400, "Incorrect id")
ans = flights.update(arg_dct)
if ans == 1:
print("Method: PUT, Time: ", datetime.datetime.now(),
file=log_file)
print("Status: ", 400, ", Reason: ", "Item already added",
file=log_file)
log_file.close()
abort(400, "Item already added")
else:
print("Method: PUT, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", res[0], ", Reason: ", res[1], file=log_file)
log_file.close()
abort(res[0], res[1])
print("Method: POST, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", 200, ", Reason: ", "OK", file=log_file)
log_file.close()
return jsonify({"data": arg_dct})


@app.route('/flights/<int:flight_id>', methods=['DELETE'])
def delete_flight(flight_id):
log_file = open('logs.txt', 'a')
print("--------------------------------------", file=log_file)
print(f"Request: DELETE, id: {flight_id}, Time: ",
datetime.datetime.now(), file=log_file)
ans = flights.pop(flight_id)
if ans == 1:
print(
f"Method: DELETE, id: {flight_id}, Time: ",
datetime.datetime.now(),
file=log_file)
print("Status: ", 400, ", Reason: ", "Bad id", file=log_file)
log_file.close()
abort(400, "Bad id")
else:
print("Method: DELETE, Time: ", datetime.datetime.now(), file=log_file)
print("Status: ", 200, ", Reason: ", "OK", file=log_file)
log_file.close()
return jsonify({"data": ans})


if __name__ == "__main__":
log_file = open('logs.txt', 'a')
print("--------------------------------------", file=log_file)
print("New session started: ", datetime.datetime.now(), file=log_file)
print("--------------------------------------", file=log_file)
log_file.close()
app.run()