Esempio n. 1
0
def make_pdf(base_url,
             main_template,
             header_template,
             main_css='',
             header_css=''):
    html = HTML(base_url=base_url, string=main_template)
    main_doc = html.render(stylesheets=[])

    def get_page_body(boxes):
        for box in boxes:
            if box.element_tag == 'body':
                return box
            return get_page_body(box.all_children())

    # Template of header
    html = HTML(base_url=base_url, string=header_template)
    header = html.render(
        stylesheets=[CSS(string='@page {size:A4; margin:1cm;}')])

    header_page = header.pages[0]
    header_body = get_page_body(header_page._page_box.all_children())
    header_body = header_body.copy_with_children(header_body.all_children())

    for page in main_doc.pages:
        page_body = get_page_body(page._page_box.all_children())
        page_body.children += header_body.all_children()

    pdf_file = main_doc.write_pdf()

    return pdf_file
Esempio n. 2
0
    def authenticate_and_render_view(self, skip_auth=False):
        """ Uses attributes in self to attempt to authenticate a user and render
        an HTML view for them. """

        auth = admin.authenticate(self.username, self.password)

        if auth == False:
            msg = "Failed to authenticate user '%s' and render HTML view!" % (
                self.username)
            self.logger.error(msg)
            raise Exception(msg)
        elif auth == True:
            s = session.Session()
            session_id = s.new(self.username, self.password)
            new_sesh = utils.mdb.sessions.find_one({"_id": session_id})
            s.User.mark_usage("authenticated successfully")

            # handle preserve sessions checkbox on the sign in view
            if "keep_me_signed_in" in self.params:
                if "preferences" not in s.User.user:
                    s.User.user["preferences"] = {}
                s.User.user["preferences"]["preserve_sessions"] = True
                utils.mdb.users.save(s.User.user)

            output, body = s.current_view_html()
            html.render(
                output,
                body_class=body,
                head=[
                    self.set_cookie_js(new_sesh["_id"],
                                       new_sesh["access_token"])
                ],
            )
  def get(self, suffix):

    output = ''
    entries = recent_entries(False)

    if not suffix or suffix == '.html' or suffix == 'htm':
      params = {
        'queryTimeElapsed':elapsed_time(),
        'entries':entries
      }

      output = html.render('blog.html', **params)

    elif suffix == '.json':
      raw_entries = []

      for entry in entries:
        raw_entries.append({
          "subject":entry.subject,
          "content":entry.content,
          "created":entry.created.strftime("%Y-%m-%d %H:%M:%S")
        })

      output = json.dumps(raw_entries)

    else:
      self.error(404)

    self.response.out.write(output)
Esempio n. 4
0
def x(environ, start_response):
  path = environ['PATH_INFO'].lstrip('/').split('/', 1)

  if path == ['']: # Root
    return ok200(start_response, commit_list(cache.commit_list()))

  if path == ['static', 'site.css']:
    return ok200(start_response, CSS, 'text/css')

  sha = path[0]
  if len(sha) != 40:
    raise ValueError('incorrect length %r' % (sha,))
  if not sha.isalnum():
    raise ValueError('invalid %r' % (sha,))

  if len(path) == 1: # Just render the state.
    I = cache.get_interpreter_from_sha(sha)
    return ok200(start_response, render(I, sha))

  command = path[1]
  if not command.replace('_', '').isalnum():
    raise ValueError('invalid %r' % (command,))

  if command == 'interpret':
    command = parse_post(environ).split()
  else:
    command = [command]

  new_sha = cache.step(sha, command)

  start_response('301 Redirect', [('Location', '/' + new_sha)])
  return []
  def get(self, identifier):
    entry = Entry.get_by_id(int(identifier))

    if entry:
      params = {
        'queryTimeElapsed':elapsed_time(identifier),
        'entries':recent_entries(identifier = identifier)
      }

      self.response.write(html.render('blog.html', **params))

    else:
      self.response.write("<h1>No entry found!</h1>")
    def post(self):
      subject = self.request.get('subject')
      content = self.request.get('content')

      if subject and content:
        entry = Entry(subject=subject, content=content)
        add_entry(entry)

        self.redirect("/unit3/blog/{0}".format(entry.key().id()))
      else:
        params = {
          'subject':subject,
          'content':content,
          'error':'We need both subject and content!'
        }

        self.response.write(html.render('newpost.html', **params))
 def get(self):
   self.response.write(html.render('newpost.html'))
 def post(self):
   user_input = self.request.get('text')
   params = {"text": encode(user_input)}
   self.response.out.write(html.render('rot13.html', **params))
 def get(self):
   params = {"text": ""}
   self.response.out.write(html.render('rot13.html', **params))
