Professional Documents
Culture Documents
ПЗ2 Проценко Максименко Орлов Котаєв
ПЗ2 Проценко Максименко Орлов Котаєв
Кафедра ІУС
Практичне заняття № 2
Виконали: Прийняла:
ст. гр. ІТКН-17-6 Артем’єва О. Ю.
Проценко А. В. з оцінкою «____________»
Максименко І. С. «____»_______________20___р.
Орлов В. Ю.
Котаєв І. Е.
Харків 2021
Мета заняття: Реализовать CRUD операции по выбранному варианту из
лабораторной работы №1, но теперь с использованием RESTful сервисов.
Предлагается реализация JAX RS.
Хід роботи
В ході роботи було створено наступні файли:
settings.py
# importing libraries
from flask import Flask, request, Response, jsonify
from flask_sqlalchemy import SQLAlchemy
countries.py
from settings import *
import json
def json(self):
return {'id': self.id, 'name': self.name,
'population': self.population, 'area': self.area}
# this method we are defining will convert our output to json
def get_all_countries():
return [Country.json(country) for country in Country.query.all()]
def get_country(_id):
return [Country.json(Country.query.filter_by(id=_id).first())]
# Country.json() coverts our output to json
# the filter_by method filters the query by the id
# the .first() method displays the first value
def delete_country(_id):
Country.query.filter_by(id=_id).delete()
# filter by id and delete
db.session.commit() # commiting the new change to our database
api.py
from countries import *
@app.route('/countries', methods=['GET'])
def get_countries():
'''Function to get all the countries in the database'''
return jsonify({'Countries': Country.get_all_countries()})
@app.route('/countries/<int:id>', methods=['GET'])
def get_country_by_id(id):
return_value = Country.get_country(id)
return jsonify(return_value)
@app.route('/countries', methods=['POST'])
def add_country():
'''Function to add new country to our database'''
request_data = request.get_json() # getting data from client
print(request_data)
Country.add_country(request_data["name"], request_data["population"],
request_data["area"])
response = Response("Country added", 201, mimetype='application/json')
return response
@app.route('/countries/<int:id>', methods=['PUT'])
def update_country(id):
'''Function to edit country in our database using country id'''
request_data = request.get_json()
Country.update_country(id, request_data['name'],
request_data['population'], request_data['area'])
response = Response("Country Updated", status=200,
mimetype='application/json')
return response
@app.route('/countries/<int:id>', methods=['DELETE'])
def remove_country(id):
'''Function to delete country from our database'''
Country.delete_country(id)
response = Response("Country Deleted", status=200,
mimetype='application/json')
return response
if __name__ == "__main__":
app.run(port=1234, debug=True)
Скріншоти виконання програми: