def _AddChromiumTryTask(self, username):
  benchmark_name = self.request.get('benchmark_name')
  benchmark_arguments = self.request.get('benchmark_arguments')
  browser_args_1 = self.request.get('browser_args_1')
  browser_args_2 = self.request.get('browser_args_2')
  target_platform = self.request.get('target_platform')
  pageset_type = self.request.get('pageset_type')
  num_repeated_runs = int(self.request.get('num_repeated_runs'))
  variance_threshold = float(self.request.get('variance_threshold'))
  discard_outliers = float(self.request.get('discard_outliers'))
  description = self.request.get('description')
  if not description:
    description = 'None'
  skia_patch = db.Blob(str(self.request.get('skia_patch')))
  chromium_patch = db.Blob(str(self.request.get('chromium_patch')))
  blink_patch = db.Blob(str(self.request.get('blink_patch')))
  requested_time = datetime.datetime.now()

  ChromiumTryTasks(
      username=username,
      benchmark_name=benchmark_name,
      benchmark_arguments=benchmark_arguments,
      browser_args_1=browser_args_1,
      browser_args_2=browser_args_2,
      target_platform=target_platform,
      pageset_type=pageset_type,
      skia_patch=skia_patch,
      chromium_patch=chromium_patch,
      blink_patch=blink_patch,
      num_repeated_runs=num_repeated_runs,
      variance_threshold=variance_threshold,
      discard_outliers=discard_outliers,
      requested_time=requested_time,
      description=description).put()
Esempio n. 2
0
    def post(self):
        player = Player.get(self.request.get("player_key"))
        if player.pic:
            player.pic.delete()
            player.pic = None
            player.put()

        player_pic = self.request.get("pic")
        box = db.Blob(images.resize(player_pic, 380, 532))
        leader = db.Blob(images.resize(player_pic, 80, 112))
        thumb = db.Blob(images.resize(player_pic, 20, 28))

        pic = PlayerPicture(key_name=player.key().name(),
                            box=box,
                            leader=leader,
                            thumb=thumb)
        pic.put()

        player.pic = pic
        player.put()

        views.PlayerBox.clear(player.key())
        views.PlayerLeaders.clear()

        # I need to give a response or I get an error. Nobody on the internet seems
        # to know why.  See https://github.com/malsup/form/issues#issue/22.
        self.response.out.write("OK")
Esempio n. 3
0
    def post(self):
        thefile = self.request.params['prductImage']
        newImageFile = DbFile(name=thefile.filename,
                              data=db.Blob(thefile.value),
                              type=thefile.type)
        newImageFile.put()
        theDetailFile = self.request.params['prductDetailImage']
        newImageDetailFile = DbFile(name=theDetailFile.filename,
                                    data=db.Blob(theDetailFile.value),
                                    type=theDetailFile.type)
        newImageDetailFile.put()
        newName = self.request.params['productName']
        newDescription = self.request.params['productDescription']
        newPrice = float(self.request.params['productPrice'])
        newImagePath = '/Files/' + newImageFile.name
        newImageDetailPath = '/Files/' + newImageDetailFile.name

        product = Product(name=newName,
                          description=newDescription,
                          price=newPrice,
                          imagePath=newImagePath,
                          imageFile=newImageFile,
                          imageDetailPath=newImageDetailPath,
                          imageDetailFile=newImageDetailFile)
        product.put()
        self.postRedirect()
Esempio n. 4
0
def update_photo(it, request_handler):
  try:
    raw_file = request_handler.request.get('new-photo')
    rot = request_handler.request.get("rotation")
    if len(raw_file) > 0:
      # a new image saved
      img = DBImage()  # - no: create it
      if rot and (rot <> u'0'):  # is a rotation requested?
        angle = int(rot) * 90
        raw_file = images.rotate(raw_file, angle)
      # exif = raw_file.get_original_metadata()
      img.picture = db.Blob(raw_file)
      img.make_thumb()
      img.owner = request_handler.user_id
      img.put()
      logging.debug('update_photo Ins:',img.key.id())
      if it.photo:  # the item has an image already?
        logging.debug( 'update_photo Del:',it.photo.id())
        it.photo.delete()
    else:
      # no new image - rotate an existing image?
      img = None  # no image supplied
      if rot and (rot != u'0'):  # is a rotation requested?
        old_img = it.photo
        if old_img and old_img.picture:
          # if so, does the item have a pic already?
          angle = int(rot) * 90  # rotate & save in place
          rotated_pic = images.rotate(old_img.picture, angle)
          old_img.picture = db.Blob(rotated_pic)
          old_img.thumb = None
          old_img.put()
  except Exception:
    logging.exception("newOrUpdateItem Image Resize: ", exc_info=True)
    img = None
  return img
Esempio n. 5
0
def editImage(form):
    postID = form.getfirst("postID", "none")
    if postID == "none":
        thePost = algaeModels.algaeImage()
    else:
        thePost = algaeModels.algaeImage.get(postID)
    theTitle = form.getfirst("postTitle", "Untitled").decode('utf-8', 'ignore')
    thePost.postTitle = theTitle
    url = re.sub(r' ', "_", theTitle)
    url = re.sub(r'\W', "", url)
    url = re.sub(r'_+', "-", url)
    if url != thePost.cleanURL:
        url = algaePython.noDupeURL(url, 'algaeImage')
    thePost.cleanURL = url
    theImage = form.getfirst("img", "")
    thePost.imgData = db.Blob(theImage)
    smImage = images.resize(theImage, algaeUserConfig.smallImageSize,
                            algaeUserConfig.smallImageSize)
    thePost.smData = db.Blob(smImage)
    mdImage = images.resize(theImage, algaeUserConfig.mediumImageSize,
                            algaeUserConfig.mediumImageSize)
    thePost.mdData = db.Blob(mdImage)
    lgImage = images.resize(theImage, algaeUserConfig.largeImageSize,
                            algaeUserConfig.largeImageSize)
    thePost.lgData = db.Blob(lgImage)
    thePost.mimeType = form['img'].type
    thePost.fileName = form['img'].filename
    if form.getfirst("isPublished", "False") == "on":
        thePost.isPublished = True
    else:
        thePost.isPublished = False
    thePost.put()
    print "Location: admin?saved=yes&edit=image&key=" + str(thePost.key())
    print 'Content-Type: text/html\n'
Esempio n. 6
0
    def doTheUpload(self, randomID, file_contents):
        # in theory we should check whether the user either owns the sketch or is an
        # admin, but it's not really worth it so far.

        thumbnailBinary = base64.standard_b64decode(
            urllib.unquote(file_contents).replace(chr(45), chr(43)))

        q0 = db.GqlQuery("SELECT * FROM MySketchesSketch WHERE randomID = :1",
                         randomID).fetch(1)

        updateAuthorSketchesAndGallerySketch = True

        if (q0):
            q0[0].thumbnail = db.Blob(thumbnailBinary)
            if q0[0].published: updateAuthorSketchesAndGallerySketch = True
            q0[0].put()

        if updateAuthorSketchesAndGallerySketch:
            q1 = db.GqlQuery(
                "SELECT * FROM AuthorSketchesSketch WHERE randomID = :1",
                randomID).fetch(1)
            q2 = db.GqlQuery("SELECT * FROM GallerySketch WHERE randomID = :1",
                             randomID).fetch(1)
            if (q1):
                q1[0].thumbnail = db.Blob(thumbnailBinary)
                q1[0].put()
            if (q2):
                q2[0].thumbnail = db.Blob(thumbnailBinary)
                q2[0].put()
Esempio n. 7
0
    def post(self, randomID):

        # Only an admin can upload full pictures
        # Note that non-admins can still do lengthy posts to this address, which should ideally be avoided
        self.session = True
        user = UserInfo()
        user.whoIs(self)

        if ((user.is_current_user_admin)):
            logging.info('you are an admin: OK')
        else:
            logging.info('you are an not an admin: not OK')
            return

        self.response.headers['Content-Type'] = "text/html"
        logging.info('you are doing a get to the full picture uploader')
        self.response.out.write("from page:")
        logging.info("from page: <br>")

        logging.info('randomID is: ' + randomID)

        # In order to check who the user is, the flash applet needs to include the same
        # session cookie that the browser uses to keep the identity of the user
        # if users.get_current_user().email().lower() != "*****@*****.**":
        # 	raise web.HTTPError(501)
        # 	return

        # for myModel in MyModel.all():
        #  myModel.delete()

        file_contents = self.request.get("fullPicture")
        # self.response.out.write(file_contents)
        # in the local environment
        logging.info('about to create the full picture object')
        # self.response.out.write('<br> unescaped: <br>')
        # self.response.out.write(urllib.unquote(file_contents).replace(chr(45),chr(43)))
        # self.response.out.write('<br> over <br>')
        # logging.info('<br> unescaped: <br>')
        # logging.info(urllib.unquote(file_contents).replace(chr(45),chr(43)))
        # logging.info('<br> over <br>')

        fullPictureBinary = base64.standard_b64decode(
            urllib.unquote(file_contents).replace(chr(45), chr(43)))

        q0 = db.GqlQuery("SELECT * FROM FullPicture WHERE randomID = :1",
                         randomID).fetch(1)

        if (q0):
            logging.info('updated an existing full picture record')
            q0[0].fullPicture = db.Blob(fullPictureBinary)
            q0[0].put()
        else:
            logging.info('created a new full picture record')
            fullPictureRecord = FullPicture()
            fullPictureRecord.randomID = randomID
            fullPictureRecord.fullPicture = db.Blob(fullPictureBinary)
            fullPictureRecord.put()

        self.response.out.write('<br> ...done <br>')
        logging.info('created the full picture object and put it in datastore')
