import webapp2
import csv
import time

from google.appengine.api import logservice
from google.appengine.api import files

import config

class Level2Handler(webapp2.RequestHandler):
  def get(self):
    # Create a new Google Storage file
    filename = 'request.csv'
    gs_file ='/gs/%s/%s' % (config.gs_bucket_name, filename),
    with, 'a') as f:
        # Create a csv writer that outputs to the Google Storage file
        w = csv.writer(f)
        for r in logservice.fetch(start_time=time.time()-5*60):
                        r.user_agent if r.user_agent else "NULL"])
    # Finalize the file

    # Render a HTML link to the file in the reponse body
    link_format = '{gs_bucket}/{filename}'
    link = link_format.format(gs_bucket=config.gs_bucket_name, filename=filename)
    self.response.write('<a href="{link}">{link}</a>'.format(link=link))

app = webapp2.WSGIApplication([('/solution/level2', Level2Handler)], debug=True)