Skip to content

Instantly share code, notes, and snippets.

@garaud
Last active January 4, 2017 10:22
Show Gist options
  • Save garaud/e141b530f80e28e58d05e0651444cffb to your computer and use it in GitHub Desktop.
Save garaud/e141b530f80e28e58d05e0651444cffb to your computer and use it in GitHub Desktop.
Simple snippet to get the latest entries from the MongoDB ClojureNews data in order to send a weekly digest email
# -*- coding: utf-8 -*-
from datetime import datetime
from dateutil.relativedelta import relativedelta
import pymongo
from pymongo import MongoClient
from jinja2 import Template
URI = "mongodb://localhost"
TEMPLATE = 'template.html'
def last_week(entry):
"""Get all latest entries since last week
"""
current = datetime.now()
previous = current - relativedelta(days=7)
return list(entry
.find({"created-date": {"$lt": current,
"$gt": previous}})
.sort([("created-date", pymongo.DESCENDING)]))
if __name__ == '__main__':
client = MongoClient(URI)
db = client['clojurenews']
entry = db['entry']
# all entries
rset = list(entry.find().sort([('created-date', pymongo.DESCENDING)]))
last_entries = last_week(db['entry'])
last_comments = last_week(db['comment-entry'])
current = datetime.now().strftime("%Y-%m-%d")
with open(TEMPLATE) as fobj:
template = Template(fobj.read())
report = template.render(collection=last_entries, date=current)
# Do not generate the file if there is no data
if last_entries:
with open('report.html', 'w') as fobj:
fobj.write(report)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h3>Clojure News &ndash; Latest Entries</h3>
From {{date}}
<p>
<ul>
{% for item in collection %}
<li><a href="{{item['url']}}">{{item['title']}}</a> par {{item['created-by']|capitalize}}</li>
{% endfor %}
</ul>
</p>
</div>
</body>
<center>
<footer>
<a href="https://clojure.news/">ClojureNews Web site</a> powered by <a href="http://clojure.org/">Clojure</a> and <a href="https://www.python.org/">Python</a>
</footer>
</center>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment