Skip to content

Commit

Permalink
Reformat code with Black
Browse files Browse the repository at this point in the history
  • Loading branch information
suminb committed Oct 30, 2019
1 parent fba84c1 commit e6b90b4
Show file tree
Hide file tree
Showing 9 changed files with 107 additions and 97 deletions.
19 changes: 10 additions & 9 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
from web import create_app


if __name__ == '__main__':
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 8024))
debug = bool(os.environ.get('DEBUG', 0))
if __name__ == "__main__":
host = os.environ.get("HOST", "0.0.0.0")
port = int(os.environ.get("PORT", 8024))
debug = bool(os.environ.get("DEBUG", 0))

app = create_app(config={'DEBUG': debug})
app = create_app(config={"DEBUG": debug})
app.run(host=host, port=port)

if app.config['DEBUG']:
if app.config["DEBUG"]:
from werkzeug import SharedDataMiddleware
import os
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
'/': os.path.join(os.path.dirname(__file__), 'static')
})

app.wsgi_app = SharedDataMiddleware(
app.wsgi_app, {"/": os.path.join(os.path.dirname(__file__), "static")}
)
18 changes: 7 additions & 11 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,19 @@

def readme():
try:
with open('README.rst') as f:
with open("README.rst") as f:
return f.read()
except FileNotFoundError:
return '(Could not read from README.rst)'
return "(Could not read from README.rst)"


setup(
name='web',
name="web",
version=web.__version__,
description='Personal website',
description="Personal website",
long_description=readme(),
url='http://github.com/suminb/web',
license='GPLv3',
url="http://github.com/suminb/web",
license="GPLv3",
packages=find_packages(),
entry_points={
'console_scripts': [
'web = web.__main__:cli'
]
},
entry_points={"console_scripts": ["web = web.__main__:cli"]},
)
24 changes: 13 additions & 11 deletions web/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,19 @@
from markdown.extensions.footnotes import FootnoteExtension


__version__ = '2.4.1'
__version__ = "2.4.1"


#
# Custom filters for Jinja
#
@evalcontextfilter
def format_tags(eval_ctx, value, attr=''):
def format_tags(eval_ctx, value, attr=""):
def f(x):
return '<span class="tag %s"><a href="/tag/%s">%s</a></span>' \
% (attr, x, x)
return '<span class="tag %s"><a href="/tag/%s">%s</a></span>' % (attr, x, x)

if isinstance(value, list):
return Markup(' '.join(map(f, value)))
return Markup(" ".join(map(f, value)))
else:
return Markup(f(value))

Expand All @@ -31,28 +30,31 @@ def optional_url(eval_ctx, name, url):


@evalcontextfilter
def markdown(eval_ctx, value, attr=''):
def markdown(eval_ctx, value, attr=""):
return markdown_(value, extensions=[FootnoteExtension()])


def create_app(name=__name__, config=None, static_folder='static',
template_folder='templates'):
def create_app(
name=__name__, config=None, static_folder="static", template_folder="templates"
):
if config is None:
config = {}

app = Flask(name)
app.config.update(config)

if app.debug:
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config["TEMPLATES_AUTO_RELOAD"] = True

from web.models import CustomJSONEncoder

app.json_encoder = CustomJSONEncoder

from web.main import main_module
app.register_blueprint(main_module, url_prefix='')

filters = ['format_tags', 'optional_url', 'markdown']
app.register_blueprint(main_module, url_prefix="")

filters = ["format_tags", "optional_url", "markdown"]
for filter_ in filters:
app.jinja_env.filters[filter_] = globals()[filter_]

Expand Down
49 changes: 26 additions & 23 deletions web/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@
from oauth2client.service_account import ServiceAccountCredentials

from web import create_app
from web.utils import (CATEGORY_COLUMN, POSTAL_ADDRESS_COLUMN, geocoding,
is_valid_coordinate, update_geocoordinate)
from web.utils import (
CATEGORY_COLUMN,
POSTAL_ADDRESS_COLUMN,
geocoding,
is_valid_coordinate,
update_geocoordinate,
)

StreamHandler(sys.stderr).push_application()
log = Logger(__name__)
Expand All @@ -30,24 +35,25 @@ def build():


@cli.command()
@click.argument('gspread_key')
@click.argument("gspread_key")
def import_gspread(gspread_key):
scope = ['https://spreadsheets.google.com/feeds']
scope = ["https://spreadsheets.google.com/feeds"]

log.info('Authentication in progress...')
log.info("Authentication in progress...")
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'sumin-labs-hrd.json', scope)
"sumin-labs-hrd.json", scope
)
gc = gspread.authorize(credentials)

sheet = gc.open_by_key(gspread_key)
worksheet = sheet.sheet1

log.info('Getting all values from the sheet...')
log.info("Getting all values from the sheet...")
values = worksheet.get_all_values()

geojson = {
'type': 'FeatureCollection',
'features': [],
"type": "FeatureCollection",
"features": [],
}

for row_index, row in enumerate(values[1:], start=1):
Expand All @@ -56,32 +62,29 @@ def import_gspread(gspread_key):
try:
coordinate = [float(x) for x in row[2:4]]
except ValueError:
log.info('Geocoding {0}...', postal_address)
log.info("Geocoding {0}...", postal_address)
coordinate = geocoding(postal_address)
log.info('Updating the spreadsheet with {0}...', coordinate)
log.info("Updating the spreadsheet with {0}...", coordinate)
update_geocoordinate(worksheet, row_index, coordinate)
else:
log.info('Fetched geocoding: {0} -> {1}',
postal_address, coordinate)
log.info("Fetched geocoding: {0} -> {1}", postal_address, coordinate)

