Exemplo n.º 1
0
    def save(self, commit=True):
        if self.instance:
            wiki = self.instance
        else:
            wiki = Wiki()

        wiki.title = self.cleaned_data['title']
        wiki.slug = self.cleaned_data['slug']
        wiki.description = self.cleaned_data['description']
        wiki.text = self.cleaned_data['text']
        wiki.format = self.cleaned_data['format']
        wiki.published = self.cleaned_data['published']
        wiki.template = self.cleaned_data['template']
        wiki.show_in_rss = self.cleaned_data['show_in_rss']
        wiki.cacheable = self.cleaned_data['cacheable']
        wiki.show_in_rss = self.cleaned_data['show_in_rss']
        wiki.disable_comments = self.cleaned_data['disable_comments']

        if self.cleaned_data['temp_tags']:
            wiki.tags = map(lambda tag: db.Category(tag),
                            self.cleaned_data['temp_tags'].split(' '))
        else:
            wiki.tags = []

        if commit:
            wiki.save()

        return wiki
Exemplo n.º 2
0
def make_entry(rec):
    """docstring for make_entry"""
    body = rec.get('body')
    body_html = markdown2.markdown(body)
    rec.update({'body_html': body_html})
    slug = rec.get('slug')
    title = rec.get('title')
    excerpt = rec.get('excerpt')
    markdown = rec.get('markdown') or 'markdown'
    tags = rec.get('tags') or []
    if len(tags) == 0:
        tags = ['general']
    tags = [db.Category(utils.slugify(tag)) for tag in tags if tag]
    
    static = rec.get('static')
    
    if not slug:
        utils.slugify(title)
        
    if not excerpt:
        soup = BeautifulSoup.BeautifulSoup(body_html)
        paras = soup.findAll('p')
        if paras:
            excerpt = paras[0].string
    return Entry(author=users.get_current_user(),
    title=title,
    slug=slug,
    body=body,
    body_html=body_html,
    markdown=markdown,
    excerpt=excerpt,
    tags= tags,
    static=static,
    )
Exemplo n.º 3
0
    def test_entity_to_dict(self):
        """Converts a datastore.Entity instance to a JSON encodable dict."""

        from datetime import datetime
        from gaesynkit import handlers
        from google.appengine.api import datastore
        from google.appengine.api import datastore_types
        from google.appengine.api import users
        from google.appengine.ext import db

        entity = datastore.Entity("Test")
        entity.update({
            "string": "A string.",
            "byte_string": datastore_types.ByteString("Byte String"),
            "boolean": True,
            "int": 42,
            "float": 1.82,
            "date": datetime(2011, 01, 06),
            "list": [1, 2, 3, 4],
            "key": db.Key.from_path("Kind", "name"),
            "user": users.User("*****@*****.**"),
            "email": db.Email("*****@*****.**"),
            "location": db.GeoPt(52.500556, 13.398889),
            "category": db.Category("coding"),
            "link": db.Link("http://www.google.com"),
            "im": db.IM("sip", "foobar"),
            "phone": db.PhoneNumber("1 (206) 555-1212"),
            "address": db.PostalAddress("Address"),
            "rating": db.Rating(99)
        })
Exemplo n.º 4
0
    def post(self):
        key = self.get_argument("key", None)
        if key:
            entry = Entry.get(key)
            entry.title = self.get_argument("title")
            entry.markdown = self.get_argument("markdown")
            categories = [
                c.strip() for c in self.get_argument("categories").split(',')
                if len(c.strip()) != 0
            ]
            entry.categories = [
                cat if type(cat) == db.Category else db.Category(unicode(cat))
                for cat in categories
            ]
            entry.html = markdown.markdown(self.get_argument("markdown"))
        else:
            title = self.get_argument("title")
            slug = unicodedata.normalize("NFKD",
                                         title).encode("ascii", "ignore")
            slug = re.sub(r"[^\w]+", " ", slug)
            slug = "-".join(slug.lower().strip().split())
            if not slug: slug = "entry"
            while True:
                existing = db.Query(Entry).filter("slug =", slug).get()
                if not existing or str(existing.key()) == key:
                    break
                slug += "-2"

            categories = [
                c.strip() for c in self.get_argument("categories").split(',')
                if len(c.strip()) != 0
            ]
            standarlized_categories = [
                cat if type(cat) == db.Category else db.Category(unicode(cat))
                for cat in categories
            ]
            entry = Entry(author=self.current_user,
                          title=title,
                          slug=slug,
                          markdown=self.get_argument("markdown"),
                          html=markdown.markdown(
                              self.get_argument("markdown")),
                          categories=standarlized_categories)
        entry.put()
        # entry.index()
        entry.enqueue_indexing(url="/tasks/searchindexing")
        self.redirect("/entry/" + entry.slug)
