예제 #1
0
 def get(self):
     blogs = db.GqlQuery( "SELECT * FROM Blog_Post "
                         "ORDER BY created DESC ")
     self.render("front.html", blogs = blogs)
예제 #2
0
def get_streams_of_visitors(owner):
    return db.GqlQuery('SELECT * FROM ClientStream WHERE owner = :1 AND is_owner = :2', owner, False)
예제 #3
0
def get_streams_expired():
    return db.GqlQuery('SELECT * FROM ClientStream WHERE modified_on < :1', datetime.datetime.fromtimestamp(time.time()-90))
예제 #4
0
    def GetRec(self, Key):  # 指定キーのデータ取得

        Sql = "SELECT * FROM " + self.__class__.__name__
        Sql += " Where __key__ = KEY('" + str(Key) + "')"
        Query = db.GqlQuery(Sql)
        return Query.fetch(Query.count())[0]
예제 #5
0
def get_stream_by_publish(url):
    return db.GqlQuery('SELECT * FROM ClientStream WHERE publish = :1', url).get()
예제 #6
0
def fetch_events_day(start, end):
  query = 'SELECT * FROM Events WHERE timestamp >= :1 AND timestamp <= :2'
  query += ' ORDER BY timestamp ASC'
  events = db.GqlQuery(query, start, end)
  return _populate_events(events)
예제 #7
0
def fetch_event_attendees(event_id):
  query = 'SELECT * FROM UserEvents WHERE event_id = :1'
  attendees = db.GqlQuery(query, event_id)
  return attendees
예제 #8
0
 def post(self, node_name):
     site = GetSite()
     browser = detect(self.request)
     template_values = {}
     template_values['site'] = site
     template_values['system_version'] = SYSTEM_VERSION
     member = CheckAuth(self)
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     template_values[
         'page_title'] = site.title + u' › ' + l10n.create_new_topic.decode(
             'utf-8')
     if (member):
         template_values['member'] = member
         q = db.GqlQuery("SELECT * FROM Node WHERE name = :1", node_name)
         node = False
         if (q.count() == 1):
             node = q[0]
         template_values['node'] = node
         section = False
         if node:
             q2 = db.GqlQuery("SELECT * FROM Section WHERE num = :1",
                              node.section_num)
             if (q2.count() == 1):
                 section = q2[0]
         template_values['section'] = section
         errors = 0
         # Verification: title
         topic_title_error = 0
         topic_title_error_messages = [
             '', u'请输入主题标题', u'主题标题长度不能超过 120 个字符'
         ]
         topic_title = self.request.get('title').strip()
         if (len(topic_title) == 0):
             errors = errors + 1
             topic_title_error = 1
         else:
             if (len(topic_title) > 120):
                 errors = errors + 1
                 topic_title_error = 2
         template_values['topic_title'] = topic_title
         template_values['topic_title_error'] = topic_title_error
         template_values[
             'topic_title_error_message'] = topic_title_error_messages[
                 topic_title_error]
         # Verification: content
         topic_content_error = 0
         topic_content_error_messages = [
             '', u'请输入主题内容', u'主题内容长度不能超过 2000 个字符'
         ]
         topic_content = self.request.get('content').strip()
         if (len(topic_content) == 0):
             errors = errors + 1
             topic_content_error = 1
         else:
             if (len(topic_content) > 2000):
                 errors = errors + 1
                 topic_content_error = 2
         template_values['topic_content'] = topic_content
         template_values['topic_content_error'] = topic_content_error
         template_values[
             'topic_content_error_message'] = topic_content_error_messages[
                 topic_content_error]
         # Verification: type
         if site.use_topic_types:
             types = site.topic_types.split("\n")
             if len(types) > 0:
                 topic_type = self.request.get('type').strip()
                 try:
                     topic_type = int(topic_type)
                     if topic_type < 0:
                         topic_type = 0
                     if topic_type > len(types):
                         topic_type = 0
                     if topic_type > 0:
                         detail = types[topic_type - 1].split(':')
                         topic_type_label = detail[0]
                         topic_type_color = detail[1]
                 except:
                     topic_type = 0
             else:
                 topic_type = 0
             options = '<option value="0">&nbsp;&nbsp;&nbsp;&nbsp;</option>'
             i = 0
             for a_type in types:
                 i = i + 1
                 detail = a_type.split(':')
                 if topic_type == i:
                     options = options + '<option value="' + str(
                         i
                     ) + '" selected="selected">' + detail[0] + '</option>'
                 else:
                     options = options + '<option value="' + str(
                         i) + '">' + detail[0] + '</option>'
             tt = '<div class="sep5"></div><table cellpadding="5" cellspacing="0" border="0" width="100%"><tr><td width="60" align="right">Topic Type</td><td width="auto" align="left"><select name="type">' + options + '</select></td></tr></table>'
             template_values['tt'] = tt
         else:
             template_values['tt'] = ''
         template_values['errors'] = errors
         if (errors == 0):
             topic = Topic(parent=node)
             q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                             'topic.max')
             if (q.count() == 1):
                 counter = q[0]
                 counter.value = counter.value + 1
             else:
                 counter = Counter()
                 counter.name = 'topic.max'
                 counter.value = 1
             q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                              'topic.total')
             if (q2.count() == 1):
                 counter2 = q2[0]
                 counter2.value = counter2.value + 1
             else:
                 counter2 = Counter()
                 counter2.name = 'topic.total'
                 counter2.value = 1
             topic.num = counter.value
             topic.title = topic_title
             topic.content = topic_content
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_content.html')
             output = template.render(path, {'topic': topic})
             topic.content_rendered = output.decode('utf-8')
             topic.node = node
             topic.node_num = node.num
             topic.node_name = node.name
             topic.node_title = node.title
             topic.created_by = member.username
             topic.member = member
             topic.member_num = member.num
             topic.last_touched = datetime.datetime.now()
             ua = self.request.headers['User-Agent']
             if (re.findall('Mozilla\/5.0 \(iPhone;', ua)):
                 topic.source = 'iPhone'
             if (re.findall('Mozilla\/5.0 \(iPod;', ua)):
                 topic.source = 'iPod'
             if (re.findall('Mozilla\/5.0 \(iPad;', ua)):
                 topic.source = 'iPad'
             if (re.findall('Android', ua)):
                 topic.source = 'Android'
             if (re.findall('Mozilla\/5.0 \(PLAYSTATION 3;', ua)):
                 topic.source = 'PS3'
             if site.use_topic_types:
                 if topic_type > 0:
                     topic.type = topic_type_label
                     topic.type_color = topic_type_color
             node.topics = node.topics + 1
             node.put()
             topic.put()
             counter.put()
             counter2.put()
             memcache.delete('feed_index')
             memcache.delete('Node_' + str(topic.node_num))
             memcache.delete('Node::' + str(node.name))
             memcache.delete('home_rendered')
             memcache.delete('home_rendered_mobile')
             taskqueue.add(url='/index/topic/' + str(topic.num))
             # Twitter Sync
             if member.twitter_oauth == 1 and member.twitter_sync == 1:
                 access_token = OAuthToken.from_string(
                     member.twitter_oauth_string)
                 twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                    access_token)
                 status = topic.title + ' #' + topic.node.name + ' http://' + self.request.headers[
                     'Host'] + '/t/' + str(topic.num)
                 try:
                     twitter.PostUpdate(status.encode('utf-8'))
                 except:
                     logging.error("Failed to sync to Twitter for Topic #" +
                                   str(topic.num))
             self.redirect('/t/' + str(topic.num) + '#reply0')
         else:
             if browser['ios']:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'mobile', 'new_topic.html')
             else:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'desktop', 'new_topic.html')
             output = template.render(path, template_values)
             self.response.out.write(output)
     else:
         self.redirect('/signin')
예제 #9
0
 def get(self, topic_num):
     site = GetSite()
     browser = detect(self.request)
     template_values = {}
     template_values['site'] = site
     template_values['rnd'] = random.randrange(1, 100)
     reply_reversed = self.request.get('r')
     if reply_reversed == '1':
         reply_reversed = True
     else:
         reply_reversed = False
     filter_mode = self.request.get('f')
     if filter_mode == '1':
         filter_mode = True
     else:
         filter_mode = False
     template_values['reply_reversed'] = reply_reversed
     template_values['filter_mode'] = filter_mode
     template_values['system_version'] = SYSTEM_VERSION
     errors = 0
     template_values['errors'] = errors
     member = CheckAuth(self)
     template_values['member'] = member
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     if member is not False:
         try:
             blocked = pickle.loads(member.blocked.encode('utf-8'))
         except:
             blocked = []
         if (len(blocked) > 0):
             template_values['blocked'] = ','.join(map(str, blocked))
         if member.num == 1:
             template_values['is_admin'] = 1
         else:
             template_values['is_admin'] = 0
     topic_num_str = str(topic_num)
     if len(topic_num_str) > 8:
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic_not_found.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic_not_found.html')
         output = template.render(path, template_values)
         self.response.out.write(output)
         return
     topic = False
     topic = memcache.get('Topic_' + str(topic_num))
     if topic is None:
         q = db.GqlQuery("SELECT * FROM Topic WHERE num = :1",
                         int(topic_num))
         if (q.count() == 1):
             topic = q[0]
             memcache.set('Topic_' + str(topic_num), topic, 86400)
     if topic:
         taskqueue.add(url='/hit/topic/' + str(topic.key()))
         template_values['page_title'] = site.title + u' › ' + topic.title
         template_values[
             'canonical'] = 'http://' + site.domain + '/t/' + str(topic.num)
         if topic.content_rendered is None:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_content.html')
             output = template.render(path, {'topic': topic})
             topic = db.get(topic.key())
             topic.content_rendered = output.decode('utf-8')
             memcache.delete('Topic_' + str(topic.num))
             topic.put()
     else:
         template_values['page_title'] = site.title + u' › 主题未找到'
     template_values['topic'] = topic
     if member:
         if member.num == 1:
             template_values['can_edit'] = True
         else:
             template_values['can_edit'] = False
     if (topic):
         node = False
         section = False
         node = GetKindByNum('Node', topic.node_num)
         if (node):
             section = GetKindByNum('Section', node.section_num)
         template_values['node'] = node
         template_values['section'] = section
         replies = False
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_replies_mobile.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_replies.html')
         if filter_mode:
             if browser['ios']:
                 r_tag = 'topic_' + str(
                     topic.num) + '_replies_filtered_rendered'
             else:
                 r_tag = 'topic_' + str(
                     topic.num) + '_replies_filtered_rendered_mobile'
             r = memcache.get(r_tag)
             if r is None:
                 replies = memcache.get('topic_' + str(topic.num) +
                                        '_replies_filtered_compressed')
                 if replies is None:
                     q5 = db.GqlQuery(
                         "SELECT * FROM Reply WHERE topic_num = :1 AND member_num = :2 ORDER BY created ASC",
                         topic.num, topic.member.num)
                     replies = q5
                     memcache.set(
                         'topic_' +
                         str(topic.num) + '_replies_filtered_compressed',
                         GetPacked(replies), 7200)
                 else:
                     replies = GetUnpacked(replies)
                 template_values['replies'] = replies
                 r = template.render(path, template_values)
                 memcache.set(r_tag, r, 86400)
         else:
             if reply_reversed:
                 if browser['ios']:
                     r_tag = 'topic_' + str(
                         topic.num) + '_replies_desc_rendered'
                 else:
                     r_tag = 'topic_' + str(
                         topic.num) + '_replies_desc_rendered_mobile'
                 r = memcache.get(r_tag)
                 if r is None:
                     replies = memcache.get('topic_' + str(topic.num) +
                                            '_replies_desc_compressed')
                     if replies is None:
                         q4 = db.GqlQuery(
                             "SELECT * FROM Reply WHERE topic_num = :1 ORDER BY created DESC",
                             topic.num)
                         replies = q4
                         memcache.set(
                             'topic_' +
                             str(topic.num) + '_replies_desc_compressed',
                             GetPacked(q4), 86400)
                     else:
                         replies = GetUnpacked(replies)
                     template_values['replies'] = replies
                     r = template.render(path, template_values)
                     memcache.set(r_tag, r, 86400)
             else:
                 if browser['ios']:
                     r_tag = 'topic_' + str(
                         topic.num) + '_replies_asc_rendered'
                 else:
                     r_tag = 'topic_' + str(
                         topic.num) + '_replies_asc_rendered_mobile'
                 r = memcache.get(r_tag)
                 if r is None:
                     replies = memcache.get('topic_' + str(topic.num) +
                                            '_replies_asc_compressed')
                     if replies is None:
                         q4 = db.GqlQuery(
                             "SELECT * FROM Reply WHERE topic_num = :1 ORDER BY created ASC",
                             topic.num)
                         replies = q4
                         memcache.set(
                             'topic_' +
                             str(topic.num) + '_replies_asc_compressed',
                             GetPacked(q4), 86400)
                     else:
                         replies = GetUnpacked(replies)
                     template_values['replies'] = replies
                     r = template.render(path, template_values)
                     memcache.set(r_tag, r, 86400)
         template_values['r'] = r
         if topic and member:
             if member.hasFavorited(topic):
                 template_values['favorited'] = True
             else:
                 template_values['favorited'] = False
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic.html')
     else:
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic_not_found.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic_not_found.html')
     output = template.render(path, template_values)
     self.response.out.write(output)
예제 #10
0
 def get(self):
     # Look up all posts by creation time and display latest 10.
     posts = db.GqlQuery(
         "select * from Post order by created desc limit 10")
     # Render those posts to front template.
     self.render('front.html', posts=posts)
예제 #11
0
    def get(self):

        player1 = Player(name='wizard612',
                         level=1,
                         score=32,
                         charclass='mage',
                         create_date=datetime.datetime.now())
        player1.put()

        player2 = Player(name='druidjane',
                         level=10,
                         score=896,
                         charclass='druid',
                         create_date=datetime.datetime.now())
        player2.put()

        player3 = Player(name='TheHulk',
                         level=7,
                         score=500,
                         charclass='warrior',
                         create_date=datetime.datetime.now())
        player3.put()

        # Create a GqlQuery object using the GqlQuery constructor.
        q = db.GqlQuery('SELECT * FROM Player ' + '        WHERE level > 5 ' +
                        '          AND level < 20 ' +
                        '     ORDER BY level ASC, score DESC')

        # Create a GqlQuery object using the model class method.
        q = Player.gql('        WHERE level > 5 ' +
                       '          AND level < 20 ' +
                       '     ORDER BY level ASC, score DESC')

        # Parameter substitution with positional arguments.
        q = db.GqlQuery(
            'SELECT * FROM Player ' + '        WHERE level > :1 ' +
            '          AND level < :2 ' +
            '     ORDER BY level ASC, score DESC', 5, 20)

        # Parameter substitution with keyword arguments.
        q = db.GqlQuery('SELECT * FROM Player ' +
                        '        WHERE level > :min_level ' +
                        '          AND level < :max_level ' +
                        '     ORDER BY level ASC, score DESC',
                        min_level=5,
                        max_level=20)

        # Parameter substitution with late binding.
        q = db.GqlQuery('SELECT * FROM Player ' +
                        '        WHERE level > :min_level ' +
                        '          AND level < :max_level ' +
                        '     ORDER BY level ASC, score DESC')
        q.bind(min_level=5, max_level=20)

        # Execute the query and iterate over all results.
        self.response.write('<p>Executing the query with iteration...</p>')
        for e in q:
            self.response.write('<p>Found result: name=%s, level=%d, '
                                'score=%d</p>' % (e.name, e.level, e.score))

        # An example of a date-time literal in GQL.
        q = db.GqlQuery(
            'SELECT * FROM Player ' +
            '        WHERE create_date < DATETIME(2012, 12, 31, 23, 59, 59)')

        # A keys-only query with GqlClass.
        q2 = db.GqlQuery('SELECT __key__ FROM Player')
        self.response.write('<p>Executing a keys-only query...</p>')
        for result_key in q2:
            self.response.write('<p>Found result key: %s</p>' % result_key)

        # Create an object of another kind.
        class GameObject(db.Expando):
            pass

        gameobj = GameObject().put()

        # A kindless query with GqlClass.
        #
        # Returns all Player and GameObject entities--and anything else in the
        # app's datastore.  Note that if you have entities in the datastore of
        # kinds other than Player or GameObject, you'll get a "No
        # implementation for kind..." error.  You can get this example working
        # by creating Expando classes for the other kinds:
        #
        # class KindName(db.Expando):
        #     pass
        q4 = db.GqlQuery('SELECT *')
        self.response.write('<p>Executing a kindless query...</p>')
        for e in q4:
            self.response.write('<p>Found result: key=%s</p>' % e.key())

        # Delete all entities.
        db.delete([player1, player2, player3, gameobj])
        self.response.write('<p>Entities deleted.</p>')

        self.response.write('<p>The time is: %s</p>' %
                            str(datetime.datetime.now()))
예제 #12
0
 def get_user_by_name(self, username):
     """ Get a user object from the db, based on their username """
     user = db.GqlQuery("SELECT * FROM User WHERE username = '******'" %
                        username)
     if user:
         return user.get()
예제 #13
0
파일: demeetr.py 프로젝트: JishnuM/Demeetr
    def get(self):
        if self.user_info():
            my_id = int(self.request.get('id'))
            event_key = db.Key.from_path('Event', my_id)
            event = db.get(event_key)

            # parent_key = db.Key.from_path('User', user.email())
            # user = db.get(parent_key)
            user = self.get_user()

            key_list = user.event_key_list

            query = db.GqlQuery(
                "SELECT * "
                "FROM Event "
                "WHERE __key__ IN :1 "
                "ORDER BY created_time ASC", key_list)

            option_query = db.GqlQuery(
                "SELECT * "
                "FROM Option "
                "WHERE ANCESTOR IS :1 "
                "ORDER BY votes DESC", event_key)

            post_query = db.GqlQuery(
                "SELECT * "
                "FROM Post "
                "WHERE ANCESTOR IS :1 "
                "ORDER BY created_time ASC", event_key)

            satisfied = []
            for option in option_query:
                if option.satisfied:
                    satisfied.append(option)
            if satisfied:
                event.confirmed = True
                best_option = satisfied[0]
                event.best_option_key = best_option.key()
            else:
                event.confirmed = False
                event.best_option_key = None
                best_option = None
            event.put()

            can_vote = []
            for option in option_query:
                if user.email in option.voters:
                    can_vote.append(False)
                else:
                    can_vote.append(True)

            total_votes = 0
            for option in option_query:
                total_votes += option.votes
            if total_votes == 0:
                total_votes = 1

            # if event.confirmed:
            # 	for x in range(0, event.total_times):
            # 		if event.className[x] == 'available':
            # 			temp_delta = datetime.timedelta(days = best_option.duration.day(), hours = best_option.duration.hour())
            # 			if ((event.overall_end - event.overall_start)>temp_delta):
            # 				date.append

            description = [("start", "datetime"), ("end", "datetime"),
                           ("content", "string"), ("group", "string"),
                           ("className", "string")]
            data = []

            # for debugging purposes
            # enter data directly
            # test1 = datetime.datetime(2013, 8, 1, 15, 23, 25)
            # test2 = datetime.datetime(2013, 8, 2, 11, 23, 25)
            # test3 = datetime.datetime(2013, 8, 1, 10, 2, 25)
            # test1e = datetime.datetime(2013, 8, 2, 15, 23, 25)
            # test2e = datetime.datetime(2013, 8, 3, 11, 23, 25)
            # test3e = datetime.datetime(2013, 8, 2, 10, 2, 25)
            # data = [[test1, test1e, "Unavailable", "1st", "unavailable"],
            # 		[test2, test2e, "Available", "2st", "available"],
            # 		[test3, test3e, "Maybe", "3st", "maybe"]]
            # enter data in datastore
            # event.overall_start.append(test1)
            # event.overall_end.append(test1e)
            # event.overall_content.append("available")
            # event.overall_group.append(user.name)
            # event.overall_className.append("available")

            # event.overall_start.append(test2)
            # event.overall_end.append(test2e)
            # event.overall_content.append("unavailable")
            # event.overall_group.append(user.name)
            # event.overall_className.append("unavailable")

            # event.overall_start.append(test3)
            # event.overall_end.append(test3e)
            # event.overall_content.append("maybe")
            # event.overall_group.append(user.name)
            # event.overall_className.append("maybe")
            # event.total_times += 3
            # event.put()

            # to get values from datastore into data
            for iterator in range(0, event.total_times):
                temp_start = event.overall_start[iterator]
                temp_end = event.overall_end[iterator]
                temp_content = event.overall_content[iterator]
                temp_group = event.overall_group[iterator]
                temp_className = event.overall_className[iterator]
                temp_event = [
                    temp_start, temp_end, temp_content, temp_group,
                    temp_className
                ]
                data.append(temp_event)

            # Loading it into gviz_api.DataTable
            data_table = gviz_api.DataTable(description)
            data_table.LoadData(data)
            # Creating a JSon string
            json = data_table.ToJSon(columns_order=("start", "end", "content",
                                                    "group", "className"),
                                     order_by="group")

            # for owntimetable
            data_own = []

            for iterator_own in range(0, user.total_events):
                user_start = user.all_start[iterator_own]
                user_end = user.all_end[iterator_own]
                user_content = user.all_content[iterator_own]
                user_group = user.all_group[iterator_own]
                user_className = user.all_className[iterator_own]
                user_event = [
                    user_start, user_end, user_content, user_group,
                    user_className
                ]
                data_own.append(user_event)

            # Loading it into gviz_api.DataTable
            data_table_own = gviz_api.DataTable(description)
            data_table_own.LoadData(data_own)

            # Creating a JSon string
            json_own = data_table_own.ToJSon(columns_order=("start", "end",
                                                            "content", "group",
                                                            "className"),
                                             order_by="group")

            template_values = {
                'json': json,
                'json_own': json_own,
                'total_votes': total_votes,
                'options': option_query,
                'user': user,
                'my_events': query,
                'event': event,
                'user_mail': user.email,
                'can_vote': can_vote,
                'posts': post_query,
                'best': best_option
                # 'logout' : users.create_logout_url(self.request.host_url)
            }
            template = jinja_environment.get_template('eventhome.html')
            self.response.out.write(template.render(template_values))
        else:
            self.redirect('/unauth')
예제 #14
0
 def get(self):
     posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC")
     self.render_blog(posts)
예제 #15
0
 def get(self):
     admin = users.is_current_user_admin()
     posts = db.GqlQuery(
         "select * from Post order by created desc limit 10")
     self.render('front.html', posts=posts, admin=admin)
예제 #16
0
 def post(self, topic_num):
     site = GetSite()
     browser = detect(self.request)
     template_values = {}
     template_values['site'] = site
     template_values['system_version'] = SYSTEM_VERSION
     member = CheckAuth(self)
     template_values['member'] = member
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     topic_num_str = str(topic_num)
     if len(topic_num_str) > 8:
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic_not_found.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic_not_found.html')
         output = template.render(path, template_values)
         self.response.out.write(output)
         return
     if (member):
         topic = False
         q = db.GqlQuery("SELECT * FROM Topic WHERE num = :1",
                         int(topic_num))
         if (q.count() == 1):
             topic = q[0]
             try:
                 topic.hits = topic.hits + 1
                 topic.put()
             except:
                 topic.hits = topic.hits - 1
         template_values['topic'] = topic
         errors = 0
         # Verification: content
         reply_content_error = 0
         reply_content_error_messages = [
             '', u'请输入回复内容', u'回复内容长度不能超过 2000 个字符'
         ]
         reply_content = self.request.get('content').strip()
         if (len(reply_content) == 0):
             errors = errors + 1
             reply_content_error = 1
         else:
             if (len(reply_content) > 2000):
                 errors = errors + 1
                 reply_content_error = 2
         template_values['reply_content'] = reply_content
         template_values['reply_content_error'] = reply_content_error
         template_values[
             'reply_content_error_message'] = reply_content_error_messages[
                 reply_content_error]
         template_values['errors'] = errors
         if (topic and (errors == 0)):
             reply = Reply(parent=topic)
             q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                             'reply.max')
             if (q.count() == 1):
                 counter = q[0]
                 counter.value = counter.value + 1
             else:
                 counter = Counter()
                 counter.name = 'reply.max'
                 counter.value = 1
             q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                              'reply.total')
             if (q2.count() == 1):
                 counter2 = q2[0]
                 counter2.value = counter2.value + 1
             else:
                 counter2 = Counter()
                 counter2.name = 'reply.total'
                 counter2.value = 1
             node = False
             section = False
             if topic:
                 q3 = db.GqlQuery("SELECT * FROM Node WHERE num = :1",
                                  topic.node_num)
                 node = q3[0]
                 q4 = db.GqlQuery("SELECT * FROM Section WHERE num = :1",
                                  node.section_num)
                 section = q4[0]
             reply.num = counter.value
             reply.content = reply_content
             reply.topic = topic
             reply.topic_num = topic.num
             reply.member = member
             reply.member_num = member.num
             reply.created_by = member.username
             topic.replies = topic.replies + 1
             topic.node_name = node.name
             topic.node_title = node.title
             topic.last_reply_by = member.username
             topic.last_touched = datetime.datetime.now()
             ua = self.request.headers['User-Agent']
             if (re.findall('Mozilla\/5.0 \(iPhone', ua)):
                 reply.source = 'iPhone'
             if (re.findall('Mozilla\/5.0 \(iPod', ua)):
                 reply.source = 'iPod'
             if (re.findall('Mozilla\/5.0 \(iPad', ua)):
                 reply.source = 'iPad'
             if (re.findall('Android', ua)):
                 reply.source = 'Android'
             if (re.findall('Mozilla\/5.0 \(PLAYSTATION 3;', ua)):
                 reply.source = 'PS3'
             reply.put()
             topic.put()
             counter.put()
             counter2.put()
             memcache.set('Topic_' + str(topic.num), topic, 86400)
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_rendered_mobile')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_rendered_mobile')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_rendered_mobile')
             memcache.delete('member::' + str(member.num) +
                             '::participated')
             memcache.delete('home_rendered')
             memcache.delete('home_rendered_mobile')
             taskqueue.add(url='/index/topic/' + str(topic.num))
             # Twitter Sync
             if member.twitter_oauth == 1 and member.twitter_sync == 1:
                 access_token = OAuthToken.from_string(
                     member.twitter_oauth_string)
                 twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                    access_token)
                 link = 'http://' + self.request.headers[
                     'Host'] + '/t/' + str(topic.num) + '#r' + str(
                         reply.num)
                 link_length = len(link)
                 reply_content_length = len(reply.content)
                 available = 140 - link_length - 1
                 if available > reply_content_length:
                     status = reply.content + ' ' + link
                 else:
                     status = reply.content[0:(available -
                                               4)] + '... ' + link
                 self.response.out.write('Status: ' + status)
                 logging.error('Status: ' + status)
                 try:
                     twitter.PostUpdate(status.encode('utf-8'))
                 except:
                     logging.error("Failed to sync to Twitter for Reply #" +
                                   str(reply.num))
             self.redirect('/t/' + str(topic.num) + '#reply' +
                           str(topic.replies))
         else:
             node = False
             section = False
             if topic:
                 q2 = db.GqlQuery("SELECT * FROM Node WHERE num = :1",
                                  topic.node_num)
                 node = q2[0]
                 q3 = db.GqlQuery("SELECT * FROM Section WHERE num = :1",
                                  node.section_num)
                 section = q3[0]
             template_values['node'] = node
             template_values['section'] = section
             if browser['ios']:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'mobile', 'topic.html')
             else:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'desktop', 'topic.html')
             output = template.render(path, template_values)
             self.response.out.write(output)
     else:
         self.redirect('/signin')
 def render_front(self, title="", art="", error=""):
     arts = db.GqlQuery("SELECT * from Art \
                         ORDER BY created DESC")
     self.render("front.html", title=title, art=art, error=error, arts=arts)
