Skip to content

Commit

Permalink
added parameters to filter adverts by city id, added new endpoint to …
Browse files Browse the repository at this point in the history
…get list of available cities
  • Loading branch information
Yariki committed Mar 24, 2024
1 parent 896d3af commit 3d8b39e
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 48 deletions.
6 changes: 4 additions & 2 deletions dimria-fe/src/redux/adverts/requests.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import axios from 'axios';

export const fetchAdverts = async () => {
return await axios.get('https://dimria-advert-prices.azurewebsites.net/api/get_advertisements');
//return await axios.get('https://dimria-advert-prices.azurewebsites.net/api/get_advertisements');
return await axios.get('http://localhost:7071/api/get_advertisements');
}

export const fetchAdvertDetails = async (advertId: string) => {
return await axios.get(`https://dimria-advert-prices.azurewebsites.net/api/get_advert_details/${advertId}`);
//return await axios.get(`https://dimria-advert-prices.azurewebsites.net/api/get_advert_details/${advertId}`);
return await axios.get(`http://localhost:7071/api/get_advert_details/${advertId}`);
}

export const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
Expand Down
13 changes: 1 addition & 12 deletions dimria-fe/src/redux/adverts/sagas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ function* fetchAdvertsAsync(action: ReturnType<typeof fetchAdvertsStart> ) {
yield put(fetchAdvertsSuccess(response.data));
} catch (error) {
yield put(fetchAdvertsFailure("Error fetching data"));
console.log(error);
}
}