Exemplo n.º 5
0
def index(request):
    if 'offset' in request.GET:
        offset = int(request.GET['offset'])
    else:
        offset = 0

    # use Users API to get current user
    user = users.get_current_user()

    # if a user is logged in, redirect to their workstack page
    if not user:
        greeting = ("<a href=\"%s\">Sign in or register</a>." %
                    users.create_login_url("/"))
        return HttpResponse("<html><body><h1>Workstack</h1>%s</body></html>" %
                            greeting)

    logout_url = users.create_logout_url("/")

    commands = Command.all().filter("user ="******"blocks =",
                              account.task).filter("status =",
                                                   db.Category("todo"))
    slushtasks = Task.all().filter("proposer =", user).filter(
        "blocks =", None).filter("status =", db.Category("todo"))

    stack = []
    tt = account.task
    while tt is not None:
        stack.append(tt)
        tt = tt.blocks

    for i, task in enumerate(reversed(stack)):
        task.level = i

    return render_to_response(
        "index.html", {
            'account': account,
            'commands': commands,
            'user': user,
            'logout_url': logout_url,
            'todos': todos,
            'stack': stack,
            'offset': offset + 50,
            'slushtasks': slushtasks
        })
Exemplo n.º 6
0
 def convert_string_tags(cls, tags):
     new_tags = []
     for t in tags:
         if type(t) == db.Category:
             new_tags.append(t)
         else:
             new_tags.append(db.Category(unicode(t)))
     return new_tags
Exemplo n.º 7
0
    def clean_tags_string(self):
        if not self.cleaned_data['tags_string']:
            return []

        return [
            db.Category(tag)
            for tag in self.cleaned_data['tags_string'].split(' ')
        ]
Exemplo n.º 8
0
    def convertStringToMaplist(cls, maplist):
        new_maplist = []
        for map in maplist:
            if type(map) == db.Category:
                new_maplist.append(map)
            else:
                new_maplist.append(db.Category(unicode(map)))

        return new_maplist
Exemplo n.º 9
0
 def _save_posts(self, posts, service):
     for post in posts:
         entry = Entry(
             service=service,
             hash=post['hash'],
             url=post['url'],
             title=post['title'],
             description=post['description'],
             time=post['time'],
             tags = [db.Category(tag) for tag in post['tags'] if tag ]
         )
         entry.put()
     self.free_cache()
Exemplo n.º 10
0
    def post(self, slug=None):
        title = self.request.get("title")
        body = self.request.get("body")
        markdown = self.request.get("markup")
        st = self.request.get("static")
        cm = self.request.get("comments")
        if st == '1': static = True
        else: static = False
        if cm == '1': comments = True
        else: comments = False

        tags = self.request.get("tags")
        tags = tags.split(' ')
        if len(tags) == 0:
            tags = ['general']
        tags = [db.Category(utils.slugify(tag)) for tag in tags if tag]

        body_html = to_html(body, markdown)

        soup = BeautifulSoup.BeautifulSoup(body_html)
        paras = soup.findAll('p')

        if paras:
            excerpt = paras[0].string
        else:
            excerpt = ''

        entry = db.Query(Entry).filter("slug =", slug).get()
        if not entry:
            entry = Entry(
                author=users.get_current_user(),
                title=title,
                slug=utils.slugify(title),
                body=body,
                body_html=body_html,
                markdown=markdown,
                excerpt=excerpt,
                tags=tags,
                static=static,
                comments=comments,
            )
        else:
            entry.title = title
            entry.body = body
            entry.body_html = body_html
            entry.excerpt = excerpt
            entry.static = static
            entry.tags = tags
            entry.comments = comments
        entry.put()
        self.redirect(entry.url())
Exemplo n.º 11
0
def switch(command_args, account):

    uuid = command_args.strip()
    task = Task.all().filter("uuid =", uuid)[0]
    task.status = db.Category("underway")
    account.task = task
    account.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="SWITCH",
                      args=command_args,
                      task=task)
    command.put()
Exemplo n.º 12
0
def pop(command_args, account):
    tobepopped = account.task
    tobepopped.status = db.Category("finished")
    tobepopped.put()

    account.task = account.task.blocks
    account.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="POP",
                      args=command_args,
                      task=tobepopped)
    command.put()
Exemplo n.º 13
0
def slush(command_args, account):
    title = command_args

    task = Task(proposer=account.user,
                proposed=datetime.datetime.now(),
                title=title,
                uuid=uuid.uuid1().hex,
                status=db.Category("todo"),
                blocks=None)
    task.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="SLUSH",
                      args=command_args,
                      task=task)
    command.put()
Exemplo n.º 14
0
    def new(title, content, labels, links):
        keyname = Entry.build_key(title)
        entry = Entry(key_name=keyname,
                      title=title,
                      content=content,
                      labels=[db.Category(l) for l in labels],
                      links=links)

        store = [entry]
        
        results = Entry.get_recent(1)
        if results:
            prev = results[0]
            entry.prev_entry = prev.key()
            prev.next_entry = db.Key.from_path('Entry', keyname)
            store.append(prev)

        db.put(store)
        return entry
Exemplo n.º 15
0
def push(command_args, account):
    title = command_args

    task = Task(proposer=account.user,
                proposed=datetime.datetime.now(),
                title=title,
                uuid=uuid.uuid1().hex,
                status=db.Category("underway"),
                blocks=account.task)
    task.put()

    account.task = task
    account.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="PUSH",
                      args=command_args,
                      task=task)
    command.put()
Exemplo n.º 16
0
 def post(self):
     key = self.get_argument("key", None)
     if key:
         try:
             entry = Entry.get(key)
         except db.BadKeyError:
             self.redirect("/")
             return
         entry.body = self.get_argument("body")
         entry.title = self.get_argument("title")
     else:
         title = self.get_argument("title")
         slug = self.slugify(title)
         if not slug:
             slug = "entry"
         original_slug = slug
         while db.Query(Entry).filter("slug = ", slug).get():
             slug = original_slug + "-" + uuid.uuid4().hex[:2]
         entry = Entry(
             author=self.current_user,
             body=self.get_argument("body"),
             slug=slug,
             title=title,
         )
     tags = set([
         self.slugify(unicode(tag))
         for tag in self.get_argument("tags", "").split(",")
     ])
     tags = [db.Category(tag) for tag in tags if tag]
     entry.tags = tags
     entry.hidden = bool(self.get_argument("hidden", False))
     entry.put()
     memcache.delete('home_entries:%s:%s' %
                     (None, self.application.settings.get("num_home", 5)))
     if not key and not entry.hidden:
         self.ping()
     self.redirect("/" + entry.slug)
Exemplo n.º 17
0
 def post(self):
     key = self.get_argument("key", None)
     if key:
         entry = Entry.get(key)
         entry.title = self.get_argument("title", "")
         entry.description = self.get_argument("description", "")
         entry.url = self.get_argument("url", "")
     else:
         h = hashlib.sha1()
         h.update(self.get_argument("url", ""))
         entry = Entry(
             service="internal",
             title=self.get_argument("title", ""),
             description=self.get_argument("description", ""),
             url=self.get_argument("url", ""),
             hash=h.hexdigest(),
         )
     tags = set([self.slugify(unicode(tag)) for tag in
         self.get_argument("tags", "").split(",")])
     tags = [db.Category(tag) for tag in tags if tag]
     entry.tags = tags
     entry.put()
     self.free_cache(tags=entry.tags)
     self.redirect("/")