Esempio n. 8
0
 def post(self,gallery_slug):
     image = images.Image(self.request.get("img"))
     thumb = images.Image(self.request.get("img"))
     aspect_ratio = float(image.width) / float(image.height)
     # crop the image to make it square for the thumb
     if aspect_ratio > 1.0:
         left_x = float(image.width-image.height)/float(2*image.width)
         right_x = float(image.height+image.width)/float(2*image.width)
         thumb.crop(left_x,0.0,right_x,1.0)
     elif aspect_ratio < 1.0:
         top_y = float(image.height-image.width)/float(2*image.height)
         bottom_y = float(image.height+image.width)/float(2*image.height)
         thumb.crop(0.0,top_y,1.0,bottom_y)
     thumb.resize(45,45)
     image.resize(800,600)
     # find gallery that we are adding to
     gallery = db.Query(Gallery).filter('slug =',gallery_slug).get()
     # is the photo to be displayed on the front page as well?
     fp = self.request.get("frontpage",False)
     if fp:
         fp = True
     # create and save the new photo
     new_photo = Photo(
         title = self.request.get("title"),
         image_data = db.Blob(image.execute_transforms()),
         thumb_data = db.Blob(thumb.execute_transforms()),
         extension = 'png',
         gallery = gallery,
         frontpage = fp,
     )
     new_photo.put()
     #self.redirect('/gallery/%s/view'%gallery_slug) 
     return self._compose(gallery_slug,['New photo "%s" added to gallery "%s".'%(new_photo.title,gallery.title)])
Esempio n. 9
0
 def get(self):
     json = []
     for m in Ad.all():
         if m.image:
             json.append({
                 'title': m.title,
             })
             image_thumb = images.resize(m.image, 100, 100)
             image_medium = images.resize(m.image, 480, 480)
             image_small = images.resize(m.image, 200, 200)
             m.image_thumb = db.Blob(image_thumb)
             m.image_small = db.Blob(image_small)
             m.put()
     for m in Billboard.all():
         if m.image:
             json.append({
                 'title': m.title,
             })
             image_thumb = images.resize(m.image, 100, 100)
             image_medium = images.resize(m.image, 480, 480)
             image_small = images.resize(m.image, 200, 200)
             m.image_thumb = db.Blob(image_thumb)
             m.image_small = db.Blob(image_small)
             m.put()
     json = simplejson.dumps(json)
     self.response.headers.add_header('Content-Type', 'application/json')
     self.response.out.write(json)
Esempio n. 10
0
    def post(self):
        team = Team.get(self.request.get("team_key"))
        if team.custom_logo:
            team.custom_logo.delete()
            team.custom_logo = None
            team.put()

        team_logo = self.request.get("logo")
        box = db.Blob(images.resize(team_logo, 128, 128))
        thumb = db.Blob(images.resize(team_logo, 20, 20))

        logo = TeamLogo(key_name=team.key().name(), box=box, thumb=thumb)
        logo.put()

        team.custom_logo = logo
        team.put()

        views.RecentMatches.clear()
        views.TeamBox.clear(team.key())
        views.TeamLeaders.clear()

        for player in team.player_set:
            views.PlayerBox.clear(player.key())

        # I need to give a response or I get an error. Nobody on the internet seems
        # to know why.  See https://github.com/malsup/form/issues#issue/22.
        self.response.out.write("OK")
Esempio n. 11
0
 def post(self):
     fiducial = Fiducial()
     fiducial.name = self.request.get('marker')
     fiducial.pic = db.Blob(self.request.get('pic'))
     fiducial.marker = db.Blob(self.request.get('fiducial'))
     fiducial.used = False
     fiducial.put()
     self.redirect('/fiducial')