예제 #18
0
 def post(self, topic_num):
     site = GetSite()
     template_values = {}
     template_values['site'] = site
     browser = detect(self.request)
     template_values['system_version'] = SYSTEM_VERSION
     member = CheckAuth(self)
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     if (member):
         if (member.num == 1):
             template_values['member'] = member
             topic = False
             q = db.GqlQuery("SELECT * FROM Topic WHERE num = :1",
                             int(topic_num))
             if (q.count() == 1):
                 topic = q[0]
                 template_values['topic'] = topic
             if (topic):
                 q2 = db.GqlQuery("SELECT * FROM Node WHERE num = :1",
                                  topic.node_num)
                 node = False
                 if (q2.count() == 1):
                     node = q2[0]
                 template_values['node'] = node
                 section = False
                 if node:
                     q3 = db.GqlQuery(
                         "SELECT * FROM Section WHERE num = :1",
                         node.section_num)
                     if (q3.count() == 1):
                         section = q3[0]
                 template_values['section'] = section
                 errors = 0
                 # Verification: title
                 topic_title_error = 0
                 topic_title_error_messages = [
                     '', u'请输入主题标题', u'主题标题长度不能超过 120 个字符'
                 ]
                 topic_title = self.request.get('title').strip()
                 if (len(topic_title) == 0):
                     errors = errors + 1
                     topic_title_error = 1
                 else:
                     if (len(topic_title) > 120):
                         errors = errors + 1
                         topic_title_error = 2
                 template_values['topic_title'] = topic_title
                 template_values['topic_title_error'] = topic_title_error
                 template_values[
                     'topic_title_error_message'] = topic_title_error_messages[
                         topic_title_error]
                 # Verification: content
                 topic_content_error = 0
                 topic_content_error_messages = [
                     '', u'请输入主题内容', u'主题内容长度不能超过 5000 个字符'
                 ]
                 topic_content = self.request.get('content').strip()
                 if (len(topic_content) == 0):
                     errors = errors + 1
                     topic_content_error = 1
                 else:
                     if (len(topic_content) > 5000):
                         errors = errors + 1
                         topic_content_error = 2
                 template_values['topic_content'] = topic_content
                 template_values[
                     'topic_content_error'] = topic_content_error
                 template_values[
                     'topic_content_error_message'] = topic_content_error_messages[
                         topic_content_error]
                 template_values['errors'] = errors
                 if (errors == 0):
                     topic.title = topic_title
                     topic.content = topic_content
                     path = os.path.join(os.path.dirname(__file__), 'tpl',
                                         'portion', 'topic_content.html')
                     output = template.render(path, {'topic': topic})
                     topic.content_rendered = output.decode('utf-8')
                     topic.last_touched = datetime.datetime.now()
                     topic.put()
                     memcache.delete('Topic_' + str(topic.num))
                     self.redirect('/t/' + str(topic.num))
                 else:
                     if browser['ios']:
                         path = os.path.join(os.path.dirname(__file__),
                                             'tpl', 'mobile',
                                             'edit_topic.html')
                     else:
                         path = os.path.join(os.path.dirname(__file__),
                                             'tpl', 'desktop',
                                             'edit_topic.html')
                     output = template.render(path, template_values)
                     self.response.out.write(output)
             else:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'mobile', 'topic_not_found.html')
                 output = template.render(path, template_values)
                 self.response.out.write(output)
         else:
             self.redirect('/t/' + str(topic_num))
     else:
         self.redirect('/signin')