Exemplo n.º 18
0
	def create_new(title, content, categories = []):
		
		cats = []
		for category in categories:
			cats.append(db.Category(category))
			
		post = Post(
			key_name = self.get_stub(title),
			title = title,
			excerpt = content[:250],
			content = content, 
			status = "draft",
			categories = cats,
			stub = self.get_stub(title),
			author = users.get_current_user(), 
			post_type = "post",
			pubdate = datetime.datetime.now()
		)
		
		try:
			post.put()
		except CapabilityDisabledError:
			return false
		return true 
Exemplo n.º 19
0
def import_from_json(data, show=False):
    ret = []

    if show:
        print len([i for i in Entry.all()])

    # Deserialize
    objects = simplejson.loads(data)

    for obj in objects:
        if obj['model'] != 'blog.entry':
            continue

        #if obj['fields']['media_type'] == 'I':
        #    print "'%s': %s"%(obj['fields']['slug'], obj['pk'])
        #continue

        if obj['fields']['media_type'] != 'P' or not obj['fields']['published']:
            continue

        msg = '%d %s' % (obj['pk'], obj['fields']['title'])
        if show:
            print msg
        else:
            ret.append(msg)

        # Blog entry
        try:
            entry = Entry.all().filter('old_id =', int(obj['pk']))[0]
        except IndexError:
            entry = Entry()

        entry.old_id = obj['pk']

        m = RE_DATETIME.match(obj['fields']['pub_date'])
        groups = [int(i) for i in m.groups()]
        entry.pub_date = datetime.datetime(*groups)

        entry.title = obj['fields']['title']
        entry.description = obj['fields']['description']
        entry.format = obj['fields']['format']
        entry.published = True
        entry.show_in_rss = False
        entry.slug = obj['fields']['slug']
        entry.tags = [db.Category(TAGS[tag]) for tag in obj['fields']['tags']]

        text = obj['fields']['content']
        text = text.replace('http://media.marinhobrandao.com/', '/')

        f = RE_IMG_URL.findall(text)
        rep = []

        for url in f:
            m = RE_IMG_URL2.match(url)
            new_url = '/media/img/upload/%s' % IMAGES[m.group(1)]

            if show:
                print '\t', new_url

            text = text.replace(url, new_url)

        entry.text = text

        entry.save()

        # Gallery image

    msg = [i.slug for i in Entry.all()]
    if show:
        print msg
    else:
        ret.append(' '.join([i for i in msg]))
Exemplo n.º 20
0
def getproperty(kind, p, key=False):
    if key:
        input_name = 'input__p__key__%s' % p
    else:
        input_name = 'input__p__%s' % p
    v = getattr(request.forms, input_name)
    if not key:
        property_class = kind._properties[p]
    else:
        property_class = db.StringProperty()
    logging.info("p = %s" % p)
    logging.info("v = %s" % v)
    logging.info("property_class = %s" % property_class)
    if not v:
        v = None
    else:
        if isinstance(property_class, db.BooleanProperty):
            if v.lower() in ['false', 'no']:
                v = False
            else:
                v = bool(v)
        elif isinstance(property_class, db.IntegerProperty):
            v = long(v)
        elif isinstance(property_class, db.FloatProperty):
            v = float(v)
        elif isinstance(property_class, db.DateTimeProperty):
            v = datetime.datetime.strptime(v, '%Y-%m-%d %H:%M:%S.%f')
        elif isinstance(property_class, db.LinkProperty):
            v = db.Link(v)
        elif isinstance(property_class, db.TextProperty):
            v = db.Text(v)
        elif isinstance(property_class, db.BlobProperty):
            v = db.Blob(v)
        elif isinstance(property_class, db.EmailProperty):
            v = db.Email(v)
        elif isinstance(property_class, db.GeoPtProperty):
            lat, lon = [float(x) for x in v.split(',', 1).strip()]
            v = db.GeoPt(lat, lon)
        elif isinstance(property_class, db.RatingProperty):
            v = db.Rating(int(v))
        elif isinstance(property_class, db.CategoryProperty):
            v = db.Category(v)
        elif isinstance(property_class,
                        (db.ListProperty, db.StringListProperty)):
            # todo assumes list of strings
            v = list([v.strip() for v in v.split(",")])
        elif isinstance(property_class, db.ReferenceProperty):
            kindname = property_class.reference_class.__name__
            v = db.Key(kindname, v)
        elif isinstance(property_class, blobstore.BlobReferenceProperty):
            v = blobstore.BlobKey(v)
        elif isinstance(
                property_class,
            (db.IMProperty, db.PhoneNumberProperty, db.PostalAddressProperty)):
            abort(
                500, 'Unsupported property type %s for model %s' %
                (property_class, kind.__name__))
    if key and v is None:
        abort(
            400, 'Property %s is part of the key for model %s so is required' %
            (p, kind.__name__))
    return v
