You are on page 1of 6

МІНІСТЕРСТВО ОСВІТИ І НАУКИ УКРАЇНИ

ХАРКІВСЬКИЙ НАЦІОНАЛЬНИЙ УНІВЕРСИТЕТ РАДІОЕЛЕКТРОНІКИ

Кафедра ІУС

Дисципліна: «SOA і патерни проектування»

Практичне заняття № 2

«РАЗРАБОТКА RESTFUL-ПРИЛОЖЕНИЙ С ИСПОЛЬЗОВАНИЕ JAX RS»

Виконали: Прийняла:
ст. гр. ІТКН-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

# creating an instance of the flask app


app = Flask(__name__)

# Configure our Database


app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

countries.py
from settings import *
import json

# Initializing our database


db = SQLAlchemy(app)

# the class Country will inherit the db.Model of SQLAlchemy


class Country(db.Model):
__tablename__ = 'countries' # creating a table name
id = db.Column(db.Integer, primary_key=True) # this is the primary key
name = db.Column(db.String(80), nullable=False)
# nullable is false so the column can't be empty
population = db.Column(db.Integer, nullable=False)
area = db.Column(db.REAL, nullable=False)

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 add_country(_name, _population, _area):


new_country = Country(name=_name, population=_population, area=_area)
db.session.add(new_country) # add new country to database session
db.session.commit() # commit changes to session

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 update_country(_id, _name, _population, _area):


country_to_update = Country.query.filter_by(id=_id).first()
country_to_update.name = _name
country_to_update.population = _population
country_to_update.area = _area
db.session.commit()

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)
Скріншоти виконання програми:

Рисунок 1 – Додання нового фільму

Рисунок 2 – Перелік усіх фільмів


Рисунок 3 – Апдейт фільму

Рисунок 4 – Видалення фільму

Рисунок 5 – Результат виконання HTTP-запросов


Висновки:
Виконали практичну роботу ми ознайомилися з REST API та розробили
CRUD додаток.

You might also like