Skip to content

Instantly share code, notes, and snippets.

@yuchant
Created January 30, 2014 10:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yuchant/312d42568192a2bf3acc to your computer and use it in GitHub Desktop.
Save yuchant/312d42568192a2bf3acc to your computer and use it in GitHub Desktop.
import re
from flask import render_template, request
from . import module
from grovemade import cache
from grovemade_admin.shop.shopify_sync import shopify
from BeautifulSoup import BeautifulSoup
GROVE_BLOG_ID = 2839566
@cache.memoize(timeout=60*30)
def get_all_shopify_posts():
'''
Get all blog posts from Shopify API.
- Get posts from shopify until exhausted. This can take many seconds. Cache.
- Post process posts to be more consistent
- extract first image
- remove tags
'''
def strip_tags(text):
return re.sub('<[^<]+?>', '', text)
def get_first_image_src(html):
tree = BeautifulSoup(html)
img = tree.find('img')
return img.get('src') if img else None
def get_shopify_posts(since_id=None):
return list(shopify.Article(prefix_options={'GROVE_BLOG_ID': GROVE_BLOG_ID}).find(
limit=250,
published_status='published',
since_id=since_id,
))
posts = get_shopify_posts()
blog_posts = posts
# keep calling shopify until results exhausted
while len(posts) == 250:
posts = get_shopify_posts(since_id=posts[-1].id)
blog_posts.extend(posts)
blog_posts.reverse()
# update shopify posts with our own cleaned data
for post in blog_posts:
post.cleaned_body = strip_tags(post.body_html)
post.first_image = get_first_image_src(post.body_html)
return blog_posts
def get_page(page, paginate_by=25):
'''
Paginator
'''
posts = get_all_shopify_posts()
posts_by_slice = [posts[i:i+paginate_by] for i in range(0, len(posts), paginate_by)]
return posts_by_slice[page]
@module.route('/')
@module.route('/<int:page>/')
def index(page=0):
ctx = {
'blog_posts': get_page(page, paginate_by=30),
}
return render_template('blog/index.html', **ctx)
@module.route('/<int:id>/<title>/')
@cache.cached(timeout=60)
def post_detail(id, title):
ctx = {
'blog_post': shopify.Article(prefix_options={'GROVE_BLOG_ID': GROVE_BLOG_ID}).find(id)
}
return render_template('blog/detail.html', **ctx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment