Example #1
0
 def get(self):
     id = get_user_id()
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 "upload_url": blobstore.create_upload_url("/profile"),
                 "user_email": get_user_email(),
                 "login_url": users.create_login_url(),
                 "logout_url": users.create_logout_url("/"),
                 "user_id": get_user_id(),
                 "profile": models.getUser(id),
                 "admin": is_admin,
             }
             render_template(self, "createProfile.html", page_params)
             return
     newList = models.getCategoryList()
     page_params = {
         "catList": newList,
         "upload_urlQ": blobstore.create_upload_url("/NewQuestion"),
         "user_email": get_user_email(),
         "login_url": users.create_login_url(),
         "logout_url": users.create_logout_url("/"),
         "user_id": id,
         "admin": is_admin,
     }
     render_template(self, "newQuestionSubmit.html", page_params)
Example #2
0
 def get(self):
     questionID = self.request.get("id")
     id = get_user_id()
     review = models.getQuestionFromURL(questionID)
     is_admin = 0
     if users.is_current_user_admin():
         is_admin = 1
     if id is not None:
         q = models.check_if_user_exists(id)
         if q == None:
             page_params = {
                 "upload_url": blobstore.create_upload_url("/profile"),
                 "user_email": get_user_email(),
                 "login_url": users.create_login_url(),
                 "logout_url": users.create_logout_url("/"),
                 "user_id": get_user_id(),
                 "profile": models.getUser(id),
                 "admin": is_admin,
             }
             render_template(self, "createProfile.html", page_params)
             return
     page_params = {
         "upload_urlQE": blobstore.create_upload_url("/ReviewQuestion?id=" + questionID),
         "user_email": get_user_email(),
         "login_url": users.create_login_url(),
         "logout_url": users.create_logout_url("/"),
         "user_id": id,
         "review": review,
         "admin": is_admin,
     }
     render_template(self, "questionReview.html", page_params)
    def get(self):
        # template_values={'upload_url':upload_url}
        template_values = {}
        fileName = self.request.get("fileName")
        if fileName:
            h = Helper()
            # check file name exists or not
            file_info = h.isFileExists(fileName)
            if file_info:
                val = self.request.get("overwrite")
                if val == "overwrite":
                    # delete existing blob and create new blob to upload if overwrite is checked
                    h.deleteBlob(file_info.blog_key)
                    # redirect to upload
                    upload_url = blobstore.create_upload_url("/upload")
                    template_values = {"upload_url": upload_url}
                    path = os.path.join(os.path.dirname(__file__), "create.html")
                    self.response.out.write(template.render(path, template_values))
                else:
                    template_values["message"] = "file name already exists !"
                    path = os.path.join(os.path.dirname(__file__), "create_pre.html")
                    self.response.out.write(template.render(path, template_values))
            else:
                upload_url = blobstore.create_upload_url("/upload")
                template_values = {"upload_url": upload_url}
                path = os.path.join(os.path.dirname(__file__), "create.html")
                self.response.out.write(template.render(path, template_values))

        else:
            path = os.path.join(os.path.dirname(__file__), "create_pre.html")
            self.response.out.write(template.render(path, template_values))
    def get(self):
        upload_url = blobstore.create_upload_url("/upload")
        self.response.out.write(
            """<html><link rel="stylesheet" href="/stylesheets/common.css" type="text/css" media="screen">
    <script src="/stylesheets/min.js"></script>
  
    <script>
	

function displayInline(contentUrl) {
  var iframe =
      '<iframe src="' + contentUrl + '" class="inlined-content"></iframe>';
  $('#inlined_content').html(iframe);
}

$(document).ready(function() {
 

  $('[data-action=delete]').click(function() {
    return confirm('Are you sure?');
  });

  $('#display_inline').click(function() {
    var url = $(this).data('content-uri');
	var fileName = $('#file_search').find(":selected").val();
	uri=url+fileName;
    displayInline(uri);
  });

  
});</script><body><div class='main'><h2> Cloud Music Box</h2></div>"""
        )
        self.response.out.write('<center><form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write(
            """Upload File:<input type="file" name="file"><input type="submit" name="submit" class="myButton" value="Submit"> </form>"""
        )
        load_url = blobstore.create_upload_url("/list")
        # self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % load_url)
        # self.response.out.write("""Load File:<input type="submit"
        # name="submit" class="myButton" value="Submit"> </form>""")

        # blob_obj = blobstore.BlobInfo.all()
        qry = EachUser.query(EachUser.author == users.get_current_user())

        self.response.out.write("<br/><br/><table><tr><th>File Name</th><th>Play</th></tr>")
        for q in qry:
            blob_obj = blobstore.BlobInfo.get(q.blobkey)
            self.response.write("<tr><td>%s :</td>" % blob_obj.filename)
            self.response.write(
                """<td><audio controls><source src="/serve/%s" type="audio/mpeg"></audio></td></tr>""" % q.blobkey
            )
        self.response.out.write("</table>")
        # self.response.out.write('<input type="button" id="try" value="list" onclick=/>')
        self.response.out.write(
            """
   <div id="inlined_content">
	
    </div><div id="alert"><!--<img src="/images/dogs-listening.jpg"/>--></center>"""
        )
        self.response.out.write("</body></html>")