Exemplo n.º 21
0
    def testQueriesWithMultipleFiltersAndOrders(self):
        """Tests queries with multiple filters and orders."""
        class Artist(db.Model):
            name = db.StringProperty()

        class Album(db.Model):
            title = db.StringProperty()

        class Song(db.Model):
            artist = db.ReferenceProperty(Artist)
            album = db.ReferenceProperty(Album)
            duration = db.StringProperty()
            genre = db.CategoryProperty()
            title = db.StringProperty()

        beatles = Artist(name="The Beatles")
        beatles.put()

        abbeyroad = Album(title="Abbey Road")
        abbeyroad.put()

        herecomesthesun = Song(artist=beatles.key(),
                               album=abbeyroad.key(),
                               duration="3:06",
                               genre=db.Category("Pop"),
                               title="Here Comes The Sun")
        herecomesthesun.put()

        query = (Song.all().filter('artist =',
                                   beatles).filter('album =', abbeyroad))

        self.assertEqual(u'Here Comes The Sun', query.get().title)

        cometogether = Song(artist=beatles.key(),
                            album=abbeyroad.key(),
                            duration="4:21",
                            genre=db.Category("Pop"),
                            title="Come Together")
        cometogether.put()

        something = Song(artist=beatles.key(),
                         album=abbeyroad.key(),
                         duration="3:03",
                         genre=db.Category("Pop"),
                         title="Something")
        something.put()

        because1 = Song(key_name='because',
                        artist=beatles.key(),
                        album=abbeyroad.key(),
                        duration="2:46",
                        genre=db.Category("Pop"),
                        title="Because")
        because1.put()

        because2 = Song(artist=beatles.key(),
                        album=abbeyroad.key(),
                        duration="2:46",
                        genre=db.Category("Pop"),
                        title="Because")
        because2.put()

        query = (Song.all().filter('artist =',
                                   beatles).filter('album =',
                                                   abbeyroad).order('title'))

        self.assertEqual([
            u'Because', u'Because', u'Come Together', u'Here Comes The Sun',
            u'Something'
        ], [song.title for song in query.run()])

        query = Song.all().filter('title !=', 'Because').order('title')

        self.assertEqual(
            [u'Come Together', u'Here Comes The Sun', u'Something'],
            [song.title for song in query.run()])

        query = Song.all().filter('title >', 'Come').order('title')

        self.assertEqual(
            [u'Come Together', u'Here Comes The Sun', u'Something'],
            [song.title for song in query.run()])

        something.delete()

        query = Song.all().filter('title >', 'Come').order('title')

        self.assertEqual([u'Come Together', u'Here Comes The Sun'],
                         [song.title for song in query.run()])
Exemplo n.º 22
0
except db.BadValueError:
    pass
art = Article(content="some content",
              link="http://www.example.com",
              author_mail="not an email")
try:
    art = Article(content="some content",
                  link="http://www.example.com",
                  author_mail="not an email",
                  rating=101)
    assert False
except db.BadValueError:
    pass
art = Article(title="my title",
              content="some content",
              tags=[db.Category("awesome"),
                    db.Category("super")],
              author_mail="*****@*****.**",
              link="http://www.example.com",
              rating=65)
assert art.title == "my title"
assert art.tags[1] == "super"
print '&nbsp;&nbsp;&nbsp;&nbsp;Put and Fetch<br/>'

art.put()
out = Article.all().fetch(10)[0]
assert art.title == out.title
assert art.content == out.content
assert art.tags == out.tags
assert art.author_mail == out.author_mail
assert art.link == out.link
Exemplo n.º 23
0
 def get_tags_argument(self, name):
     tags = [slugify(tag) for tag in self.request.get(name, "").split(",")]
     tags = set([tag for tag in tags if tag])
     return [db.Category(tag) for tag in tags]