Esempio n. 12
0
    def _setScore():
        playSession.delete()

        verifiedScore = None
        verifiedScoreWrapper = VerifiedScoreWrapper.get_by_key_name(
            "verifiedScore", parent=playerKey)
        if verifiedScoreWrapper is not None:
            verifiedScore = verifiedScoreWrapper.verified

        if verifiedScore is None or scoreValue > verifiedScore.value or (
                scoreValue == verifiedScore.value
                and scoreTime < verifiedScore.time):
            pendingScore = PendingScore.get_by_key_name("pendingScore",
                                                        parent=playerKey)
            if pendingScore is not None:
                nonVerifiedScore = pendingScore.nonVerified
            else:
                nonVerifiedScore = None

            if nonVerifiedScore is None or scoreValue > nonVerifiedScore.value or (
                    scoreValue == nonVerifiedScore.value
                    and scoreTime < nonVerifiedScore.time):

                try:
                    proofBlob = db.Blob(proof)
                except Exception:
                    proofText = str(proof)
                    proofBlob = db.Blob(proofText)

                nonVerifiedScore = NonVerifiedScore(value=scoreValue,
                                                    time=scoreTime,
                                                    proof=proofBlob,
                                                    seed=seed,
                                                    version=version,
                                                    parent=playerKey)
                nonVerifiedScore.put()
                if pendingScore is None:
                    pendingScore = PendingScore(key_name='pendingScore',
                                                parent=playerKey,
                                                nonVerified=nonVerifiedScore)
                else:
                    conflicts = ReviewConflict.gql(
                        "WHERE ANCESTOR IS :score",
                        score=pendingScore.nonVerified.key()).fetch(
                            100)  # shoud not be more than 2
                    for conflict in conflicts:
                        conflict.delete()
                    pendingScore.nonVerified.delete()
                    pendingScore.nonVerified = nonVerifiedScore
                pendingScore.put()

                return {'result': {'message': 'success'}}
            else:
                pass  # TODO : are you trying to cheat?
        else:
            pass  # TODO : are you trying to cheat?

        return getErrorResponse(SCORE_TOO_SMALL)
Esempio n. 13
0
 def post(self, gallery_slug):
     action = self.request.get("action")
     if action == 'delete':
         photo_id = self.request.get("id")
         p = Photo.get_by_id(int(photo_id))
         p.delete()
         return self._compose(gallery_slug, ['Delete Successful'])
     elif action == 'frontpage':
         photo_id = self.request.get("id")
         new_setting = self.request.get("frontpage")
         p = Photo.get_by_id(int(photo_id))
         p.frontpage = (new_setting == 'include')
         p.put()
         return self._compose(gallery_slug, ['Edit Successful'])
     elif action == 'add':
         try:
             image = images.Image(self.request.get("img"))
             thumb = images.Image(self.request.get("img"))
             aspect_ratio = float(image.width) / float(image.height)
             # crop the image to make it square for the thumb
             if aspect_ratio > 1.0:
                 left_x = float(image.width - image.height) / float(
                     2 * image.width)
                 right_x = float(image.height + image.width) / float(
                     2 * image.width)
                 thumb.crop(left_x, 0.0, right_x, 1.0)
             elif aspect_ratio < 1.0:
                 top_y = float(image.height - image.width) / float(
                     2 * image.height)
                 bottom_y = float(image.height + image.width) / float(
                     2 * image.height)
                 thumb.crop(0.0, top_y, 1.0, bottom_y)
             thumb.resize(45, 45)
             image.resize(800, 600)
             #find gallery that we are adding to
             gallery = db.Query(Gallery).filter('slug =',
                                                gallery_slug).get()
             # is the photo to be displayed on the front page as well?
             fp = self.request.get("frontpage", False)
             if fp:
                 fp = True
             # create and save the new photo
             new_photo = Photo(
                 title=self.request.get("title"),
                 image_data=db.Blob(image.execute_transforms()),
                 thumb_data=db.Blob(thumb.execute_transforms()),
                 extension='png',
                 gallery=gallery,
                 frontpage=fp)
             new_photo.put()
             #return self.response.out.write('<img src="%s_thumb.%s"></img>' % (new_photo.key().id(),new_photo.extension))
             return self._compose(gallery_slug, ['Upload Successful'])
         except Exception, e:
             return self._compose(gallery_slug, ['Upload Failed', str(e)])
