Skip to content

Commit

Permalink
chore: update ci pipeline and poetry version (#160)
Browse files Browse the repository at this point in the history
* chore: update ci pipeline and poetry version

- Introduce dependencies' caching, python black testing and pytest in ci pipeline. Set the ubuntu agent to an explicit version.
- Bump poetry version to 1.8.2, and bump all dev dependencies to their latest. Update flask to use <3.0.0 version. Following this version, the Markup module is not include in Flask anymore.
- Run `black -l 80` on project
- Update __version__ in __init__.py to "0.4.1" to make the test successful. (I don't see the functionality of this test. I will consider removing it in the next PR).

* chore: fix PR review comments

- Update Makefile to include all CI steps. Introduce `black` and `quality` tasks. The latter runs `black` and `pep8` tasks.
- Update ci.yaml to include make tasks include of raw commands
- Fix `black` related findings (i.e. mainly F401 ones). The F401 findings were related with typing module, so instructed `black` to ignore those.
  • Loading branch information
argysamo authored May 6, 2024
1 parent 6d89169 commit 093f143
Show file tree
Hide file tree
Showing 10 changed files with 1,225 additions and 1,391 deletions.
31 changes: 19 additions & 12 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,33 @@ jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
fail-fast: true
matrix:
python: ["3.6", "3.7", "3.8"]
python: ["3.9", "3.10", "3.11", "3.12"]
poetry-version: [1.8.2]

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
with:
fetch-depth: 1

- name: Set up Python
uses: actions/setup-python@v1
- name: Set up Poetry ${{ matrix.poetry-version }}
uses: abatilo/[email protected]
with:
poetry-version: ${{ matrix.poetry-version }}

- name: Set up Python ${{ matrix.python }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
cache: 'poetry'
cache-dependency-path: poetry.lock

- name: Install Dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Install dependencies
run: make install

- name: Code Quality
run: |
pip install black
black -l 80 --check
run: make quality

- name: Unit tests
run: make test
13 changes: 9 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
.PHONY: test pep8 types clean install build publish tree env
.PHONY: test quality pep8 black types clean install build publish tree env

test: pep8
py.test --cov=flask_googlemaps -l --tb=short --maxfail=1 tests/
test:
@poetry run pytest --cov .

quality: pep8 black

pep8:
@flake8 flask_googlemaps --ignore=F403
@poetry run flake8 flask_googlemaps --ignore=F403

black:
@poetry run black -l 80 --check .

types:
@mypy --py2 flask_googlemaps
Expand Down
11 changes: 8 additions & 3 deletions examples/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
from flask import Flask, render_template, request
from flask_googlemaps import GoogleMaps
from flask_googlemaps import Map, icons
#from dynaconf import FlaskDynaconf

# from dynaconf import FlaskDynaconf

app = Flask(__name__, template_folder="templates")
#FlaskDynaconf(app) # will read GOOGLEMAPS_KEY from .secrets.toml
# FlaskDynaconf(app) # will read GOOGLEMAPS_KEY from .secrets.toml


# you can set key as config
Expand Down Expand Up @@ -148,7 +149,11 @@ def mapview():
varname="circlemap",
lat=33.678,
lng=-116.243,
circles=[circle, [33.685, -116.251, 1000], (33.685, -116.251, 1500),],
circles=[
circle,
[33.685, -116.251, 1000],
(33.685, -116.251, 1500),
],
)

polyline = {
Expand Down
25 changes: 13 additions & 12 deletions examples/example_2.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
from flask import Flask, render_template
from flask_googlemaps import GoogleMaps, Map, icons
#from dynaconf import FlaskDynaconf
#enter the api key below
api = ''

# from dynaconf import FlaskDynaconf
# enter the api key below
api = ""
app = Flask(__name__)
GoogleMaps(app, key = api)
#FlaskDynaconf(app)
GoogleMaps(app, key=api)
# FlaskDynaconf(app)

import json


@app.route("/")
def map_created_in_view():

with open('dark_mode.json') as d:
with open("dark_mode.json") as d:
dark_data = json.load(d)

wmap = Map(
Expand All @@ -26,10 +27,9 @@ def map_created_in_view():
icons.dots.blue: [(37.4300, -122.1400, "Hello World")],
},
style="height:400px;width:600px;margin:0;color:#242f3e;",
bicycle_layer = True,
bicycle_layer=True,
)


gmap = Map(
identifier="gmap",
varname="gmap",
Expand All @@ -40,7 +40,7 @@ def map_created_in_view():
icons.dots.blue: [(37.4300, -122.1400, "Hello World")],
},
style="height:400px;width:600px;margin:0;color:#242f3e;",
layer = "https://geo.data.gov.sg/dengue-cluster/2020/09/02/kml/dengue-cluster.kml"
layer="https://geo.data.gov.sg/dengue-cluster/2020/09/02/kml/dengue-cluster.kml",
)

dmap = Map(
Expand All @@ -54,11 +54,12 @@ def map_created_in_view():
},
style="height:400px;width:600px;margin:0;color:#242f3e;",
styles=dark_data,

)