Expand All @@ -27,18 +28,6 @@ function* fetchAdvertDetailsAsync(action: Action<string> ) {

// @ts-ignore
const response = yield call(fetchAdvertDetails, advertId);

//yield call(delay, 500);

// const response : AdvertDetailsDto = {
// "advert_id": 27272590,
// "city_name": "Житомир",
// "description": "3-к кв в новобудові, всі окремі кімнати, велика кухня, свіжий ремонт, , 2 санвузли, є право власності, є відео, запрошуємо на показ",
// "price": 84000,
// "currency": "$",
// "floor": "3 поверх з 10",
// "rooms_count": 3
// };
if(response.status === 200){
yield put(fetchAdvertDetailsSuccess(response.data));
}
Expand Down
34 changes: 34 additions & 0 deletions dimria/cosmos_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,37 @@ def get_adverts():
finally:
logging.info(f"\n Get Adverts")

def get_adverts_filtered(cityId: int):

client = cosmos_client.CosmosClient(settings['host'], {'masterKey': settings['master_key']}, user_agent="DimRia", user_agent_overwrite=True)
try:
# setup database for this sample
try:
db = client.get_database_client(settings['db_id'])
except exceptions.CosmosResourceExistsError:
logging.error('Database with id \'{0}\' was not found'.format(settings['db_id']))

# setup container for this sample
try:
container = db.get_container_client(settings['container_id'])

except exceptions.CosmosResourceExistsError:
logging.error('Container with id \'{0}\' was not found'.format(settings['container_id']))

items = list(container.query_items(
query='SELECT * FROM adverts a WHERE a.city_id = @cityId',
parameters=[
{"name": "@cityId", "value": cityId}
],
enable_cross_partition_query=True
))

return items

except exceptions.CosmosHttpResponseError as e:
logging.error('\nrun_sample has caught an error. {0}'.format(e.message))

finally:
logging.info(f"\n Get Adverts")


25 changes: 20 additions & 5 deletions dimria/dimria_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@

API_KEY = os.getenv("DIMRIA_API_KEY")

search_items = [
SEARCH_ITEMS = [
{
'state_id': 2,
'city_id': 2,
'n_id': 6696
'n_id': 6696,
'city_name': 'Житомир'
},
{
'state_id': 10,
'city_id': 17306,
'n_id': None
'n_id': None,
'city_name': 'Чубинське'
}
]

Expand All @@ -27,7 +29,7 @@ def search_adverts() -> SearchResponse:
items = []


for item in search_items:
for item in SEARCH_ITEMS:

url = _get_url(item.get('state_id'), item.get('city_id'), item.get('n_id'))

Expand All @@ -47,7 +49,7 @@ def search_adverts() -> SearchResponse:
logging.error("No adverts found")
return None

if searchResponse.count == 0:
if searchResponse.count == 0:
logging.error("No adverts found")
return None

Expand All @@ -68,6 +70,19 @@ def get_advert_details(advertId: int) -> AdvertDetails:
return details


def get_cities():
cities = []

for item in SEARCH_ITEMS:
cities.append({
'city_id': item.get('city_id'),
'city_name': item.get('city_name')

});

return cities;



def _get_url(state_id, city_id, n_id = None):

Expand Down
6 changes: 3 additions & 3 deletions dimria/requests_handle.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@
import os

import requests
from dimria.cosmos_db import get_adverts
from dimria.cosmos_db import get_adverts, get_adverts_filtered
from dimria.models.AdvertDetailsRequest import AdvertDetailsResult
from dimria.models.AdvertDto import AdvertDto
from dimria.models.PriceDto import PriceDto

API_KEY = os.getenv("DIMRIA_API_KEY")


def get_adverts_statistics() -> list: # type: ignore
def get_adverts_statistics(cityId: int) -> list: # type: ignore

adverts = get_adverts()
adverts = get_adverts() if cityId == -1 else get_adverts_filtered(cityId)
if not adverts:
logging.error("No adverts found")
return None
Expand Down
72 changes: 46 additions & 26 deletions function_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,18 @@
from dimria.requests_handle import get_adverts_statistics, get_http_advert_details
from dimria.service_bus import send_advert_detail_message, send_advert_list_message

HEADERS = {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : "true",
"Access-Control-Allow-Methods" : "GET, POST, OPTIONS",
"Access-Control-Allow-Headers" : "Origin, Content-Type, Accept"}

app = func.FunctionApp()

################################################################################################

# @app.route(route="search_adverts", auth_level=func.AuthLevel.ANONYMOUS)
@app.schedule(schedule="0 */30 * * * *", arg_name="mytimer", run_on_startup=True, use_monitor=False)
#@app.schedule(schedule="0 */30 * * * *", arg_name="mytimer", run_on_startup=True, use_monitor=False)
def timer_search_adverts(mytimer: func.TimerRequest) -> None: # req: func.HttpRequest func.HttpResponse: # mytimer: func.TimerRequest -> None:

searchResponse = search_adverts()
Expand Down Expand Up @@ -84,16 +90,22 @@ def advert_details_save_db(msg: func.ServiceBusMessage):

################################################################################################

@app.route("get_advertisements", methods=["GET"], auth_level=func.AuthLevel.ANONYMOUS)
@app.route("get_advertisements/{cityId:int?}", methods=["GET"], auth_level=func.AuthLevel.ANONYMOUS)
def get_advertisements(req: func.HttpRequest) -> func.HttpResponse:

results = get_adverts_statistics()
cityId = req.route_params.get('cityId')

if(cityId is None):
cityId = -1

results = get_adverts_statistics(int(cityId))

if(results is None):
return func.HttpResponse("No adverts found", status_code=404)
return func.HttpResponse("No adverts found", status_code=404, headers=HEADERS)

data = json.dumps(results, cls=AdvertDtoEncoder)
return data

return func.HttpResponse(data, status_code=200, headers=HEADERS)

################################################################################################

Expand All @@ -103,30 +115,30 @@ def get_advert_details(req: func.HttpRequest) -> func.HttpResponse:
advert_id = req.route_params.get('id')

if(advert_id is None):
return func.HttpResponse("No advert id found", status_code=404)
return func.HttpResponse("No advert id found", status_code=404, headers=HEADERS)

resultRequest = get_http_advert_details(advert_id)

if(resultRequest is None):
return func.HttpResponse(f"No advert details found for advert id - {advert_id}", status_code=404)

print(resultRequest)

cityName = resultRequest['city_name']
state_id = resultRequest['state_id']
city_id = resultRequest['city_id']
currency_type_id = resultRequest['currency_type_id']
price = resultRequest['price']
rooms_count = resultRequest['rooms_count']
currency_type_uk = resultRequest['currency_type_uk']
description = resultRequest['description_uk']
floor=resultRequest['floor']
photos = parse_photos(resultRequest['photos'])
main_photo = build_ptoho_url(resultRequest['main_photo'])
lat = resultRequest['latitude']
lon = resultRequest['longitude']
building_name = resultRequest['user_newbuild_name']
url = build_main_advert_url(resultRequest['beautiful_url'])
return func.HttpResponse(f"No advert details found for advert id - {advert_id}", status_code=404, headers=HEADERS)

# print(resultRequest)

cityName = resultRequest['city_name'] if 'city_name' in resultRequest else 'Unknown'
state_id = resultRequest['state_id'] if 'state_id' in resultRequest else 0
city_id = resultRequest['city_id'] if 'city_id' in resultRequest else 0
currency_type_id = resultRequest['currency_type_id'] if 'currency_type_id' in resultRequest else 0
price = resultRequest['price'] if 'price' in resultRequest else 0
rooms_count = resultRequest['rooms_count'] if 'rooms_count' in resultRequest else 0
currency_type_uk = resultRequest['currency_type_uk'] if 'currency_type_uk' in resultRequest else '$'
description = resultRequest['description_uk'] if 'description_uk' in resultRequest else ''
floor=resultRequest['floor'] if 'floor' in resultRequest else 0
photos = parse_photos(resultRequest['photos']) if 'photos' in resultRequest else []
main_photo = build_ptoho_url(resultRequest['main_photo']) if 'main_photo' in resultRequest else ''
lat = resultRequest['latitude'] if 'latitude' in resultRequest else 0
lon = resultRequest['longitude'] if 'longitude' in resultRequest else 0
building_name = resultRequest['user_newbuild_name'] if 'user_newbuild_name' in resultRequest else ''
url = build_main_advert_url(resultRequest['beautiful_url']) if 'beautiful_url' in resultRequest else ''

resultResponse: AdvertDetailsResponse = AdvertDetailsResponse(
advert_id,
Expand All @@ -145,4 +157,12 @@ def get_advert_details(req: func.HttpRequest) -> func.HttpResponse:
)

data = json.dumps(resultResponse, cls=AdvertDetailsResponseEncoder)
return data

return func.HttpResponse(data, status_code=200, headers=HEADERS)

@app.route("get_cities", methods=["GET"], auth_level=func.AuthLevel.ANONYMOUS )
def get_cities() -> func.HttpResponse:
items = get_cities()

return func.HttpResponse(json.dumps(items), status_code=200, headers=HEADERS)

0 comments on commit 3d8b39e

Please sign in to comment.