Esempio n. 14
0
    def post(self):
        """ Write bullshit to DB """
        self.checkSession(self.request.headers.get('Cookie'))
        if not self.checkAccess('eventadd'):
            self.insertMenu()
            self.insertContent('У вас нет прав на добавление события')
        else:
            event = DBEvent()
            event.name = self.request.get('name')
            event.minidescr = self.request.get('minidescr')[:1024]
            event.descr = self.request.get('descr')

            event.date = db.datetime.date.today()
            day = int(self.request.get('day'))
            month = int(self.request.get('month'))
            year = int(self.request.get('year'))
            if day and month and year:
                event.date = db.datetime.date(year, month, day)

            event.time = self.request.get('time')
            event.access = int(self.request.get('access'))
            event.owner = self.request.get('owner')
            event.place = self.request.get('place')
            event.userid = self.Session['userid']
            event.author = self.Session['user_key']
            event.catid = int(self.request.get('cat'))
            if self.request.get('closed') == 'True':
                event.closed = True
            else:
                event.closed = False
            event.put()
            self.insertMenu()
            self.insertContent('Событие добавлено')
            dbevents = db.GqlQuery("SELECT * FROM DBEvent WHERE name = :name",
                                   name=event.name)
            eventid = dbevents.fetch(1)[0].key().id()
            data = self.request.get("pic")
            if data:
                try:
                    dbQuery = DBEventPicture.gql("WHERE eventid = :dbeventid",
                                                 dbeventid=int(eventid))
                    pics = dbQuery.fetch(1)
                    pic = pics[0]
                    avatar = images.resize(data, 400, 400)
                    pic.image = db.Blob(avatar)
                    pic.put()
                except:
                    pict = DBEventPicture()
                    avatar = images.resize(data, 400, 400)
                    pict.image = db.Blob(avatar)
                    pict.eventid = int(eventid)
                    pict.put()
        self.drawPage()
Esempio n. 15
0
 def add(form):
     image_thumb = images.resize(form['image'], 100, 100)
     image_medium = images.resize(form['image'], 480, 480)
     image_small = images.resize(form['image'], 200, 200)
     billboard = Billboard(title=form['title'])
     billboard.phone = db.PhoneNumber(form['phone'])
     billboard.email = db.Email(form['email'])
     billboard.image = db.Blob(form.get('image'))
     billboard.image_thumb = db.Blob(image_thumb)
     billboard.image_medium = db.Blob(image_medium)
     billboard.image_small = db.Blob(image_small)
     billboard.put()
Esempio n. 16
0
class ProjectData(db.Model):
    nature = db.StringProperty(multiline=False, choices=['product', 'project'])
    name = db.StringProperty(multiline=False)
    description = db.TextProperty()
    short_description = db.StringProperty(multiline=True)
    screenshot = db.Blob()
    screenshot_mimetype = db.StringProperty(required=True, multiline=False)
    icon = db.Blob()
    icon_mimetype = db.StringProperty(required=True, multiline=False)
    url = db.StringProperty(multiline=False)
    modified_by = db.UserProperty(auto_current_user=True)
    modified_on = db.DateTimeProperty(auto_now=True)
Esempio n. 17
0
    def post(self):
        pluginid = self.request.get('pluginid', '')
        needBigData=False
        id = self.request.get('id', '')
        versioncode = self.request.get('versioncode', '')
        versionnum = self.request.get('versionnum', '')
        updateDesc = self.request.get('updateDesc', '')
        if id:
            pluginVersion = PluginVersion.get_by_id(int(id))
        else:
            pluginVersion = PluginVersion()
            pluginVersion.plugin = int(pluginid)
        pluginVersion.versioncode = versioncode
        pluginVersion.versionnum = int(versionnum)
        pluginVersion.updateDesc = updateDesc

        appdata = self.request.POST.get('data')
        if appdata != '' and appdata != u'' and appdata != None:
            pluginVersion.data = db.Blob(appdata.file.read())
            pluginVersion.size = appdata.bufsize
        else:
            needBigData=True
        for i in range(1, 11):
            imgfilename = 'image' + str(i)
            imgfield = self.request.POST.get(imgfilename)
            if imgfield != '' and imgfield != u'' and imgfield != None:
                if imgfield.type.lower() not in ['image/pjpeg', 'image/x-png', 'image/jpeg', 'image/png', 'image/gif',
                                                 'image/jpg']:
                    continue
                imgfile = Images()
                imgfile.filename = imgfield.filename
                imgfile.filetype = imgfield.type
                imgfile.data = db.Blob(imgfield.file.read())
                imgfile.size = imgfield.bufsize
                imgfile.put()
                pluginVersion.imageids.append(imgfile.key().id())
        pluginVersion.put()
        plugin = {}
        pluginVersionList = []
        if pluginid:
            plugin = Plugin.get_by_id(int(pluginid))
            pluginVersionList = PluginVersion.all().filter('plugin =', int(pluginid)).order('-versionnum')

        data={'plugin': plugin, 'pluginVersion': pluginVersion, 'pluginVersionList': pluginVersionList, 'id': id,
                     'pluginid': pluginid, 'result': 'succeed', 'msg': u'操作成功。','needBigData':needBigData}
        if needBigData:
            upload_url = blobstore.create_upload_url('/upload?pluginversionid=%s'%(pluginVersion.key().id()))
            data['upload_url']=upload_url
            data['msg']= u'请上传APK文件。'
            self.render('template/plugin/pluginUpload2.html',data)
        else:
            self.render('template/plugin/pluginUpload.html',data )
Esempio n. 18
0
    def post(self):
        self.checkSession(self.request.headers.get('Cookie'))
        self.insertMenu()

        id = int(self.request.uri.split('/')[-1])
        photo = DBPhoto.get_by_id(id)
        albom_ppc = DBAlbum.get_by_id(int(photo.albumid))

        if (self.Session['access'] >= 8
                or self.Session['userid'] == int(albom_ppc.userid)):
            if self.request.get('pic'):
                image = images.Image(self.request.get('pic'))
                image_resized = images.Image(
                    images.resize(image._image_data,
                                  width=130,
                                  output_encoding=images.JPEG)
                ) if image.height >= image.width else images.Image(
                    images.resize(image._image_data,
                                  height=130,
                                  output_encoding=images.JPEG))
                image_cropped = images.crop(
                    image_resized._image_data, 0.0, 0.0,
                    float(130) / float(image_resized.width), 1.0, images.JPEG
                ) if image_resized.height == 130 else images.crop(
                    image_resized._image_data, 0.0, 0.0, 1.0,
                    float(130) / float(image_resized.height), images.JPEG)
                photo.image_small = db.Blob(image_cropped)
                if (image.width < 400 and image.height < 400
                    ) or image.width > 1024 or image.height > 768:
                    self.insertContent(
                        "Фотография не должна быть больше 1024x768 пикселей, но хотя бы одна сторона фотографии должна быть больше 400 пикселей"
                    )
                    self.drawPage()
                    return
                photo.image_big = db.Blob(image._image_data)
            photo.put()

            try:
                tags = DBPhotoTags.gql("where imageid = :imageid", imageid=id)
                if tags.count() == 0: 1 / 0
                for tag in tags:
                    tag.tags = self.request.get('tags')
                    tag.put()
            except:
                tags = DBPhotoTags()
                tags.tags = self.request.get('tags')
                tags.imageid = id
                tags.put()

            self.insertContent("Изменено успешно!")
        self.drawPage()
        self.redirect("/album/%s" % str(albom_ppc.key().id()))
Esempio n. 19
0
def new_purchase():
    form = PicUploadForm()
    if request.method == 'POST' and form.validate():
        image = request.files['PicImage'].read()
        Purchase(pic_title=request.form['PicTitle'],
                 pic_image_thumb=db.Blob(images.resize(image, 200, 100)),
                 pic_image_large=db.Blob(images.resize(image, 800, 800)),
                 pic_poster=request.form['PicPoster'],
                 pic_price=request.form['PicPrice'],
                 pic_where=request.form['PicWhere']).put()
        return redirect('/')
    else:
        return render_template('new_purchase.html', form=form)
Esempio n. 20
0
    def setter(self, req):
        self.part = req['part']
        if "" != req['photo']:
            self.photo = db.Blob(req['photo'])
        if "" != req['thumbnail']:
            self.thumbnail = db.Blob(req['thumbnail'])

#self.image_get(photo,480,320)
#			if (True == ('thumbnail' in req)):
#				thumbnail = req['thumbnail']
#				self.thumbnail = self.image_get(thumbnail)
#			else:
#				self.thumbnail = self.image_get(photo,480,320)
        super(Content, self).setter(req)
Esempio n. 21
0
def create_postdata(data):
    u"""
        投稿データを作成
    """
    postdata = PostData()
    postdata.name = data['author_name']
    postdata.comment = data['comment']
    postdata.delete_password = data['delete_password']
    postdata.exhibit_flag = data['exhibit_flag']
    postdata.main_image = db.Blob(data['main_image']) if data['main_image'] is not None else None
    postdata.sub_image_1 = db.Blob(data['sub_image_1']) if data['sub_image_1'] is not None else None
    postdata.sub_image_2 = db.Blob(data['sub_image_2']) if data['sub_image_2'] is not None else None
    postdata.put()
    return postdata