# print(get_address(api, 22.4761596, 88.4149326))
return render_template("example_2.html", dmap=dmap ,gmap = gmap, wmap = wmap,key = api)
# print(get_address(api, 22.4761596, 88.4149326))
return render_template(
"example_2.html", dmap=dmap, gmap=gmap, wmap=wmap, key=api
)


if __name__ == "__main__":
Expand Down
6 changes: 5 additions & 1 deletion examples/jsonify_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,11 @@ def circle_view():
varname="circlemap",
lat=33.678,
lng=-116.243,
circles=[circle, [33.685, -116.251, 1000], (33.685, -116.251, 1500),],
circles=[
circle,
[33.685, -116.251, 1000],
(33.685, -116.251, 1500),
],
)

return jsonify(circlemap.as_json())
Expand Down
79 changes: 57 additions & 22 deletions flask_googlemaps/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"""FlaskGoogleMaps - Google Maps Extension for Flask"""

__version__ = "0.4.0"
__version__ = "0.4.1"

from json import dumps
from typing import Optional, Dict, Any, List, Union, Tuple, Text
from typing import Optional, Dict, Any, List, Union, Tuple, Text # noqa: F401

import requests
from flask import Blueprint, Markup, g, render_template

from flask_googlemaps.icons import dots, Icon
from flask_googlemaps.icons import dots, Icon # noqa: F401