Example #5
0
    def get(self):
        user = Session(self).get_current_user()
        if not user:
            nextPath = "=".join(("/login?continue", self.request.url))
            self.redirect(nextPath)
        else:
            targetUser = None

            # if the page was passed a userId look at that profile instead
            # Todo
            # If user.Id == ID (user looks at self) or user.isAdmin
            if self.request.get("userId"):
                targetUserId = long(self.request.get("userId"))
                targetUser = Account.get_by_id(targetUserId)
            # else the logged in user
            else:
                targetUser = user

            userUploadURL = blobstore.create_upload_url("/myProfilePhotoUpload")
            targetUserUploadURL = blobstore.create_upload_url("/changeUserDetails")
            template_values = {
                "user": user,
                "targetUser": targetUser,
                "userUploadURL": userUploadURL,
                "targetUserUploadURL": targetUserUploadURL,
            }
            template = JINJA_ENVIRONMENT.get_template("profile.html")
            self.response.write(template.render(template_values))
    def get(self, class_id):
        cls = Class.get_by_id(int(class_id))
        if not cls:
            self.abort(404)

        upload_to = blobstore.create_upload_url("/addmaterial")
        upload_video_to = blobstore.create_upload_url(uri_for("upload_video"))
        return self.render("app/class_detail.html", cls=cls, upload_to=upload_to, upload_video_to=upload_video_to)
    def testShowForm(self):
        self.mox.StubOutWithMock(blobstore, "create_upload_url")
        layer = model.Layer(name="a", world="earth")
        layer_id = layer.put().id()
        handler = resource.ResourceHandler()
        dummy_url = object()

        blobstore.create_upload_url("/resource-create/%d" % layer_id).AndReturn(dummy_url)

        self.mox.ReplayAll()
        self.assertEqual(handler.ShowForm(layer), {"upload_url": dummy_url})