Exemplo n.º 24
0
 def set_tags(self, tags):
     if tags:
         self.tags = [
             db.Category(urllib.quote(tag.strip().encode('utf8')))
             for tag in tags.split(',')
         ]
Exemplo n.º 25
0
    def post(self):
        #********************** User Auth **************************#
        user = users.get_current_user()
        nickname = ''
        if user:
            nickname = user.nickname()
        if nickname:
            key = self.request.get('key')
            if key:
                e = db.get(key)
                if e.user != nickname:
                    e = Entry()
                    e.user = nickname
            else:
                e = Entry()
                e.user = nickname
            type = self.request.get('type')
            if not type:
                type = 'link'
            tz = self.request.get('tz')
            if tz[0:1] == '-':
                tz = int(tz[1:])
                tz = -tz
            else:
                tz = int(tz[1:])
                tz = +tz

            title = self.request.get('title')
            e.title = title.replace('&', '&amp;').replace('<', '&lt;').replace(
                '>', '&gt;')
            url = self.request.get('url')
            purl = self.request.get('purl')
            if type == 'pic' and not key:
                e.url = purl.replace('&', '&amp;').replace('<',
                                                           '&lt;').replace(
                                                               '>', '&gt;')
            else:
                e.url = url.replace('&', '&amp;').replace('<', '&lt;').replace(
                    '>', '&gt;')
            content = self.request.get('content')
            e.content = content
            if not key:
                e.addtime += datetime.timedelta(hours=tz)
            e.private = bool(int(self.request.get('private')))
            e.type = type
            if type == 'pic' and not key:
                if url:
                    try:
                        result = urlfetch.fetch(url)
                        if result.status_code == 200:
                            e.image = db.Blob(result.content)
                    except:
                        self.response.out.write(
                            'Fetch picture fail! You can <a href="/add?type=pic">upload</a> it manually'
                        )
                        return
                else:
                    myfile = self.request.get("myfile")
                    if not myfile:
                        self.response.out.write('No file specified!')
                        return
                    try:
                        e.image = db.Blob(myfile)
                    except:
                        self.response.out.write('Uploading fail!')
                        return

            if key:  #更新数据
                for oldtag in e.tags:
                    tag = Tag.all().filter("user",
                                           nickname).filter('name', oldtag)
                    if (tag.count(1) > 0):
                        t = tag.get()
                        if type == 'link':
                            t.count_link -= 1
                        if type == 'note':
                            t.count_note -= 1
                        if type == 'pic':
                            t.count_pic -= 1
                        t.put()
            else:  #新增数据
                max_pageCount = 900  #超过此数据,则pageid递增
                entry = Entry.all().order('-addtime')
                if entry.count() > 0:
                    cur_pageid = entry.get().pageid
                else:
                    cur_pageid = 0

                cur_pageCount = entry.filter('pageid =',
                                             cur_pageid).count(1000)

                if cur_pageCount >= max_pageCount:
                    e.pageid = cur_pageid + 1
                else:
                    e.pageid = cur_pageid

            e.tags = []
            tag_names = self.request.get('tags').split()
            for tag_name in tag_names:
                tag = Tag.all().filter("user",
                                       nickname).filter('name', tag_name)
                if (tag.count(1) > 0):
                    t = tag.get()
                    if type == 'link':
                        t.count_link += 1
                    if type == 'note':
                        t.count_note += 1
                    if type == 'pic':
                        t.count_pic += 1
                    t.user = nickname
                    t.usetime = datetime.datetime.now()
                    t.put()
                else:
                    t = Tag()
                    t.name = tag_name
                    if type == 'link':
                        t.count_link = 1
                    if type == 'note':
                        t.count_note = 1
                    if type == 'pic':
                        t.count_pic = 1
                    t.user = nickname
                    t.usetime = datetime.datetime.now()
                    t.put()
                e.tags.append(db.Category(tag_name))
            e.put()
            self.redirect('/' + type + '/' + nickname)
        else:
            self.redirect(users.create_login_url(self.request.uri))