Esempio n. 22
0
    def post(self):
        self.checkSession(self.request.headers.get('Cookie'))
        self.insertMenu()
        temp_uri = self.request.uri
        uri = temp_uri.split('/')
        event_id = int(uri[-1])
        event = DBEvent.get_by_id(event_id)
        data = self.request.get("pic")
        if self.checkAccess('eventedit'):
            if data:
                try:
                    dbQuery = DBEventPicture.gql("WHERE eventid = :dbeventid",
                                                 dbeventid=int(event_id))
                    pics = dbQuery.fetch(1)
                    pic = pics[0]
                    avatar = images.resize(data, 400, 400)
                    pic.image = db.Blob(avatar)
                    pic.put()
                except:
                    pict = DBEventPicture()
                    avatar = images.resize(data, 400, 400)
                    pict.image = db.Blob(avatar)
                    pict.eventid = int(event_id)
                    pict.put()

            if self.Session['access'] >= event.access or int(
                    self.Session['userid']) == int(event.userid):
                event.name = self.request.get('name')
                event.descr = self.request.get('descr')
                day = int(self.request.get('day'))
                month = int(self.request.get('month'))
                year = int(self.request.get('year'))
                event.date = db.datetime.date(year, month, day)
                event.time = self.request.get('time')
                event.place = self.request.get('place')
                event.access = int(self.request.get('access'))
                event.owner = self.request.get('owner')
                #                print self.request.get('closed')
                if self.request.get('closed') == 'True':
                    event.closed = True
                else:
                    event.closed = False
                event.put()
                self.insertContent('Данные успешно изменены')
            else:
                self.insertContent('У вас нет прав на изменение этого события')
        else:
            self.insertContent('У вас нет прав на изменение этого события')
        self.drawPage()
Esempio n. 23
0
	def set(cls, key, items, sortcmp=None):
		logging.warning("Sorting list - %s" % repr(sortcmp))
		if sortcmp:
			logging.warning("Sorting list - first: %s, last: %s" % (items[0], items[-1]))
			items.sort(cmp=sortcmp)
			logging.warning("Sorting list - first: %s, last: %s" % (items[0], items[-1]))
		data = pickle.dumps(items)
		data = zlib.compress(data)
		lst = Lst.get_by_key_name(key)
		if lst is None:
			lst = Lst(key_name=key, blob=db.Blob(data))
			lst.put()
		else:
			lst.blob = db.Blob(data)
			lst.put()
Esempio n. 24
0
 def post(self):
     company_id = self.request.get_range('company_id')
     company = None
     if company_id:
         company = iiko.CompanyNew.get_by_id(company_id)
     if company:
         company.icon1 = db.Blob(self.request.get('icon1', None))
         company.icon2 = db.Blob(self.request.get('icon2', None))
         company.icon3 = db.Blob(self.request.get('icon3', None))
         company.icon4 = db.Blob(self.request.get('icon4', None))
         company.company_icon = db.Blob(self.request.get('company_icon', None))
         company.put()
     else:
         self.error(404)
     return self.render_json({'id': company.key.id()})
Esempio n. 25
0
 def WriteEntry(self, image_name, value):
   """Stores the image in data store as a blob object."""
   small_image = SmallImage(key_name=image_name,
                            image_name=image_name,
                            image=db.Blob(value))
   small_image.put()
   self.EnqueueTask(small_image, value)
