from django.core.management.base import NoArgsCommand, CommandError
from django.core.files.base import ContentFile
from main.webkit2png import WebkitRenderer, init_qtgui
# Models
from main.models import Website
class Command(NoArgsCommand):
'''
This manage.py command is used with cron to update screenshots for Websites
'''
help = 'Use this command to update website screenshots No arguments needed'
def handle_noargs(self, **options):
# Get websites which don't have their screenshots set yet
websites = Website.objects.filter(screenshot_active = False)
# Init renderer
app = init_qtgui()
renderer = WebkitRenderer()
# Parameters
renderer.format = 'png'
renderer.width = 1024
renderer.height = 500
renderer.format = 'png'
for website in websites:
# Render screenshot to website.screenshot (ImageField)
file_contents = renderer.render_to_bytes(website.url)
website.screenshot.save('%s.png' % website.slug, ContentFile(file_contents), save=True)
website.screenshot_active = True
website.save()
I have been running around with this problem for a while now: How to create website screenshots for my Django app. Here's a management command that can be used with cron to update screenshots for sites using this amazing python script:
github.com/AdamN/…
To get it working:
- Use Ubuntu with xvfb and python-qt4, libqt4-webkit packages installed
- Copy webkit2png.py under your app (in my case main app)
- Start Xvfb and set it to $DISPLAY with this:
- $ Xvfb :25 -screen 0 1024x10000x24 &
- $ export DISPLAY=127.0.0.1:25.0
- Store the code into file project/main/management/command/generate_screenshot.py (remember init.py for both management and command folders) – see django docs for more about custom management commands
- Run using python manage.py generate_screenshots
This should get you started. Webkit2png's code is rather easy to read if you want to change renderer parameters etc. Of course you might also want to use task queuing instead of cron but that one is easy to change.
Hope this saves some work hours for you :)
Ps. With Linux webkit2png.py really seems to be the easiest solution by far. If you know anything else, please ping me!