Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.5 kB
7
Indexable
Never
# app.py (continued)

@app.route('/add_city', methods=['POST'])
def add_city():
    data = request.json
    new_city = City(
        name=data['name'],
        state=data['state'],
        country=data['country'],
        tourist_rating=data['tourist_rating'],
        date_established=data['date_established'],
        estimated_population=data['estimated_population']
    )
    db.session.add(new_city)
    db.session.commit()
    return jsonify({"message": "City added successfully!"})

@app.route('/update_city/<int:city_id>', methods=['PUT'])
def update_city(city_id):
    city = City.query.get(city_id)
    if not city:
        return jsonify({"error": "City not found!"}), 404

    data = request.json
    city.tourist_rating = data.get('tourist_rating', city.tourist_rating)
    city.date_established = data.get('date_established', city.date_established)
    city.estimated_population = data.get('estimated_population', city.estimated_population)
    db.session.commit()
    return jsonify({"message": "City updated successfully!"})

@app.route('/delete_city/<int:city_id>', methods=['DELETE'])
def delete_city(city_id):
    city = City.query.get(city_id)
    if not city:
        return jsonify({"error": "City not found!"}), 404

    db.session.delete(city)
    db.session.commit()
    return jsonify({"message": "City deleted successfully!"})

@app.route('/search_city/<string:city_name>', methods=['GET'])
def search_city(city_name):
    cities = City.query.filter_by(name=city_name).all()
    if not cities:
        return jsonify({"message": "No matching cities found!"}), 404

    result = []
    for city in cities:
        # Here you can make API requests to get additional information about the city
        # For example, using the `requests` library, you can fetch weather information:
        # weather_data = requests.get('https://api.example.com/weather?city={}'.format(city.name)).json()

        city_data = {
            "id": city.id,
            "name": city.name,
            "state": city.state,
            "country": city.country,
            "tourist_rating": city.tourist_rating,
            "date_established": city.date_established,
            "estimated_population": city.estimated_population,
            # Add additional data here (2-digit Country Code, 3-digit Country Code, Currency Code, Weather)
        }
        result.append(city_data)

    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)