Esempio n. 10
0
 def get(self):
   self.response.out.write(html.render('lab.html'))
Esempio n. 11
0
    def process_params(self, user_action=None):
        """ All cgi.FieldStorage() params passed to this object on init
        need to be processed. This does ALL OF THEM at once. """

        #
        #   dashboard-based, user operation params
        #

        if "update_user_preferences" in self.params:
            self.User.update_preferences(self.params)
            user_action = "updated user preferences"

        if "change_password" in self.params:
            if "password" in self.params and "password_again" in self.params:
                self.User.update_password(self.params["password"].value, self.params["password_again"].value)
                user_action = "updated password"
            else:
                user_action = "failed to update password"

        # do error reporting
        if "error_report" in self.params and "body" in self.params:
            self.report_error()

        #
        #   change view operations, incl. with/without an asset
        #

        # change to a generic view without an asset
        if "change_view" in self.params:
            target_view = self.params["change_view"].value
            user_action = self.change_current_view(target_view)

        # change to a view of an asset
        for p in ["view_campaign", "view_settlement", "view_survivor"]:
            if p in self.params:
                user_action = self.change_current_view_to_asset(p)

        # these are our two asset removal methods: this is as DRY as I think we
        #   can get with this stuff, since both require unique handling
        if "remove_settlement" in self.params:
            s_id = ObjectId(self.params["remove_settlement"].value)
            self.set_current_settlement(s_id)
            S = assets.Settlement(settlement_id=s_id, session_object=self)
            S.remove()
            user_action = "removed settlement %s" % S
            self.change_current_view("dashboard")

        if "remove_survivor" in self.params:
            # we actually have to get the survivor from the MDB to set the
            # current settlement before we can initialize the survivor and
            # use its remove() method.
            s_id = ObjectId(self.params["remove_survivor"].value)
            s_doc = mdb.survivors.find_one({"_id": s_id})
            self.set_current_settlement(s_doc["settlement"])
            S = assets.Survivor(survivor_id=s_id, session_object=self)
            S.remove()
            user_action = "removed survivor %s from %s" % (S, S.Settlement)
            self.change_current_view("view_campaign", asset_id=S.survivor["settlement"])


        # user and campaign exports
        if "export_user_data" in self.params:
            export_type = self.params["export_user_data"].value
            if "asset_id" in self.params and self.User.is_admin():
                user_object = assets.User(user_id=self.params["asset_id"].value, session_object=self)
                filename = "%s_%s.kdm-manager_export.%s" % (datetime.now().strftime(ymd), user_object.user["login"], export_type.lower())
                payload = user_object.dump_assets(dump_type=export_type)
            else:
                payload = self.User.dump_assets(dump_type=export_type)
                filename = "%s_%s.kdm-manager_export.%s" % (datetime.now().strftime(ymd), self.User.user["login"], export_type.lower())
            self.User.mark_usage("exported user data (%s)" % export_type)
            self.logger.debug("[%s] '%s' export complete. Rendering export via HTTP..." % (self.User, export_type))
            html.render(str(payload), http_headers="Content-Disposition: attachment; filename=%s\n" % (filename))
        if "export_campaign" in self.params:
            export_type = self.params["export_campaign"].value
            C = assets.Settlement(settlement_id=ObjectId(self.params["asset_id"].value), session_object=self)
            payload, length = C.export(export_type)
            filename = "%s_-_%s.%s" % (datetime.now().strftime(ymd), C.settlement["name"], export_type.lower())
            self.User.mark_usage("exported campaign data as %s" % export_type)
            self.logger.debug("[%s] '%s' export complete. Rendering export via HTTP..." % (self.User, export_type))
            html.render(payload, http_headers="Content-type: application/octet-stream;\r\nContent-Disposition: attachment; filename=%s\r\nContent-Title: %s\r\nContent-Length: %i\r\n" % (filename, filename, length))


        #
        #   settlement operations - everything below uses user_asset_id
        #       which is to say that all forms that submit these params use
        #       the asset_id=mdb_id convention.

        user_asset_id = None
        if "asset_id" in self.params:
            user_asset_id = ObjectId(self.params["asset_id"].value)


        #   create new user assets

        if "new" in self.params:

            #
            #   new survivor creation via API call
            #

            if self.params["new"].value == "survivor":
                self.set_current_settlement(user_asset_id)

                POST_params = {"settlement": self.Settlement.settlement["_id"]}
                incoming_form_params = ["name","sex","survivor_avatar","father","mother","email","public"]
                for p in incoming_form_params:
                    if p in self.params and self.params[p].value not in ["",u""]:
                        if "string:" in self.params[p].value:
                            oid = self.params[p].value.split("string:")[1]
                            POST_params[p] = oid
                        else:
                            POST_params[p] = self.params[p].value
                    else:
                        pass

                response = api.post_JSON_to_route("/new/survivor", payload=POST_params, Session=self)
                if response.status_code == 200:
                    s_id = ObjectId(response.json()["sheet"]["_id"]["$oid"])
                    self.change_current_view("view_survivor", asset_id=s_id)
                    S = assets.Survivor(s_id, session_object=self)
                    user_action = "created survivor %s in %s" % (S, self.Settlement)
                else:
                    msg = "An API error caused survivor creation to fail! API response was: %s - %s" % (response.status_code, response.reason)
                    self.logger.error("[%s] new survivor creation failed!" % self.User)
                    self.logger.error("[%s] %s" % (self.User, msg))
                    raise RuntimeError(msg)


            #
            #   new settlement creation via API call
            #

            if self.params["new"].value == "settlement":

                params = {}
                params["campaign"] = self.params["campaign"].value

                # try to get a name or default to None
                if "name" in self.params:
                    params["name"] = self.params["name"].value
                else:
                    params["name"] = None

                # try to get expansions/survivors params or default to []
                for p in ["expansions", "survivors", "specials"]:
                    if p not in self.params:
                        params[p] = []
                    elif p in self.params and isinstance(self.params[p], cgi.MiniFieldStorage):
                        params[p] = [self.params[p].value]
                    elif p in self.params and type(self.params[p]) == list:
                        params[p] = [i.value for i in self.params[p]]
                    else:
                        msg = "Invalid form parameter! '%s' is unknown type: '%s'" % (p, type(self.params[p]).__name__)
                        self.logger.error("[%s] invalid param key '%s' was %s. Params: %s" % (self.User, p, type(self.params[p]), self.params))
                        raise AttributeError(msg)

                # hit the route; check the response
                response = api.post_JSON_to_route("/new/settlement", payload=params, Session=self)
                if response.status_code == 200:
                    s_id = ObjectId(response.json()["sheet"]["_id"]["$oid"])
                    self.set_current_settlement(s_id)
                    S = assets.Settlement(s_id, session_object=self)
                    user_action = "created settlement %s" % self.Settlement
                    self.change_current_view("view_campaign", S.settlement["_id"])
                    S.save()
                elif response.status_code == 405:
                    self.change_current_view('dashboard')
                else:
                    msg = "An API error caused settlement creation to fail! API response was: %s - %s" % (response.status_code, response.reason)
                    self.logger.error("[%s] new settlement creation failed!" % self.User)
                    self.logger.error("[%s] %s" % (self.User, msg))
                    raise RuntimeError(msg)


        #   bulk add

        if "bulk_add_survivors" in self.params:

            self.set_current_settlement(user_asset_id)
            S = assets.Settlement(settlement_id=user_asset_id, session_object=self)
            male = int(self.params["male_survivors"].value)
            female = int(self.params["female_survivors"].value)

            for tup in [("M", male), ("F",female)]:
                letter, sex = tup
                for i in range(sex):
                    POST_params = {"settlement": self.Settlement.settlement["_id"], "sex": letter, "public": True,}
                    response = api.post_JSON_to_route("/new/survivor", payload=POST_params, Session=self)
                    if response.status_code == 200:
                        pass
                    else:
                        msg = "An API error caused survivor creation to fail! API response was: %s - %s" % (response.status_code, response.reason)
                        self.logger.error("[%s] new survivor creation failed!" % self.User)
                        self.logger.error("[%s] %s" % (self.User, msg))
                        raise RuntimeError(msg)

            user_action = "added %s male and %s survivors to %s" % (male, female, self.Settlement)
            self.change_current_view("view_campaign", user_asset_id)


        #   modify

        if "modify" in self.params:
            if self.params["modify"].value == "settlement":
                s = mdb.settlements.find_one({"_id": ObjectId(user_asset_id)})
                self.set_current_settlement(s["_id"])
                S = assets.Settlement(settlement_id=s["_id"], session_object=self)
                S.modify(self.params)
                user_action = "modified settlement %s" % self.Settlement

            if self.params["modify"].value == "survivor":

                update_mins = True
                if "norefresh" in self.params:
                    update_mins = False

                s = mdb.survivors.find_one({"_id": ObjectId(user_asset_id)})
                self.set_current_settlement(s["settlement"], update_mins)
                S = assets.Survivor(survivor_id=s["_id"], session_object=self)
                S.modify(self.params)
                user_action = "modified survivor %s of %s" % (S, self.Settlement)

        self.User.mark_usage(user_action)