DEFAULT_ICON = dots.red
DEFAULT_CLUSTER_IMAGE_PATH = "static/images/m"
Expand All @@ -27,7 +28,8 @@ def __init__(
cls="map", # type: str
language="en", # type: str
region="US", # type: str
rectangles=None, # type: Optional[List[Union[List, Tuple, Tuple[Tuple], Dict]]]
rectangles=None,
# type: Optional[List[Union[List, Tuple, Tuple[Tuple], Dict]]]
circles=None, # type: Optional[List[Union[List, Tuple, Dict]]]
polylines=None, # type: Optional[List[Union[List, Tuple, Dict]]]
polygons=None, # type: Optional[List[Union[List, Tuple, Dict]]]
Expand Down Expand Up @@ -256,13 +258,20 @@ def build_rectangle_dict(
"stroke_weight": stroke_weight,
"fill_color": fill_color,
"fill_opacity": fill_opacity,
"bounds": {"north": north, "west": west, "south": south, "east": east},
"bounds": {
"north": north,
"west": west,
"south": south,
"east": east,
},
}

return rectangle

def add_rectangle(self, north=None, west=None, south=None, east=None, **kwargs):
# type: (Optional[float], Optional[float], Optional[float], Optional[float], **Any) -> None
def add_rectangle(
self, north=None, west=None, south=None, east=None, **kwargs
):
# type: (Optional[float], Optional[float], Optional[float], Optional[float], **Any) -> None # noqa: E501
"""Adds a rectangle dict to the Map.rectangles attribute
The Google Maps API describes a rectangle using the LatLngBounds
Expand Down Expand Up @@ -297,7 +306,9 @@ def add_rectangle(self, north=None, west=None, south=None, east=None, **kwargs):
if east:
kwargs["bounds"]["east"] = east

if set(("north", "east", "south", "west")) != set(kwargs["bounds"].keys()):
if set(("north", "east", "south", "west")) != set(
kwargs["bounds"].keys()
):
raise AttributeError("rectangle bounds required to rectangles")

kwargs.setdefault("stroke_color", "#FF0000")
Expand Down Expand Up @@ -346,7 +357,9 @@ def build_circles(self, circles):
elif isinstance(circle, (tuple, list)):
if len(circle) != 3:
raise AttributeError("circle requires center and radius")
circle_dict = self.build_circle_dict(circle[0], circle[1], circle[2])
circle_dict = self.build_circle_dict(
circle[0], circle[1], circle[2]
)
self.add_circle(**circle_dict)

def build_circle_dict(
Expand Down Expand Up @@ -395,7 +408,9 @@ def build_circle_dict(

return circle

def add_circle(self, center_lat=None, center_lng=None, radius=None, **kwargs):
def add_circle(
self, center_lat=None, center_lng=None, radius=None, **kwargs
):
# type: (Optional[float], Optional[float], Optional[float], **Any) -> None
"""Adds a circle dict to the Map.circles attribute
Expand Down Expand Up @@ -744,14 +759,16 @@ def build_heatmap(self, heatmap_data, heatmap_layer):
raise AttributeError("heatmap_later requires 'heatmap_data'")
if not isinstance(heatmap_data, (list)):
raise AttributeError(
"heatmap_data only accepts a list of dicts with keys 'lat' 'lng' and their corresponding values"
"heatmap_data only accepts a list of dicts with keys "
"'lat' 'lng' and their corresponding values"
)
for hm in heatmap_data:
if isinstance(hm, dict):
self.add_heatmap(**hm)
else:
raise AttributeError(
"elements of list 'heatmap_data' must be a dict of keys 'lat' and 'lng' with their corresponding values"
"elements of list 'heatmap_data' must be a dict of keys "
"'lat' and 'lng' with their corresponding values"
)

def add_heatmap(self, lat=None, lng=None, **kwargs):
Expand All @@ -763,7 +780,9 @@ def add_heatmap(self, lat=None, lng=None, **kwargs):
if "lat" not in kwargs or "lng" not in kwargs:
raise AttributeError("heatmap_data requires 'lat' and 'lng' values")
if len(kwargs) > 2:
raise AttributeError("heatmap_data can only contain 'lat' and 'lng' values")
raise AttributeError(
"heatmap_data can only contain 'lat' and 'lng' values"
)

self.heatmap_data.append(kwargs)

Expand Down Expand Up @@ -820,7 +839,9 @@ def verify_lat_lng_coordinates(self, lat, lng):
def js(self):
# type: () -> Markup
return Markup(
self.render("googlemaps/gmapjs.html", gmap=self, DEFAULT_ICON=DEFAULT_ICON)
self.render(
"googlemaps/gmapjs.html", gmap=self, DEFAULT_ICON=DEFAULT_ICON
)
)

@property
Expand Down Expand Up @@ -860,18 +881,30 @@ def set_googlemaps_loaded():
def get_address(API_KEY, lat, lon):
# type: (str, float, float) -> dict
add_dict = dict()
response = rq.get(
response = requests.get(
"https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ ",".join(map(str, [lat, lon]))
+ "&key="
+ API_KEY
).json()
add_dict["zip"] = response["results"][0]["address_components"][-1]["long_name"]
add_dict["country"] = response["results"][0]["address_components"][-2]["long_name"]
add_dict["state"] = response["results"][0]["address_components"][-3]["long_name"]
add_dict["city"] = response["results"][0]["address_components"][-4]["long_name"]
add_dict["locality"] = response["results"][0]["address_components"][-5]["long_name"]
add_dict["road"] = response["results"][0]["address_components"][-6]["long_name"]
add_dict["zip"] = response["results"][0]["address_components"][-1][
"long_name"
]
add_dict["country"] = response["results"][0]["address_components"][-2][
"long_name"
]
add_dict["state"] = response["results"][0]["address_components"][-3][
"long_name"
]
add_dict["city"] = response["results"][0]["address_components"][-4][
"long_name"
]
add_dict["locality"] = response["results"][0]["address_components"][-5][
"long_name"
]
add_dict["road"] = response["results"][0]["address_components"][-6][
"long_name"
]
add_dict["formatted_address"] = response["results"][0]["formatted_address"]
return add_dict

Expand Down Expand Up @@ -909,7 +942,9 @@ def init_app(self, app):
app.add_template_global(googlemap_obj)
app.add_template_filter(googlemap)
app.add_template_global(googlemap)
app.add_template_global(app.config.get("GOOGLEMAPS_KEY"), name="GOOGLEMAPS_KEY")
app.add_template_global(
app.config.get("GOOGLEMAPS_KEY"), name="GOOGLEMAPS_KEY"
)
app.add_template_global(set_googlemaps_loaded)
app.add_template_global(is_googlemaps_loaded)

Expand Down
2 changes: 1 addition & 1 deletion flask_googlemaps/icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

__all__ = ["dots", "alpha", "shapes", "pushpin", "paddle"]

from typing import Optional, List
from typing import Optional, List # noqa: F401


class Icon(object):
Expand Down
8 changes: 4 additions & 4 deletions flask_googlemaps/tests/test_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

class TestFunctionAddMarker:
"""
This Class is to test function add marker.
This Class is to test function add marker.
"""

google_map = None
Expand All @@ -21,8 +21,8 @@ def config_test(self):
@pytest.mark.parametrize("marker", [{}, {"lat": 1}, {"lng": 1}])
def test_should_raise_attribute_error_when_is_missing_params(self, marker):
"""
Test check the validation of marker.
This should raise expetion when the lat, lng or both are missing.
Test check the validation of marker.
This should raise expetion when the lat, lng or both are missing.
"""
with pytest.raises(AttributeError) as error:
self.google_map.add_marker(**marker)
Expand All @@ -38,7 +38,7 @@ def test_should_raise_attribute_error_when_is_missing_params(self, marker):
)
def test_it_should_add_to_marker_list_a_new_valid_marker(self, marker):
"""
Test check if add_marker is adding a new market to markers_list.
Test check if add_marker is adding a new market to markers_list.
"""
self.google_map.add_marker(**marker)
assert len(self.google_map.markers) == 1
Loading

0 comments on commit 093f143

Please sign in to comment.