if not is_valid_coordinate(coordinate):
log.warn('{0} is not a valid coordinate', coordinate)
log.warn("{0} is not a valid coordinate", coordinate)
continue

feature = {
'type': 'Feature',
'properties': {
'category': trip_category,
"type": "Feature",
"properties": {"category": trip_category,},
"geometry": {
"type": "Point",
"coordinates": [coordinate[1], coordinate[0]],
},
'geometry': {
'type': 'Point',
'coordinates': [coordinate[1], coordinate[0]],
}
}
geojson['features'].append(feature)
geojson["features"].append(feature)

print(json.dumps(geojson))


if __name__ == '__main__':
if __name__ == "__main__":
cli()
46 changes: 23 additions & 23 deletions web/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,62 +7,62 @@
from web.models import ExperienceCollection


main_module = Blueprint('main', __name__, template_folder='templates/main')
main_module = Blueprint("main", __name__, template_folder="templates/main")

StreamHandler(sys.stderr).push_application()
log = Logger(__name__)

DATA_FILE = 'data/experiences.yml'
DATA_FILE = "data/experiences.yml"


@main_module.route('/')
@main_module.route("/")
def index():
# FIXME: Could we automate this part somehow? (current_page)
return render_template('index.html', **{'current_page': 'index'})
return render_template("index.html", **{"current_page": "index"})


@main_module.route('/coding-expedition.html')
@main_module.route("/coding-expedition.html")
def coding_expedition():
context = {
'current_page': 'coding_expedition',
'google_maps_api_key': os.environ['GOOGLE_MAPS_API_KEY'],
"current_page": "coding_expedition",
"google_maps_api_key": os.environ["GOOGLE_MAPS_API_KEY"],
}
return render_template('coding_expedition.html', **context)
return render_template("coding_expedition.html", **context)


@main_module.route('/experience.html')
@main_module.route("/experience.html")
def experience_summary():
context = {
'current_page': 'experience',
"current_page": "experience",
}
return render_template('experience_summary.html', **context)
return render_template("experience_summary.html", **context)


@main_module.route('/experiences/<key>.html')
@main_module.route("/experiences/<key>.html")
def experience(key):
collection = ExperienceCollection.load(DATA_FILE)
# FIXME: Code refactoring required
try:
experience = collection[key]
except KeyError:
return '', 404
return "", 404

if not experience.published and not os.environ.get('DEBUG'):
return '', 404
if not experience.published and not os.environ.get("DEBUG"):
return "", 404

context = {
'current_page': 'experience',
'collection': collection,
'experience': experience,
"current_page": "experience",
"collection": collection,
"experience": experience,
}
return render_template('experience.html', **context)
return render_template("experience.html", **context)


@main_module.route('/experiences/tags/<tag>.html')
@main_module.route("/experiences/tags/<tag>.html")
def experiences_with_tag(tag):
collection = ExperienceCollection.load(DATA_FILE)
context = {
'current_page': 'experience',
'experiences': collection.find_experiences_with_tag(tag),
"current_page": "experience",
"experiences": collection.find_experiences_with_tag(tag),
}
return render_template('experiences.html', **context)
return render_template("experiences.html", **context)
25 changes: 16 additions & 9 deletions web/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,29 @@


class CustomJSONEncoder(JSONEncoder):

def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%dT%H:%M')
return obj.strftime("%Y-%m-%dT%H:%M")
else:
return super(JSONEncoder, self).default(obj)


class Loader(yaml.SafeLoader):

def __init__(self, stream):
self._root = os.path.split(stream.name)[0]
super(Loader, self).__init__(stream)

def include(self, node):
filename = os.path.join(self._root, self.construct_scalar(node))
_, ext = os.path.splitext(filename)
with open(filename, 'r') as f:
if ext == '.yml':
with open(filename, "r") as f:
if ext == ".yml":
return yaml.load(f, Loader)
else:
return f.read()


Loader.add_constructor('!include', Loader.include)
Loader.add_constructor("!include", Loader.include)


class ExperienceCollection:
Expand Down Expand Up @@ -68,9 +66,18 @@ def load(cls, yaml_file):


class Experience:

def __init__(self, key, published, parent, title, description, starts_at,
ends_at, category, tags):
def __init__(
self,
key,
published,
parent,
title,
description,
starts_at,
ends_at,
category,
tags,
):
self.key = key
self.published = published
self.key = key
Expand Down
7 changes: 3 additions & 4 deletions web/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@
def testapp(request):
"""Session-wide test `Flask` application."""
settings_override = {
'TESTING': True,
'DEBUG': True,
"TESTING": True,
"DEBUG": True,
}
app = create_app(__name__, config=settings_override,
template_folder='../templates')
app = create_app(__name__, config=settings_override, template_folder="../templates")

# Establish an application context before running the tests.
ctx = app.app_context()
Expand Down
2 changes: 1 addition & 1 deletion web/tests/test_basic.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
def test_pages(testapp):
pages = ('/',)
pages = ("/",)
for page in pages:
resp = testapp.get(page)
assert resp.status_code == 200
Loading

0 comments on commit e6b90b4

Please sign in to comment.