Example #8
0
    def get(self, username):
        """display profile of user with username, if None, display logged in user
        """
        mode = self.request.get("mode")
        upload_url = ""

        if mode == "add_project":
            template = "profile/add_project.html"
            upload_url = blobstore.create_upload_url("/" + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
        elif mode == "edit_project":
            template = "profile/edit_project.html"
            upload_url = blobstore.create_upload_url("/" + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
        elif mode == "edit":
            template = "profile/edit.html"
        else:
            template = "profile/profile.html"

        user = User.get_user(username)

        if not user:
            user = User.save(username, "{}@someplace.com".format(username), "some long password")

        gravatar = user.avatar_url
        friends = []

        if user:
            all, ic, cc = self.organize_courses_for(user)

            if user.dob:
                dob = user.dob.strftime("%m/%d/%Y")
            else:
                dob = None

            projects = Project.get_projects_by_ids(user.projects)

            context = {
                "user": user,
                "dob": dob,
                "username": username,
                "gravatar": gravatar,
                "friends": friends,
                "friend_btn": False,
                "courses_all": Course.courses_to_dict(),
                "courses_completed": cc,
                "courses_incomplete": ic,
                "projects": projects,
                "upload_url": upload_url,
                "errors": {},
            }

            self.render(template, context)
        else:
            self.redirect("/logout")
    def testShowRaw(self):
        self.mox.StubOutWithMock(blobstore, "create_upload_url")
        layer = model.Layer(name="a", world="earth")
        layer_id = layer.put().id()
        handler = resource.ResourceHandler()
        handler.response = self.mox.CreateMockAnything()

        blobstore.create_upload_url("/resource-create/%d" % layer_id).AndReturn("Escape <me>!")
        blobstore.create_upload_url("/resource-bulk/%d" % layer_id).AndReturn("abc")
        handler.response.set_status(httplib.BAD_REQUEST)

        blobstore.create_upload_url("/resource-create/%d" % layer_id).AndReturn("q")
        blobstore.create_upload_url("/resource-bulk/%d" % layer_id).AndReturn("w")
        handler.response.set_status(httplib.OK)

        self.mox.ReplayAll()

        # Error specified.
        handler.request = {"error": "abc"}
        handler.response.out = StringIO.StringIO()
        handler.ShowRaw(layer)
        self.assertEqual(handler.response.out.getvalue(), "%d\n\nabc\nEscape &lt;me&gt;!\nabc" % httplib.BAD_REQUEST)

        # Result specified.
        handler.request = {"result": "def"}
        handler.response.out = StringIO.StringIO()
        handler.ShowRaw(layer)
        self.assertEqual(handler.response.out.getvalue(), "%d\ndef\n\nq\nw" % httplib.OK)
Example #10
0
File: main.py Project: kamuju/grad
    def get(self):
        user = users.get_current_user()
        if user:
            greeting = 'Welcome, %s! (<a href="%s">sign out</a>)' % (user.nickname(), users.create_logout_url("/"))
        else:
            greeting = '<a href="%s">Sign in or register</a>.' % users.create_login_url("/")

        self.response.out.write("<html><body>%s</body></html>" % greeting)
        # login_url = users.create_login_url(self.request.path)
        # logout_url = users.create_logout_url(self.request.path)

        uploads = None
        if user:
            q = UserUpload.all()
            q.filter("user =", user)
            q.ancestor(db.Key.from_path("UserUploadGroup", user.email()))
            uploads = q.fetch(100)
        try:
            if env and env.startswith("Google App Engine/"):
                # Connecting from App Engine
                self.response.out.write(
                    """<h1 style="text-align:center"> 
                                        Assignment 7 <br>
                                        Environment is Google App Engine</h1>"""
                )
                upload_url = blobstore.create_upload_url("/upload", gs_bucket_name=bucket_name)
            else:
                upload_url = blobstore.create_upload_url("/upload")
                self.response.out.write(
                    """<h1 style="text-align:center"> Assignment 7 <br>
                                    Environment is Local DEV</h1>"""
                )

            self.response.out.write("""<h2 style="text-align:center"> Uploads images</h2>""")

            template = template_env.get_template("home.html")
            context = {
                "user": user,
                "login_url": login_url,
                "logout_url": logout_url,
                "uploads": uploads,
                "upload_url": upload_url,
            }

            self.response.write(template.render(context))
        except Exception as e:
            self.response.write("Exception Occurred!!<br>")
            self.response.write(e.message)
            self.response.write(str(e.args))
Example #11
0
    def ShowRaw(self, layer):
        """Displays the result of Create(), as passed to it in the query string.

    The results are written in 5 lines:
      1. Status: BAD_REQUEST (400) if the "error" query argument is set.
         Otherwise OK (200).
      2. Result ID: The contents of the "result" query argument. This should be
         the ID(s) of the created resource(s) if any were created successfully.
         May be empty if creation failed.
      3. Error Message: The contents of the "error" query argument. May be empty
         if creation succeeded.
      4. Single Upload URL: A new upload URL that a user can use to upload
         another resource.
      5. Bulk Upload URL: A new upload URL that a user can use to bulk upload
         multiple resources.

    The status code is written out because on the client side, upload forms have
    to be submitted into an iframe and as a result the normal status code cannot
    be accessed through JS.

    GET Args:
      result: The ID of the created resource.
      error: An error message. Ignored if result is set.

    Args:
      layer: The layer to which the created resource belongs.
    """
        error = self.request.get("error")
        result = self.request.get("result")

        layer_id = layer.key().id()
        single_url = blobstore.create_upload_url("/resource-create/%d" % layer_id)
        bulk_url = blobstore.create_upload_url("/resource-bulk/%d" % layer_id)

        if error:
            status = httplib.BAD_REQUEST
        else:
            status = httplib.OK
        self.response.set_status(status)
        self.response.out.write(status)
        self.response.out.write("\n")
        self.response.out.write(cgi.escape(result or ""))
        self.response.out.write("\n")
        self.response.out.write(cgi.escape(error or ""))
        self.response.out.write("\n")
        self.response.out.write(cgi.escape(single_url))
        self.response.out.write("\n")
        self.response.out.write(cgi.escape(bulk_url))
Example #12
0
File: home.py Project: amgam/mIGs
    def get(self):
        user = users.get_current_user()
        if user:  # signed in already
            parent = ndb.Key("Persons", extract(users.get_current_user().nickname()))
            person = parent.get()  # checks in the db

            upload_url = blobstore.create_upload_url("/uploadimage")

            if person.face:
                url = images.get_serving_url(person.face)
                template = jinja_environment.get_template("profile.html")

                template_values = {
                    "user_name": person.name,
                    "room": person.room,
                    "hp": person.hp,
                    "image": url,
                    "upload_url": upload_url,
                    "logout": users.create_logout_url(self.request.host_url),
                }
            else:
                template_values = {
                    "user_name": person.name,
                    "room": person.room,
                    "hp": person.hp,
                    "upload_url": upload_url,
                    "logout": users.create_logout_url(self.request.host_url),
                }
                template = jinja_environment.get_template("profileblank.html")

            self.response.out.write(template.render(template_values))
        else:
            self.redirect(self.request.host_url)
Example #13
0
    def get(self):
        email = self.request.get("user")
        if not email:
            user = self.current_user
        else:
            user = users.User(email)

        invitations = Appointment.all().filter("invitee_list =", user.email())
        appointments = Appointment.all().filter("email =", user.email())
        photos = Photo.all().filter("user =", user)
        if not user == self.current_user:
            photos.filter("public =", True)
        files = File.all().filter("user =", user)
        if not user == self.current_user:
            files.filter("public =", True)

        upload_url = blobstore.create_upload_url("/upload")
        self.generate(
            "profile.html",
            {
                "photos": photos,
                "files": files,
                "appointments": appointments,
                "invitations": invitations,
                "upload_url": upload_url,
                "user": user,
            },
        )
Example #14
0
    def get(self):
        upload_url = blobstore.create_upload_url("/upload.html")
        self.response.out.write("<html><body>")
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write(
            """Upload File: <input type="file" name="file"><br> <input "type"="text" name="stream_id"><br/>
        <input type="submit"
        name="submit" value="Submit"></form></body></html>"""
        )

        def post(self):
            if not users.get_current_user():
                self.redirect("/")
                return

        if self.request.get("stream_id"):
            stream = models.Stream.get_by_id(int(self.request.get("stream_id")))

        if not stream:
            self.response.out.write(json.dumps({"status": "ERROR", "reason": "No stream found"}))

        photo = models.Photo(title=self.request.get("title", "untitled image"))
        image = self.request.get("img")
        photo.full_size_image = db.Blob(image)
        photo.stream = stream
        photo.comments = self.request.get("comments", "")
        output = photo.put()
        self.response.out.write(json.dumps({"status": "OK", "result": "Image upload success %s" % output}))
Example #15
0
    def get(self):
        # Get the latest N trails
        numTrails = self.request.get("n") if self.request.get("n") else self.defaultNum
        trails = Trail.query().order(Trail.creationDate)

        if self.request.get("remote") and self.request.get("callback"):
            # JSONP request. Render the content as json and wrap it in a function call
            trails = map(self._jsonEncoder, trails)
            jsonpContent = self.request.get("callback") + "(" + simplejson.dumps(trails) + ")"
            self.response.headers["Content-Type"] = "text/javascript"
            self.response.out.write(jsonpContent)
        elif self.request.headers["accept"] in ["application/json", "text/json"]:
            # Ajax request. Dump the list as json
            trails = map(self._jsonEncoder, trails)
            self.response.headers["Content-Type"] = "application/json"
            self.response.out.write(trails)
        else:
            # render the default view
            path = os.path.join("default/", "trails.html")
            uploadUrl = blobstore.create_upload_url("/trail")
            logging.warning("Upload url: " + self.request.get("link"))
            context = {
                "trails": trails,
                "uploadUrl": uploadUrl,
                "logoutUrl": users.create_logout_url("/"),
                "dialogId": "newTrailDialog",
                "formId": "newTrailForm",
            }
            self.render_template(path, **context)
Example #16
0
    def get(self):
        """ Returns a simple HTML form for create/edit publishing house """

        params = {}

        params["upload_url"] = blobstore.create_upload_url("/upload_logo")
        params["name"] = ""
        params["tagline"] = ""
        params["description"] = ""
        params["genres"] = []
        params["show_in_job_posts"] = ""
        params["logo_url"] = ""
        params["unsolicited"] = True
        params["there_is_ph"] = False

        if self.user:
            publishing_house = bmodels.PublishingHouse.get_by_ownerkey(self.user_key)
            if publishing_house:
                params["there_is_ph"] = True
                params["name"] = publishing_house.name
                params["tagline"] = publishing_house.tagline
                params["description"] = publishing_house.description
                if publishing_house.logo_key and publishing_house.logo_key != "":
                    params["logo_url"] = "/serve/%s" % publishing_house.logo_key
                params["genres"] = [str(i) for i in publishing_house.genres]
                params["show_in_job_posts"] = publishing_house.show_in_job_posts
                params["unsolicited"] = publishing_house.unsolicited

        params["fiction_genres"] = utils.genres_fiction
        params["nonfiction_genres"] = utils.genres_nonfiction

        return self.render_template("edit_publishing_house.html", **params)
Example #17
0
def build_graph(graph_id):
    g = UserGraph.get_by_id(graph_id)
    FINISH_URL = "/complete_upload/%s" % graph_id
    blobstore_url = blobstore.create_upload_url(FINISH_URL)

    url = "https://chart.googleapis.com/chart"
    data = {"cht": "gv:%s" % g.graph_type, "chl": g.dot, "chof": "png"}

    result = requests.post(url, params=data)

    if result.status_code != 200:
        # g.error = result.text
        # I really wish Google would provide more meaningful feedback when this fails
        g.error = "Failed to generate your graph (Error [%s]), perhaps a syntax error?" % result.status_code
        g.building = False
        g.put()
    else:
        image_content = result.content

        files = {"file": ("%s.png" % graph_id, image_content)}
        result = requests.post(blobstore_url, files=files)
        if result.status_code != 200:
            raise Exception(
                "Could not save %s.png to blob storage, [%s] %s" % (graph_id, result.status_code, result.text)
            )
Example #18
0
    def get(self):
        user = users.get_current_user()
        if user:
            if user.user_id() != "113627741897119896619":
                self.redirect(users.create_login_url(self.request.uri))
            upload_url = blobstore.create_upload_url("/upload")
            self.response.out.write("<html><body>")
            self.response.out.write("<br>")
            self.response.out.write("<a href=https://workoutchirico.appspot.com/stat/test/> stat/test </a><br><br>")
            self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
            self.response.out.write(
                """Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>"""
            )

            h = {}
            for b in blobstore.BlobInfo.all():
                h[b.filename] = b.key()

            for filename in sorted(h.keys(), reverse=True):
                self.response.out.write('<li><a href="/serve/%s' % str(h[filename]) + '">' + str(filename) + "</a>")
                self.response.out.write(' <a href="/stat/%s' % str(h[filename]) + '">(Stats and Load)</a>')
                self.response.out.write(' <a href="/stat/test/%s' % str(h[filename]) + '">(Detail)</a>')
                self.response.out.write(
                    '&nbsp;&nbsp; <a href="/stat/summary/%s' % str(h[filename]) + '"> (Summary)</a>'
                )

        else:
            self.redirect(users.create_login_url(self.request.uri))
Example #19
0
 def get(self, projectid, imageid):
     user = self.get_login_user()
     if not user:
         self.redirect("/login?goback=/%s/images/%s/edit" % (projectid, imageid))
         return
     project = self.get_project(projectid)
     if not project:
         self.error(404)
         self.render("404.html", info="Project with key <em>%s</em> not found" % projectid)
         return
     image = self.get_image(project, imageid)
     if not image:
         self.error(404)
         self.render("404.html", info="Image with key <em>%s</em> not found" % imageid)
         return
     upload_url = blobstore.create_upload_url("/%s/images/%s/edit_image" % (projectid, imageid))
     blob_info = blobstore.BlobInfo.get(image.image_key)
     kw = {
         "project": project,
         "open_p": project.default_open_p,
         "upload_url": upload_url,
         "image": image,
         "blob_info": blob_info,
         "size": blob_info.size / 1024.0,
         "i_title": self.request.get("i_title") or image.title,
         "i_description": self.request.get("i_description") or image.description,
         "image_class": self.request.get("image_class"),
         "title_class": self.request.get("title_class"),
         "error_message": self.request.get("error_message"),
         "action": "Edit",
         "button_text": "Save changes",
     }
     self.render("image_upload.html", **kw)
Example #20
0
    def get(self, key_name):
        # First we need to check if the key_name is in the non_created_profiles
        logging.info(key_name)

        user_profiles = self.user_proxy.profiles
        redirection = None
        template_values = None

        if self.user_proxy:
            is_non_created = False

            for i in xrange(0, len(user_profiles)):
                if key_name == user_profiles[i]["key_name"] and user_profiles[i]["created"] is None:
                    profile = user_profiles[i]
                    template_values = {"unique": True, "profile": profile}
                    break
                elif key_name == user_profiles[i]["key_name"] and user_profiles[i]["created"] is not None:
                    shortname = self.user_proxy.profiles[i]["shortname"]
                    redirection = "/" + shortname
                    self.user_proxy.set_profile(key_name)
                    break

        if template_values:

            template_values["blobstore_url"] = blobstore.create_upload_url("/picture/upload")
            self.render("profile.html", template_values)

        elif redirection:
            self.redirect(redirection)
        else:
            self.error(404)
Example #21
0
    def get(self):
        """GET

    With no parameters, return the URL to use to submit uploads via
    multipart/form-data.

    With mode and key parameters, return status of the previous uploadpkg
    operation to the calling client.

    This method actually acts as a helper to the starting and finishing
    of the uploadpkg post() method.

    Parameters:
      mode: optionally, 'success' or 'error'
      key: optionally, blobstore key that was uploaded
    """
        if not handlers.IsHttps(self):
            # TODO(user): Does blobstore support https yet? If so, we can
            # enforce security in app.yaml and not do this check here.
            return

        gaeserver.DoMunkiAuth()

        mode = self.request.get("mode")
        msg = self.request.get("msg", None)
        if mode == "success":
            self.response.out.write(self.request.get("key"))
        elif mode == "error":
            self.response.set_status(400)
            self.response.out.write(msg)
        else:
            upload_url = blobstore.create_upload_url("/uploadpkg")
            self.response.out.write(upload_url)
Example #22
0
    def get(self, ruser):
        ruser = urllib.unquote(urllib.unquote(ruser))
        if self.request.GET:
            show = self.request.get("show")
            if show == "":
                show = 0
            else:
                show = Paging().Test_page(show)
        else:
            show = 0
        show = int(show)

        fotolist = GqlQuery("SELECT * FROM FotosDB2 WHERE user = '%s' ORDER BY date DESC" % ruser)
        paging = Paging().page(fotolist, show, num=12)
        fotolist = fotolist.fetch(12, show)

        if ruser == users.get_current_user().nickname():
            dell = True
        else:
            dell = False

        template_values = {
            "upload_url": blobstore.create_upload_url("/uploadfoto"),
            "fotolist": fotolist,
            "paging": paging,
            "dell": dell,
        }
        self.generate("fotos.index.html", template_values, razdel="", logo="logo", title="Фотоальбом %s" % ruser)
    def get(self):
        # Sino existe una sesion redireccionamos al controler main.py
        if not self.session.get("usuario"):
            self.redirect("/")
            # si existe la sesion, imprimos que sesion es
        else:
            usr = db.Query(models.Usuario).filter("str_email", self.session["usuario"])
            tipo = usr.get().str_tipo
            print(tipo)

            if tipo == "foraneo":
                nombreS = usr.get().str_email
                nombre = usr.get().str_nombre
                print(nombreS)
                print(nombre.encode("utf-8"))

                template = jinja2.Environment(loader=jinja2.FileSystemLoader(os.getcwd()))
                template = template.get_template("configuracion.html")

                upload_url = blobstore.create_upload_url("/cargarArchivo?file=fotoperfil")
                context = {"nombre": "Bienvenido, " + nombre, "correo": usr, "upload_url": upload_url}
                # self.response.out.write('Bienvenido, ' + nombre)
                self.response.out.write(template.render(context))
                # self.response.out.write('Usuario = ' + self.session['usuario'])
            else:
                self.redirect("/inicioArrendador")
Example #24
0
    def get(self):
        self.response.out.write("<html><body>")
        query_str = "SELECT * FROM FeedItem ORDER BY date DESC LIMIT 10"
        feed_items = db.GqlQuery(query_str)

        for feed_item in feed_items:
            self.response.out.write("<div>")

            if feed_item.image:
                self.response.out.write("<img src='/serve/%s'></img>" % feed_item.image.data.key())
            self.response.out.write("</div>")
            if feed_item.text:
                self.response.out.write("<div>")
                self.response.out.write(feed_item.text)
                self.response.out.write("</div>")

        upload_url = blobstore.create_upload_url("/api/upload_image")
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write(
            """
                <div><label>Text:</label></div>
                <div><textarea name="text" rows="3" cols="60"></textarea></div>
                <div><label>Image:</label></div>
                <div><input type="file" name="file"/></div>
                <div><input type="submit" value="Add!"></div>
              </form>
            </body>
          </html>"""
        )
Example #25
0
    def get(self):
        colleges = model.get_colleges()
        departments = model.get_departments()
        courses = model.get_courses()

        dep_name = departments[0]
        dep_id = departments[1]
        dep_college = departments[2]

        cour_name = courses[0]
        cour_id = courses[1]
        cour_department = courses[2]

        upload_url = blobstore.create_upload_url("/upload/submit")

        template_values = {
            "colleges": colleges,
            "departments_name": simplejson.dumps(dep_name),
            "departments_id": simplejson.dumps(dep_id),
            "departments_college": simplejson.dumps(dep_college),
            "courses_name": simplejson.dumps(cour_name),
            "courses_id": simplejson.dumps(cour_id),
            "courses_department": simplejson.dumps(cour_department),
            "action": upload_url,
        }
        path = os.path.join(os.path.dirname(__file__), "html/upload.html")
        self.response.out.write(template.render(path, template_values))
Example #26
0
    def get(self):
        # user = Authenticate(self.request)
        # if not user:
        #     return self.redirect("/login")

        upload_url = blobstore.create_upload_url("/ndbrecoverupload")
        return self.render("ndbrecover.html", upload_url=upload_url)
Example #27
0
    def get(self, mode=""):
        templateName = "templates/index.html"
        data = {}

        session = get_current_session()
        callback_url = "%s/work" % self.request.host_url
        client = oauth2.SpringpadClient(APPLICATION_KEY, APPLICATION_SECRET, callback_url)
        # session.clear()
        if session.has_key("token"):
            token = session.get("token")
            secret = session.get("secret")
            results = client._lookup_user_info(token, secret)
            data = results
            session["userInfo"] = results
            templateName = "templates/worker.html"
            upload_url = blobstore.create_upload_url("/upload")
            data["upload_url"] = upload_url
            if self.request.get("workbook"):
                data["total"] = (
                    '<span class="note alert">You uploaded %s bytes. Your items will be copied into a new springpad notebook named "%s". Feel free to upload another while you wait.</span>'
                    % (self.request.get("size"), self.request.get("workbook"))
                )

        path = os.path.join(os.path.dirname(__file__), templateName)
        self.response.out.write(template.render(path, data))
Example #28
0
def process_leasingfinder():
    leasingfinder_data_final = []
    default_month = datetime.today().strftime("%Y%m")
    months_to_show = [default_month]
    month_list_entity = ds.get_saved_months("month_list_leasing")
    if month_list_entity != None:
        months_to_show = month_list_entity.month_list_leasing
        default_month = months_to_show[0]

    if request.method == "POST":
        default_month = request.form.get("default_month", "")

    print "Get data for month %s" % default_month

    leasingfinder_data = ds.get_general_entities_bymonth(default_month)
    if leasingfinder_data != None:
        for i in leasingfinder_data:
            leasingfinder_data_final.append(json.dumps(json.loads(i.json_str)))

    upload_url = blobstore.create_upload_url("/leasingfinder/results")
    return render_template(
        "leasing_finder_show.html",
        uploadurl=upload_url,
        leasingfinder_data=leasingfinder_data_final,
        months_to_show=months_to_show,
        default_month=default_month,
    )
Example #29
0
 def get(self, projectid):
     user = self.get_login_user()
     if not user:
         self.redirect("/login?goback=/%s/images/new" % projectid)
         return
     project = self.get_project(projectid)
     if not project:
         self.error(404)
         self.render("404.html", info="Project with key <em>%s</em> not found" % projectid)
         return
     if not project.user_is_author(user):
         self.redirect("/%s/images" % projectid)
         return
     upload_url = blobstore.create_upload_url("/%s/images/new_image" % projectid)
     kw = {
         "project": project,
         "open_p": project.default_open_p,
         "upload_url": upload_url,
         "i_title": self.request.get("i_title"),
         "i_description": self.request.get("i_description"),
         "image_class": self.request.get("image_class"),
         "title_class": self.request.get("title_class"),
         "error_message": self.request.get("error_message"),
         "action": "New",
         "button_text": "Upload image",
     }
     self.render("image_upload.html", **kw)
Example #30
0
    def get(self):
        # get session link for upload
        # make it in json
        #

        upload_url = blobstore.create_upload_url("/upload_photo")
        self.response.out.write(upload_url)