예제 #19
0
def fetch_events_facebook():
  query = 'SELECT * FROM Events WHERE facebook_event = True'
  query += ' ORDER BY timestamp ASC'
  events = db.GqlQuery(query)
  return _populate_events(events)
예제 #20
0
 def post(self, reply_num):
     template_values = {}
     site = GetSite()
     member = CheckAuth(self)
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     if member:
         if member.num == 1:
             template_values['page_title'] = site.title + u' › 编辑回复'
             template_values['member'] = member
             q = db.GqlQuery("SELECT * FROM Reply WHERE num = :1",
                             int(reply_num))
             if q[0]:
                 reply = q[0]
                 topic = reply.topic
                 node = topic.node
                 template_values['reply'] = reply
                 template_values['topic'] = topic
                 template_values['node'] = node
                 # Verification: content
                 errors = 0
                 reply_content_error = 0
                 reply_content_error_messages = [
                     '', u'请输入回复内容', u'回复内容长度不能超过 2000 个字符'
                 ]
                 reply_content = self.request.get('content').strip()
                 if (len(reply_content) == 0):
                     errors = errors + 1
                     reply_content_error = 1
                 else:
                     if (len(reply_content) > 2000):
                         errors = errors + 1
                         reply_content_error = 2
                 template_values['reply_content'] = reply_content
                 template_values[
                     'reply_content_error'] = reply_content_error
                 template_values[
                     'reply_content_error_message'] = reply_content_error_messages[
                         reply_content_error]
                 template_values['errors'] = errors
                 if (errors == 0):
                     reply.content = reply_content
                     reply.put()
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_desc_compressed')
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_asc_compressed')
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_filtered_compressed')
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_desc_rendered')
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_asc_rendered')
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_filtered_rendered')
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_desc_rendered_mobile')
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_asc_rendered_mobile')
                     memcache.delete('topic_' + str(topic.num) +
                                     '_replies_filtered_rendered_mobile')
                     self.redirect('/t/' + str(topic.num) + '#reply' +
                                   str(topic.replies))
                 else:
                     path = os.path.join(os.path.dirname(__file__), 'tpl',
                                         'desktop', 'edit_reply.html')
                     output = template.render(path, template_values)
                     self.response.out.write(output)
             else:
                 self.redirect('/')
         else:
             self.redirect('/')
     else:
         self.redirect('/signin')
예제 #21
0
def fillProfile(content):
    '''
        fillProfile

        Tratamento do perfil do usuário, primeiro preenchendo dados chave

        PLAN

            Traçar o perfil do usuário, bem como suas características e dados
            para fornecer apenas conteúdo de interesse do mesmo.
    '''
    c = Cliente()
    user = users.get_current_user()
    client = db.GqlQuery("SELECT * FROM Cliente WHERE user = :1", user)
    c = client[0]
    retorno = ""
    if c.nome is None:
        nome = re.findall("(?<=ou )[A-Z]\S+[^., ?]", content)
        if nome:
            c.nome = nome[0]
            r = nome[0]
            apelido = re.findall("[A-Z]\S{1}[aeioun]", nome[0])
            if apelido:
                c.apelido = apelido[0]
                r = apelido[0]
            retorno = retorno + r + ", gostei!! "
            c.put()
        else:
            retorno = "Entao " + c.nome
    elif c.idade is None:
        idade = re.findall("\d{2}|\d{4}", content)
        if idade and len(idade[0]) <= 2:
            idade = int(idade[0])
            c.idade = idade
            if idade == 18:
                retorno = retorno + "Ahh, já pode ir pra cadeia ein, cuidado!!"
            elif idade > 18:
                retorno = retorno + " Uia!!"
            else:
                retorno = retorno + "Nossa, joven ahn!"
        else:
            retorno = " Quantos anos você tem? "
        c.put()
    elif c.profissao is None and c.nome is not None:
        pro = re.findall("((?<=ou )|(?<=a.o ))\S+[^., ?]", content)
        if pro:
            pro = pro[0]
            c.profissao = pro
            retorno = retorno + " %s, hum, bela profiss&atildeo!" % pro
            c.put()
        else:
            retorno = retorno + " O que faz da vida?"
    else:
        #        retorno = "Desculpe, versão de testes finalizada"
        k = db.GqlQuery("select * from Knowledge where sender = :1", user)
        if k.count() > 0:
            k = k[0]
        else:
            k = Knowledge()
            k.sender = user
        k.frases.append(content)
        k.put()
        palavra = re.findall("\S+", content)
        retorno = "."
        #        retorno = respAritial(palavra[0])
        i = 0
        while i < (len(palavra) - 2):
            retorno = respAritial(palavra[i])
            i = i + 1
    return retorno.decode('utf8')
예제 #22
0
def get_posts(limit, offset):
    posts = db.GqlQuery("SELECT * FROM Blog "
                        "ORDER BY created DESC "
                        "LIMIT limit OFFSET offset")
    return posts
예제 #23
0
def get_stream(clientId):
    return db.GqlQuery('SELECT * FROM ClientStream WHERE clientId = :1', clientId).get()