Esempio n. 26
0
  def post(self):
    """Handles the output posted from taskqueue puller.

    name is a queryparam that is the task_id of the task whose output is being
    posted by the puller. We first find the image_name for the task and store
    the processed image as image_name_processed. This helps when user searches
    for the image and we can show both uploaded as well as processed image.
    This handler is OAuth enabled, so that only the administrators of this app
    can call this handler using an OAuth token.
    """

    try:
      user = oauth.get_current_user()
      # Currently there is no way to figure out if a given OAuth user is an
      # admin. users.is_current_user_admin() only takes care of logged in users,
      # not users who are presenting tokens on OAuth. We should fix this!
      if user and user.nickname() == '*****@*****.**':
        task_name = self.request.get('name')
        name = self.GetImageNameFromTaskImageMap(task_name)
        if name:
          image_key = name + '_processed'
          image_contents = self.request.body
          small_image = SmallImage(key_name=image_key,
                                   image_name=image_key,
                                   image=db.Blob(image_contents))
          small_image.put()
        else:
          logging.error('No image associated with this task')
          self.error(404)
      else:
        logging.error('unauthorized user ' + user.nickname())
        self.error(403)
    except oauth.OAuthRequestError, e:
      logging.error('no oauth token detected')
      self.error(403)
  def post(self):
    # Check if this is a delete chromium try task request.
    delete_key = self.request.get('delete')
    if delete_key:
      SkiaTryTasks.delete_skia_try_task(delete_key)
      self.redirect('skia_try')
      return

    # It is an add skia try task request.
    patch = db.Blob(str(self.request.get('patch')))
    pagesets_type, chromium_rev, skia_rev = self.request.get(
        'pagesets_type_and_chromium_build').split('-')
    render_pictures_args = self.request.get('render_pictures_args')
    gpu_nopatch_run = self.request.get('gpu_nopatch_run') == 'True'
    gpu_withpatch_run = self.request.get('gpu_withpatch_run') == 'True'
    description = self.request.get('description')
    if not description:
      description = 'None'
    requested_time = datetime.datetime.now()

    SkiaTryTasks(
        username=self.user.email(),
        patch=patch,
        pagesets_type=pagesets_type,
        chromium_rev=chromium_rev,
        skia_rev=skia_rev,
        render_pictures_args=render_pictures_args,
        gpu_nopatch_run=gpu_nopatch_run,
        gpu_withpatch_run=gpu_withpatch_run,
        requested_time=requested_time,
        description=description).put()
    self.redirect('skia_try')
Esempio n. 28
0
    def put(self, user, folder, name):  ##### write an owned program
        m = re.search(r'/user/([^/]+)/folder/([^/]+)/program/([^/]+)',
                      self.request.path)
        user = m.group(1)
        folder = m.group(2)
        name = m.group(3)
        if not self.validate(user, folder, name): return
        if not self.authorize_user(user): return
        # TODO: Check content type of request
        import cgi
        params = cgi.parse_qs(self.request.body)
        req_program = params['program'][0]
        changes = json.loads(req_program)

        # This is a slight abuse of the PUT verb, since attributes not specified are left unchanged
        db_program = Program.get(
            db.Key.from_path("User", user, "Folder", folder, "Program", name))
        if not db_program:
            db_folder = Folder.get(
                db.Key.from_path("User", user, "Folder", folder))
            if not db_folder:
                return self.error(404)
            db_program = Program(parent=db_folder, key_name=name)

        if "description" in changes:
            db_program.description = changes["description"]
        if "screenshot" in changes:
            db_program.screenshot = db.Blob(str(changes["screenshot"]))
        if "source" in changes: db_program.source = changes["source"]
        db_program.put()
Esempio n. 29
0
def univ_create():

    if request.method == 'GET':
        return render_template('/univ/create.html')
    elif request.method == 'POST':
        univ_data = request.form
        post_data = request.files['photo']
        filestream = post_data.read()

        upload_data = Photo()
        upload_data.photo = gdb.Blob(filestream)
        upload_data.put()

        univ = I_Univ(univ_name=univ_data['univ_name'],
                      nation=univ_data['nation'],
                      state=univ_data['state'],
                      city=univ_data['city'],
                      avg_credit=univ_data['avg_credit'],
                      eng_score=univ_data['eng_score'],
                      student=univ_data['student'],
                      tuition=univ_data['tuition'],
                      cost=univ_data['cost'],
                      house=univ_data['house'],
                      term=univ_data['term'],
                      photo=str(upload_data.key()))

        # 데이터베이스에 데이터를 저장할 준비를 한다. (게시글)
        db.session.add(univ)
        # 데이터베이스에 저장하라는 명령을 한다.
        db.session.commit()

        flash(u'univ을 작성하였습니다.', 'success')
        return redirect(url_for('univ_list'))
Esempio n. 30
0
    def post(self):
        user = users.get_current_user().nickname()
        subject = self.request.get('subject')
        content = self.request.get('content')
        briefs = content[0:500]
        tags = self.request.get('tags')
        tagst = tags.split(',')
        tagsli = []
        for t in tagst:
            tt = t.encode('ascii', 'ignore')
            tagsli.append(tt)
        time = unicode(datetime.now().replace(microsecond=0))
        images = self.request.get('img').encode('ascii', 'ignore')
        imaget = db.Blob(images)

        blog_post = Post(author=user,
                         title=subject,
                         body=content,
                         tag=tags,
                         tagli=tagsli,
                         brief=briefs,
                         time=time,
                         image=imaget)
        blog_post.put()
        self.redirect('/')