Exemplo n.º 26
0
 def set_tags(self, tags):
     if tags:
         tags = tags.strip(' ')
         tags = [db.Category(urllib.quote(tag.strip())) for tag in tags.split(' ')]
         self.tags = [tag for tag in tags if not tag in self.tags]
Exemplo n.º 27
0
    def post(self):

        if users.is_current_user_admin():
            key = self.request.get('key')
            if key:
                e = db.get(key)

            else:
                e = Entry()

            type = self.request.get('type')
            if not type:
                type = 'link'
            title = self.request.get('title')
            e.title = title.replace('&', '&amp;').replace('<', '&lt;').replace(
                '>', '&gt;')
            url = self.request.get('url')
            purl = self.request.get('purl')
            if type == 'pic' and not key:
                e.url = purl.replace('&', '&amp;').replace('<',
                                                           '&lt;').replace(
                                                               '>', '&gt;')
            else:
                e.url = url.replace('&', '&amp;').replace('<', '&lt;').replace(
                    '>', '&gt;')
            content = self.request.get('content')
            e.content = content
            if not key:
                e.addtime += datetime.timedelta(hours=+8)
            e.private = bool(int(self.request.get('private')))
            e.type = type
            if type == 'pic' and not key:
                if url:
                    try:
                        result = urlfetch.fetch(url)
                        if result.status_code == 200:
                            e.image = db.Blob(result.content)
                    except:
                        self.response.out.write('获取图片超时!')
                        return
                else:
                    myfile = self.request.get("myfile")
                    if not myfile:
                        self.response.out.write('没有选择文件!')
                        return
                    try:
                        e.image = db.Blob(myfile)
                    except:
                        self.response.out.write('文件上传失败!')
                        return

            if key:  #更新数据
                for oldtag in e.tags:
                    tag = Tag.all().filter('name', oldtag)
                    if (tag.count(1) > 0):
                        t = tag.get()
                        if type == 'link':
                            t.count_link -= 1
                        if type == 'note':
                            t.count_note -= 1
                        if type == 'pic':
                            t.count_pic -= 1
                        t.put()
            else:  #新增数据
                max_pageCount = 900  #超过此数据,则pageid递增
                entry = Entry.all().order('-addtime')
                if entry.count() > 0:
                    cur_pageid = entry.get().pageid
                else:
                    cur_pageid = 0

                cur_pageCount = entry.filter('pageid =',
                                             cur_pageid).count(1000)

                if cur_pageCount >= max_pageCount:
                    e.pageid = cur_pageid + 1
                else:
                    e.pageid = cur_pageid

            e.tags = []
            tag_names = self.request.get('tags').split()
            for tag_name in tag_names:
                tag = Tag.all().filter('name', tag_name)
                if (tag.count(1) > 0):
                    t = tag.get()
                    if type == 'link':
                        t.count_link += 1
                    if type == 'note':
                        t.count_note += 1
                    if type == 'pic':
                        t.count_pic += 1

                    t.usetime = datetime.datetime.now()
                    t.put()
                else:
                    t = Tag()
                    t.name = tag_name
                    if type == 'link':
                        t.count_link = 1
                    if type == 'note':
                        t.count_note = 1
                    if type == 'pic':
                        t.count_pic = 1

                    t.usetime = datetime.datetime.now()
                    t.put()
                e.tags.append(db.Category(tag_name))
            e.put()
            self.redirect('/' + type + '/')
        else:
            self.redirect(users.create_login_url(self.request.uri))
Exemplo n.º 28
0
from hashlib import sha256

from regex import re

from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app

from entities import User
from entities import Poem
from entities import Error
from entities import Comment

template_dir = os.path.join(os.path.dirname(__file__),'templates')
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),autoescape=True)

USER = db.Category("user")
ADMIN = db.Category("admin")

#CONFIG: Change this to suit yourself
ADMINISTRATOR = 'administrator'
SITE_TITLE = "A Child of Hard Times"
SITE_SUBTITLE = "Poems by Bea Sisk"
COMMENT_SUBTITLE = "Comments"
COPYRIGHT_NOTICE = "&copy;Bea Sisk 2012 - All rights reserved, no wrongs deserved."

def hash_str(s):
    return md5(s).hexdgest()

def make_secure_val(s):
    return "%s,%s" % (s,hash_str(s))