예제 #24
0
    def get(self):
        url_queries = self.request.GET
        state = url_queries['state']
        code = url_queries['code']
        url = 'https://github.com/login/oauth/access_token?client_id=a454ac3fef0a7cde71df&client_secret=4029cf0da2c400aa755d818dcdda96be97fc94a4&redirect_uri=http://gitpromote.appspot.com/dev&code=' + str(
            code)
        req = requests.post(url)
        req = str(req.content)
        access_token = ""
        i = 13
        while (req[i] != '&'):
            access_token = access_token + req[i]
            i = i + 1

        user_api_url = 'https://api.github.com/user?access_token=' + str(
            access_token)
        user_json_data = requests.get(user_api_url)
        d = json.loads(user_json_data.content)
        user_login_id = d['login']
        q = db.GqlQuery("SELECT * FROM Userdata WHERE user_login_id= :w",
                        w=user_login_id).fetch(limit=2)
        #if len(q)>0:
        #    self.redirect('http://gitpromote.appspot.com')
        #    return
        if 'name' in d:
            fullname = d['name']
        else:
            fullname = ""

        self.session['user_login_id'] = user_login_id

        avatar_url = d['avatar_url']
        user_html_url = d['html_url']
        if 'blog' in d:
            website = d['blog']
        else:
            website = ""
        if 'email' in d:
            email = d['email']
        else:
            email = ""
        if 'location' in d:
            location = d['location']
        else:
            location = ""
        public_repos = d['public_repos']
        bio = ""
        followers = d['followers']
        following = d['following']
        repos_url = d['repos_url']
        followers_url = d['followers_url']
        following_url = d['following_url']
        created_at = d['created_at']
        updated_at = d['updated_at']

        lang = []
        res = requests.get(str(repos_url))
        repo_data = json.loads(res.content)
        for i in repo_data:
            if not i['fork'] and not i['private']:
                repo_name = i['name']
                repo_html_url = i['html_url']
                user_login_id = i['owner']['login']
                language = i['language']
                forks = i['forks']
                stars = i['stargazers_count']
                homepage = i['homepage']
                description = i['description']
                lang.append(language)
                if len(q) == 0:
                    repo_instance = Repodata(key_name=repo_name,
                                             repo_name=repo_name,
                                             user_login_id=user_login_id,
                                             forks=forks,
                                             repo_html_url=repo_html_url,
                                             stars=stars,
                                             language=language,
                                             homepage=str(homepage),
                                             description=description)
                    repo_instance.put()

                if len(q) > 0:
                    repo_instance = Repodata(key_name=repo_name,
                                             repo_name=repo_name,
                                             user_login_id=user_login_id,
                                             forks=forks,
                                             repo_html_url=repo_html_url,
                                             stars=stars,
                                             language=language,
                                             homepage=str(homepage),
                                             description=description)
                    repo_instance.put()

        lang_list = list(set(lang))
        if None in lang_list:
            lang_list.remove(None)

        if len(q) > 0:
            user_instance = Userdata(key_name=user_login_id,
                                     repos_url=repos_url,
                                     public_repos=public_repos,
                                     created_at=created_at,
                                     updated_at=updated_at,
                                     lang_tags=lang_list,
                                     fullname=fullname,
                                     user_login_id=user_login_id,
                                     avatar_url=avatar_url,
                                     user_html_url=user_html_url,
                                     website=website,
                                     email=email,
                                     location=location,
                                     following=following,
                                     followers=followers,
                                     following_url=following_url,
                                     followers_url=followers_url)
            user_instance.put()
            self.redirect('/user/' + str(user_login_id))

        if len(q) == 0:
            user_instance = Userdata(key_name=user_login_id,
                                     repos_url=repos_url,
                                     bio=bio,
                                     public_repos=public_repos,
                                     created_at=created_at,
                                     updated_at=updated_at,
                                     lang_tags=lang_list,
                                     fullname=fullname,
                                     user_login_id=user_login_id,
                                     avatar_url=avatar_url,
                                     user_html_url=user_html_url,
                                     website=website,
                                     email=email,
                                     location=location,
                                     following=following,
                                     followers=followers,
                                     following_url=following_url,
                                     followers_url=followers_url)
            user_instance.put()
            self.redirect('/details')
예제 #25
0
def get_streams_of_owner(owner):
    return db.GqlQuery('SELECT * FROM ClientStream WHERE owner = :1 AND is_owner = :2', owner, True)
예제 #26
0
 def render_blogs(self, title="", art=""):
     arts = db.GqlQuery("SELECT * FROM Art "
                        "ORDER BY created DESC LIMIT 5 ")
     self.render("blogs.html", title=title, art=art, arts=arts)
예제 #27
0
def get_streams_of_owner_by_visitor(owner, visitor):
    return db.GqlQuery('SELECT * FROM ClientStream WHERE owner = :1 AND visitor = :2 AND is_owner = :3', owner, visitor, False)
예제 #28
0
 def render_blog(self):
     posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 5")
     self.render("blog.html", posts=posts)
예제 #29
0
def get_messages_of_owner(owner):
    return db.GqlQuery('SELECT * FROM OfflineMessage WHERE receiver = :1 ORDER BY created_on', owner)
예제 #30
0
 def get(self):
     posts = db.GqlQuery("SELECT * FROM BlogPost " "ORDER BY created DESC")
     self.render("blog.html", posts=posts)