본문 바로가기

Python

Python 프로그래밍


# -*- coding:utf-8 -*-

import commands, datetime, os, daemon, shutil, urllib, sys
from bottle import route, run, template, request

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
LOG_DIR = '/screenshot/daemon.log'

if not os.path.isfile(LOG_DIR):
  os.mkdir('/screenshot/')
if not os.path.isdir('%s/output' % CURRENT_DIR):
  os.mkdir('%s/output' % CURRENT_DIR)

LOG = open(LOG_DIR, 'a')

@route('/')
def index():
  url = request.query.url or ''
  res = request.query.res or '1200x1024'
  now = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
  output_dir = '%s/output/%s' % (CURRENT_DIR, now)
  os.mkdir(output_dir)
  cmd = u'cd %s; pageres "%s" %s' % (output_dir, url, res.replace('%20',' '))
  print cmd
  output = run_command(cmd)
  png = run_command('cd %s; ls *.png' % output_dir)
  ret = ''
  if 'Successfully generated' in output:
    if request.query.type == 'base64':
      ret = 'https://t1.daumcdn.net/cfile/tistory/273DBC4956E644210C"rb").read().encode("base64"))
    else:
      new_name = png.replace('?','-').replace('&','-').replace('=','_').replace('!','-').replace('%','P')
      shutil.move('%s/%s' % (output_dir, png), '%s/%s' % (output_dir, new_name))
      ret = 'http://screenshot.dev.com/%s/%s' % (now, new_name)
    if request.query.callback:
      ret = '%s("%s")' % (request.query.callback, ret)
    return ret
  else:
    return output + 'xx' + png 
def run_command(cmd):
  cmd = cmd.encode('utf-8')
  return commands.getoutput(cmd)
def start_server():
  run(host='0.0.0.0', port=18190)
with daemon.DaemonContext(stderr=LOG, stdout=LOG):
  start_server()
#start_server()