示例#1
0
class KeywordModel(db.Model):
	keyword = db.StringProperty()
	status = db.StringProperty()
	text = db.StringProperty()
	url = db.URLProperty()
	imgURL = db.URLProperty()
	one = db.StringProperty()
	two = db.StringProperty()
	three = db.StringProperty()
示例#2
0
class TVideo(db.Model):
    wimp_url = db.URLProperty()
    video_url = db.URLProperty()

    title = db.TextProperty(required=False)
    description = db.TextProperty(required=False)

    def __init__(self,
                 parent=None,
                 key_name=None,
                 _app=None,
                 _from_entity=False,
                 **kwds):
        super(TVideo, self).__init__(parent,
                                     key_name,
                                     _app,
                                     _from_entity,
                                     kwds=kwds)
        if self.wimp_url:
            self.scrape_wimp()

    def scrape_wimp(self):
        conn = urllib2.urlopen(self.wimp_url)
        page = conn.readlines()

        title_re = re.compile("<b>(.*)</b>")
        look_here_for_description = False

        for line in page:
            if re.search(title_re, line):
                self.title = re.split(title_re, line)[1]
            elif line.find('flv') != -1:
                self.video_url = 'http://www.wimp.com' + re.split(
                    '.*","(.*)"\);', line)[1]

            if self.title and not self.description:  # desc is after title
                if look_here_for_description:
                    self.description = re.split('\s*(.*)</div>', line)[1]
                    look_here_for_description = False
                elif line.startswith('<br/>'):
                    look_here_for_description = True

    def __str__(self):
        if self.is_saved():
            id = str(self.key())
        else:
            id = 'UNSAVED'
        wimp_url = self.wimp_url or ''
        video_url = self.video_url or ''
        title = self.title or ''
        description = self.description or ''
        return "Video:\n    id: %s\n    wimp_url: %s\n    video_url: %s\n    title: %s\n    description: %s\n    " % (
            wimp_url, id, video_url, title, description)
示例#3
0
class Video(db.Model):
  wimp_url = db.URLProperty()
  video_url = db.URLProperty()
  
  title = db.TextProperty(required=False)
  description = db.TextProperty(required=False)
  
  @classmethod
  def get_or_create(Klass, wimp_url, save=True):
    """
    The Right Way to add a video. Uses the given url (of the form
    http://www.wimp.com/somevideo/) as the key, and then scrapes the
    wimp page for more info.
    """
    vid = Klass.get_or_insert(wimp_url)
    vid.wimp_url = wimp_url
    vid.scrape_wimp()
    if save:
      vid.save()
    return vid  
  
  def scrape_wimp(self):
    conn = urllib2.urlopen(self.wimp_url)
    page = conn.readlines()
    
    title_re = re.compile("<b>(.*)</b>")
    look_here_for_description = False

    for line in page:
      if re.search(title_re, line):
        self.title = re.split(title_re, line)[1]
      elif line.find('flv') != -1:
        self.video_url = 'http://www.wimp.com' + re.split('.*","(.*)"\);', line)[1]
      
      if self.title and not self.description: # desc is after title
        if look_here_for_description:
          self.description = re.split('\s*(.*)</div>', line)[1]
          look_here_for_description = False
        elif line.startswith('<br/>'):
            look_here_for_description = True

  def __str__(self):
    if self.is_saved():
      id = str(self.key())
    else:
      id = 'UNSAVED'
    wimp_url = self.wimp_url or ''
    video_url = self.video_url or ''
    title = self.title or ''
    description = self.description or ''
    return "Video:\n    id: %s\n    wimp_url: %s\n    video_url: %s\n    title: %s\n    description: %s\n    " % (id, wimp_url, video_url, title, description)
示例#4
0
class TwitterUser(SocialUser):
    """USER FROM TWITTER"""
    user = db.ReferenceProperty(User)
    username = db.TextProperty()
    picurl = db.URLProperty(indexed=False)
    objects = TwitterUserHelper()
    
    def is_twitter(self):
        return True
    
    def has_perms(self, uid):
        from geoauth.models import OAUTH_Access
        if OAUTH_Access.get_token_user('twitter', self.user) is None:
            return False
        return True
        
    @classmethod
    def register(cls, user, uid, username, realname, picurl):
        def _tx():
            key_name = 'tu%s' % uid
            utwitter = TwitterUser(key_name=key_name, user=user, uid=str(uid), username=username, realname=realname, picurl=picurl)
            utwitter.put()
            return utwitter
        utwitter = db.run_in_transaction(_tx)
        from signals import user_social_new
        user_social_new.send(sender=utwitter)
        return utwitter         
    
    def update(self, username, realname, picurl):
        self.username = username
        self.realname= realname
        self.picurl = picurl
        self.put()
示例#5
0
class OAUTH_Client(model_plus.Model):
    """Applications using our data"""
    # oauth_key is the Model's key_name field
    client_secret = db.TextProperty()
    client_verifier = db.TextProperty()
    user = db.ReferenceProperty(User)
    name = db.TextProperty()
    description = db.TextProperty()
    image = db.IMProperty()
    callback = db.URLProperty(required=False)
    created = db.DateTimeProperty(auto_now_add=True)

    @classmethod
    def generate(cls, *args, **kwargs):
        def _generate_key():
            #genera una cadena de numeros aleatoria, se codifica a base64 y se limpia para URLs
            u = uuid4()
            return base64.urlsafe_b64encode(
                u.bytes.encode("base64")).strip('=')

        kwargs['key_name'] = 'oclient_%s' % _generate_key()
        kwargs['client_secret'] = _generate_key()
        client = OAUTH_Client(*args, **kwargs)
        client.put()
        return client

    @classmethod
    def get_token(cls, key_name):
        return OAUTH_Client.get_by_key_name('oclient_%s' % key_name)

    @property
    def client_key(self):
        return self.key().name().split('oclient_')[:-1]
示例#6
0
class UserProfile(model_plus.Model):
    """Datos para el perfil del usuario"""
    username = db.TextProperty()
    avatar = db.URLProperty(required=False)
    sync_avatar_with = db.StringProperty(required=True,
                                         choices=AVATAR_CHOICES,
                                         default='gravatar')
    description = db.TextProperty(required=False)
    created = db.DateTimeProperty(auto_now_add=True)

    _sociallinks = None

    @classproperty
    def objects(self):
        return UserProfileHelper()

    @property
    def sociallinks(self):
        if self._sociallinks is None:
            self._sociallinks = UserSocialLinks.all().ancestor(
                self.key()).get()
        return self._sociallinks

    def sociallinks_async(self):
        q = UserSocialLinks.all().ancestor(self.key())
        return q.run()

    def _post_put(self, **kwargs):
        import memcache
        memcache.delete('%s%s_avatarcachebase64' %
                        (memcache.version, self.username))
        memcache.set('%s%s' % (memcache.version, self.key().name()),
                     memcache.serialize_instances(self), 300)
示例#7
0
文件: models.py 项目: javoeria/gae-py
class Image(db.Model):

    comic = db.ReferenceProperty(Comic, collection_name='images_set')
    user = db.UserProperty(auto_current_user=True)
    link = db.URLProperty(required=True)
    text = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
示例#8
0
文件: models.py 项目: javoeria/gae-py
class Comic(db.Model):

    author = db.UserProperty(auto_current_user=True)
    name = db.StringProperty(required=True)
    description = db.StringProperty(required=True, multiline=True)
    cover = db.URLProperty(required=True)
    create_date = db.DateTimeProperty(auto_now_add=True)
    update_date = db.DateTimeProperty(auto_now_add=True)
示例#9
0
class Ligo(db.Model):
    link = db.URLProperty()
    ligo = db.StringProperty()
    date = db.DateTimeProperty(auto_now=True)
    hit = db.IntegerProperty(default=0)

    def __unicode__(self):
        return 'ligo: %s, link: %s' % (self.ligo, self.link)
class Gift(db.Model):
  name = db.StringProperty(required=True)
  giver = db.UserProperty()
  recipient = db.StringProperty(required=True)

  description = db.TextProperty()
  url = db.URLProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)
示例#11
0
class Track(db.Model):
    author = db.StringProperty()
    lyric = db.TextProperty()
    number = db.IntegerProperty()
    ref = db.URLProperty()
    title = db.StringProperty()
    vol = db.IntegerProperty()
    created = db.DateTimeProperty()
    updated = db.DateTimeProperty()
示例#12
0
class TweetEntity(db.Model):
    '''
    ★DBに保存する情報
    ・URL
    ・ページ名 (URLよりHTTPヘッダ情報を取得)
    ・Tweet本文
    ・時刻
    ・星(評価)
    ・ユーザ名
    '''
    tweetId = db.IntegerProperty(required=True)
    url = db.URLProperty()
    pageTitle = db.StringProperty()
    tweetText = db.StringProperty()
    tweetAt = db.DateTimeProperty()
    star = db.IntegerProperty()
    account = db.StringProperty()
    account_image = db.URLProperty()
示例#13
0
class Comment(db.Model):
    post = db.ReferenceProperty(required=True)
    name = db.StringProperty(required=True)
    email = db.EmailProperty(required=False)
    url = db.URLProperty(required=False)
    body = db.StringProperty(required=True, multiline=True)
    ip_address = db.StringProperty(required=True)
    posted_date = db.DateTimeProperty(required=True, auto_now_add=True)
    moderated = db.BooleanProperty(required=True, default=False)
    validated = db.BooleanProperty(required=True, default=False)
示例#14
0
class RSSSource(db.Model):
    """Describes a RSS Feed Source.

  Properties:
    name: Name of a RSS feed source.
    url: url of a RSS feed source.
  """
    name = db.StringProperty()
    url = db.URLProperty()

    @classmethod
    def GetAllSources(cls):
        """Returns a query object of all RSS feed sources."""
        return cls.all().order('name')

    @classmethod
    def GetSourceByName(cls, name):
        """Returns a RSS Feed source.

    Args:
      name: Name of RSS source.

    Returns:
      A RSS source or None.
    """
        return cls.all().filter('name =', name).get()

    @classmethod
    def AddSource(cls, source_json):
        """Adds a RSS source.

    Args:
      source_json: A Json containing RSS source data.

    Returns:
      Key of saved RSS source.
    """
        rss_source = RSSSource()
        rss_source.name = source_json.get('name')
        rss_source.url = source_json.get('url')
        return rss_source.put()

    def UpdateSource(self, source_json):
        """Updates a RSS source.

    Args:
      source_json: A Json containing RSS source data.

    Returns:
      Key of an updated RSS source.
    """
        self.name = source_json.get('name')
        self.url = source_json.get('url')
        return self.put()
class Message(db.Model):
    message_type = db.IntegerProperty(required=True)
    # 1 won pyramid
    # 2 expiring

    recipient = db.ReferenceProperty(reference_class=Character,
                                     collection_name="recipient_set",
                                     required=True)
    sender = db.ReferenceProperty(reference_class=Character,
                                  collection_name="sender_set",
                                  default=None)  # None = game message
    title = db.StringProperty  # optional title for message box
    body = db.StringProperty(required=True)
    link = db.URLProperty()
    image = db.URLProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    is_deleted = db.BooleanProperty(default=False)
    read_by_user = db.BooleanProperty(default=False)
    pop_message_box = db.BooleanProperty(
        default=False
    )  # if True, a message box will be popped up the next time the user joins the game
示例#16
0
class SearchResult(db.Model):
    url = db.URLProperty(required = False)
    title = db.StringProperty(required = False)
    searchTerm = db.StringProperty(required = False)
    date = db.DateTimeProperty(auto_now_add=True)
    type = db.StringProperty(required=True)
    site = db.ReferenceProperty(Site)
    
    def toJSON(self):
        return dumps(self.toDict())
    
    def toDict(self):
        return {'title':self.title,'id':str(self.key())}
class Item(BaseModel):
    """Represents a type of thing that may in the inventory."""
    bar_code_number = db.IntegerProperty()
    bar_code_number.unique = True
    name = db.StringProperty(required=True)
    name.unique = True
    appears_on_order_form = db.ReferenceProperty(OrderSheet)
    order_form_section = db.StringProperty()
    description = db.StringProperty()
    # 'Each' 'Box' 'Pair' etc
    measure = db.StringProperty(choices=('Each', 'Roll', 'Bottle', 'Box',
                                         'Pair', 'Board', 'Bundle', 'Bag',
                                         'Ton', 'Yard', 'Sheet', 'Cartridge',
                                         'Tube', 'Tub', 'Sq. Yds.', 'Gallon',
                                         'Section', 'Home', 'Box', 'Drop-off',
                                         '', 'Other'))
    # Dollars.
    unit_cost = db.FloatProperty()
    must_be_returned = db.StringProperty(choices=['Yes', 'No'], default='No')
    picture = db.BlobProperty()
    thumbnail = db.BlobProperty()
    supplier = db.ReferenceProperty(Supplier)
    supplier_part_number = db.StringProperty()
    url = db.URLProperty()
    last_editor = db.UserProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)
    supports_extra_name_on_order = db.BooleanProperty(default=False)

    def __unicode__(self):
        return self.description

    def VisibleSortableLabel(self, label):
        """Strips numeric prefixes used for sorting.

    Labels may have a digit prefix which is used for sorting, but
    should not be shown to users.
    """
        if not label:
            return ''
        parts = label.split()
        if len(parts) > 0 and parts[0].isdigit():
            return ' '.join(parts[1:])
        return label

    def VisibleName(self):
        return self.VisibleSortableLabel(self.name)

    def VisibleOrderFormSection(self):
        return self.VisibleSortableLabel(self.order_form_section)
示例#18
0
class Diputado(db.Model):
    nombre = db.StringProperty()
    distrito = db.IntegerProperty(default=0)
    nu_diputado = db.IntegerProperty(default=0)
    fraccion = db.ReferenceProperty(Fraccion,collection_name="fraccion")
    cabecera =  db.StringProperty()
    tipo_de_eleccion = db.StringProperty()
    entidad = db.ReferenceProperty(Entidad,collection_name="entidad")
    curul = db.StringProperty()
    suplente = db.StringProperty()
    email = db.EmailProperty()
    onomastico = db.StringProperty()
    foto = db.URLProperty()
    def __unicode__(self):
        return self.nombre
示例#19
0
文件: user.py 项目: morlov/rankit-dev
class User(Entity):

    name = db.StringProperty(required=True)
    password = db.StringProperty(required=True)
    email = db.StringProperty(required=True)
    avatar_url = db.URLProperty()
    registered = db.DateTimeProperty(auto_now_add=True)

    @staticmethod
    def get_by_email(email):
        return User.all().filter("email =", email).get()

    @staticmethod
    def get_by_name(name):
        return User.all().filter("name =", name).get()
示例#20
0
class SRVOPMPRocess(db.Model):
    # OPM ELement
    id = db.StringProperty()
    description = db.StringProperty()
    # OPM Entity
    name = db.StringProperty()
    # OPM Thing
    essence = db.StringProperty()
    affiliation = db.StringProperty()
    scope = db.StringProperty()
    url = db.URLProperty()
    # OPM Process
    classType = db.StringProperty()
    minActivationTime = db.IntegerProperty()
    maxActivationTime = db.IntegerProperty()
    inLinks = db.StringListProperty()  # List Keys
    outLinks = db.StringListProperty()  # List Keys
示例#21
0
class SRVOPMObject(db.Model):
    # OPM ELement
    id = db.StringProperty()
    description = db.StringProperty()
    # OPM Entity
    name = db.StringProperty()
    # OPM Thing
    essence = db.StringProperty()
    affiliation = db.StringProperty()
    scope = db.StringProperty()
    url = db.URLProperty()
    # OPM Object
    classType = db.StringProperty()
    type = db.StringProperty()
    inLinks = db.StringListProperty()  # List Keys
    outLinks = db.StringListProperty()  # List Keys
    initValue = db.StringProperty()
    states = db.StringListProperty()  # List Keys
示例#22
0
class OAUTH_Token(model_plus.Model):
    """Save the token used by another applications trying to get the authorization for a user"""
    #token_key is the Model's key_name field
    token_secret = db.TextProperty()
    token_callback = db.URLProperty(required=False)
    token_verifier = db.TextProperty(required=False)
    access = db.BooleanProperty(default=False)  # True if token is access token
    oauth_user = db.ReferenceProperty(User, required=False)
    oauth_consumer = db.ReferenceProperty(
        OAUTH_Client)  # the application requesting access
    created = db.DateTimeProperty(auto_now_add=True)

    @property
    def token_key(self):
        return self.key().name().split('otoken_')[:-1]

    @classmethod
    def generate(cls, *args, **kwargs):
        def _generate_key():
            #genera una cadena de numeros aleatoria, se codifica a base64 y se limpia para URLs
            u = uuid4()
            return base64.urlsafe_b64encode(
                u.bytes.encode("base64")).strip('=')

        kwargs['key_name'] = 'otoken_%s' % _generate_key()
        kwargs['token_secret'] = _generate_key()
        token = OAUTH_Token(*args, **kwargs)
        token.put()
        return token

    def authorize_token(self, user):
        if self.access or self.token_verifier is not None:
            raise OAUTHException('Invalid token')
        self.oauth_user = user
        self.token_verifier = base64.urlsafe_b64encode(
            uuid4().bytes.encode("base64")).strip('=')
        self.put()

    @classmethod
    def get_token(cls, key_name):
        return OAUTH_Token.get_by_key_name('otoken_%s' % key_name)
示例#23
0
class BlogPost(db.Model):
    author = db.ReferenceProperty(Author)
    tags = db.StringListProperty()
    title = db.StringProperty()
    content = db.TextProperty()
    signature = db.StringProperty()
    url = db.URLProperty()

    @classmethod
    def blog_post_from_feed_entry(cls, entry):
        import pprint
        pprint.pprint(entry)
        author = Author.get_or_insert(key_name=entry["source"]["link"],
                                      title=entry["source"]["title"],
                                      name=entry["author"])

        return cls(author=author,
                   tags=[t["term"] for t in entry.get("tags", [])],
                   title=entry["title"],
                   content=entry["content"][0]["value"],
                   signature=Signatures.signature_key_for_post(entry),
                   url=entry["link"])
示例#24
0
class FacebookUser(SocialUser):
    """USERS FROM FACEBOOK"""
    user = db.ReferenceProperty(User)
    profile_url = db.URLProperty(indexed=False)
    access_token = db.TextProperty()
    objects = FacebookUserHelper()
    
    def is_facebook(self):
        return True

    def has_perms(self):
        from geoauth.models import OAUTH_Access
        if OAUTH_Access.get_token_user('facebook', self.user) is None:
            return False
        return True
        
    @classmethod
    def register(cls, user, uid, email, realname, profile_url, access_token):
        def _tx():
            key_name = 'fu%s' % uid
            ufacebook = FacebookUser(key_name=key_name, user=user, 
                                   uid=str(uid), email=email, 
                                   realname=realname, profile_url=profile_url, 
                                   access_token=access_token)
            ufacebook.put()
            return ufacebook
        ufacebook = db.run_in_transaction(_tx)
        from signals import user_social_new
        user_social_new.send(sender=ufacebook)
        return ufacebook
    
    def update(self, realname, profile_url, uid=None):
        if uid is not None:
            self.uid = uid
        self.realname= realname
        self.profile_url = profile_url
        self.put()
示例#25
0
class Portfolio(db.Model):
    title = db.StringProperty(required=True)
    description = db.TextProperty(required=True)
    url = db.URLProperty()
    screen_shot = db.BlobProperty()
示例#26
0
class StudentProject(soc.models.linkable.Linkable):
    """Model for a student project used in the GSoC workflow.
  """

    #: Required field indicating the "title" of the project
    title = db.StringProperty(required=True, verbose_name=ugettext('Title'))
    title.help_text = ugettext('Title of the project')

    #: Required, text field describing the project
    abstract = db.TextProperty(required=True)
    abstract.help_text = ugettext(
        'Short abstract, summary, or snippet;'
        ' 500 characters or less, plain text displayed publicly')

    #: Optional, text field containing all kinds of information about this project
    public_info = db.TextProperty(required=False, default='')
    public_info.help_text = ugettext(
        'Additional information about this project to be shown publicly')

    #: Optional, URL which can give more information about this project
    additional_info = db.URLProperty(required=False)
    additional_info.help_text = ugettext(
        'Link to a resource containing more information about this project.')

    #: Optional field storing a feed URL; displayed publicly
    feed_url = db.LinkProperty(verbose_name=ugettext('Project Feed URL'))
    feed_url.help_text = ugettext(
        'The URL should be a valid ATOM or RSS feed. '
        'Feed entries are shown on the public page.')

    #: A property containing which mentor has been assigned to this project.
    #: A project must have a mentor at all times.
    mentor = db.ReferenceProperty(reference_class=soc.models.mentor.Mentor,
                                  required=True,
                                  collection_name='student_projects')

    #: A property containing a list of additional Mentors for this project
    additional_mentors = db.ListProperty(item_type=db.Key, default=[])

    #: The status of this project
    #: accepted: This project has been accepted into the program
    #: failed: This project has failed an evaluation.
    #: completed: This project has completed the program successfully. This
    #:            should be set automatically when a program has been deemed
    #:            finished.
    #: withdrawn: This project has been withdrawn from the program by a Program
    #:            Administrator or higher.
    #: invalid: This project has been marked as invalid because it was deleted
    status = db.StringProperty(
        required=True,
        default='accepted',
        choices=['accepted', 'failed', 'completed', 'withdrawn', 'invalid'])

    #: List of all processed GradingRecords which state a pass for this project.
    #: This property can be used to determine how many evaluations someone has
    #: passed. And is also used to ensure that a GradingRecord has been
    #: processed.
    passed_evaluations = db.ListProperty(item_type=db.Key, default=[])

    #: List of all processed GradingRecords which state a fail for this project.
    #: This is a ListProperty to ensure that the system keeps functioning when
    #: manual changes in GradingRecords occur.
    failed_evaluations = db.ListProperty(item_type=db.Key, default=[])

    #: Student which this project is from
    student = db.ReferenceProperty(reference_class=soc.models.student.Student,
                                   required=True,
                                   collection_name='student_projects')

    #: Program in which this project has been created
    program = db.ReferenceProperty(reference_class=soc.models.program.Program,
                                   required=True,
                                   collection_name='student_projects')
示例#27
0
class Feed(db.Model):
  site_name = db.StringProperty()
  link = db.URLProperty()
  title = db.StringProperty()
  updated_parsed = db.DateTimeProperty()
示例#28
0
class GSoCProject(db.Model):
    """Model for a GSoC project used in the GSoC workflow.

  Parent:
    soc.modules.gsoc.models.profile.Profile
  """

    #: Required field indicating the "title" of the project
    title = db.StringProperty(required=True, verbose_name=ugettext('Title'))
    title.help_text = ugettext('Title of the project')

    #: Required, text field describing the project
    abstract = db.TextProperty(required=True,
                               verbose_name=ugettext('Project abstract'))
    abstract.help_text = ugettext(
        'Short abstract, summary, or snippet;'
        ' 500 characters or less, plain text displayed publicly')

    #: Text field containing all kinds of information about this project
    public_info = db.TextProperty(
        required=False,
        default='',
        verbose_name=ugettext('Additional information'))
    public_info.help_text = ugettext(
        'Additional information about this project to be shown publicly')

    #: Optional, URL which can give more information about this project
    additional_info = db.URLProperty(
        required=False, verbose_name=ugettext('External resource URL'))
    additional_info.help_text = ugettext(
        'Link to a resource containing more information about this project.')

    #: Optional field storing a feed URL; displayed publicly
    feed_url = db.LinkProperty(verbose_name=ugettext('Project Feed URL'))
    feed_url.help_text = ugettext(
        'The URL should be a valid ATOM or RSS feed. '
        'Feed entries are shown on the public page.')

    #: The project can be marked to be featured on program home page.
    is_featured = db.BooleanProperty(default=False,
                                     required=True,
                                     verbose_name=ugettext('Featured'))
    is_featured.help_text = ugettext(
        'Should this project be featured on the program homepage.')

    #: A property containing a list of Mentors assigned for this project
    mentors = db.ListProperty(item_type=db.Key, default=[], required=True)

    def getMentors(self):
        """Returns a list of profile_model.GSoCProfile entities which
    are mentors for this project.

    Returns:
      list of mentors for this project
    """
        mentor_ndb_keys = map(ndb.Key.from_old_key, self.mentors)
        return [mentor for mentor in ndb.get_multi(mentor_ndb_keys) if mentor]

    #: The status of this project
    status = db.StringProperty(required=True,
                               default=STATUS_ACCEPTED,
                               choices=[
                                   STATUS_ACCEPTED, STATUS_FAILED,
                                   STATUS_WITHDRAWN, STATUS_INVALID
                               ])

    #: List of all processed GradingRecords which state a pass for this project.
    #: This property can be used to determine how many evaluations someone has
    #: passed. And is also used to ensure that a GradingRecord has been
    #: processed.
    passed_evaluations = db.ListProperty(item_type=db.Key, default=[])

    #: List of all processed GradingRecords which state a fail for this project.
    #: This is a ListProperty to ensure that the system keeps functioning when
    #: manual changes in GradingRecords occur.
    failed_evaluations = db.ListProperty(item_type=db.Key, default=[])

    #: Organization which this project is in
    org = db.ReferenceProperty(
        reference_class=soc.models.organization.Organization,
        required=True,
        collection_name='student_projects')

    #: Program in which this project has been created
    program = db.ReferenceProperty(reference_class=soc.models.program.Program,
                                   required=True,
                                   collection_name='projects')

    #: Proposal to which this project corresponds to
    proposal = db.ReferenceProperty(
        reference_class=soc.modules.gsoc.models.proposal.GSoCProposal,
        required=False,
        collection_name='projects')

    #: Whether the student has submitted their code samples or not
    code_samples_submitted = db.BooleanProperty(default=False)

    def codeSamples(self):
        """Returns code_sample.GSoCCodeSample entities uploaded for this project.

    Returns:
      code sample entities for this project
    """
        query = code_sample_model.GSoCCodeSample.all()
        query.ancestor(self)
        return query.fetch(1000)

    def countCodeSamples(self):
        """Returns number of code_sample.GSoCCodeSample entities uploaded
    for this project.

    Returns:
      number of code samples uploaded for this project
    """
        query = code_sample_model.GSoCCodeSample.all(keys_only=True)
        query.ancestor(self)
        return query.count()
示例#29
0
文件: model.py 项目: cnripple/micolog
class Comment(db.Model):
    entry = db.ReferenceProperty(Entry)
    date = db.DateTimeProperty(auto_now_add=True)
    content = db.TextProperty(required=True)
    author = db.StringProperty()
    email = db.EmailProperty()
    weburl = db.URLProperty()
    status = db.IntegerProperty(default=0)
    reply_notify_mail = db.BooleanProperty(default=False)
    ip = db.StringProperty()
    ctype = db.IntegerProperty(default=COMMENT_NORMAL)
    no = db.IntegerProperty(default=0)
    comment_order = db.IntegerProperty(default=1)

    @property
    def mpindex(self):
        count = self.entry.commentcount
        no = self.no
        if g_blog.comments_order:
            no = count - no + 1
        index = no / g_blog.comments_per_page
        if no % g_blog.comments_per_page or no == 0:
            index += 1
        return index

    @property
    def shortcontent(self, len=20):
        scontent = self.content
        scontent = re.sub(r'<br\s*/>', ' ', scontent)
        scontent = re.sub(r'<[^>]+>', '', scontent)
        scontent = re.sub(r'(@[\S]+)-\d{2,7}', r'\1:', scontent)
        return scontent[:len].replace('<', '&lt;').replace('>', '&gt;')

    def gravatar_url(self):

        # Set your variables here
        if g_blog.avatar_style == 0:
            default = g_blog.baseurl + '/static/images/homsar.jpeg'
        else:
            default = 'identicon'

        if not self.email:
            return default

        size = 50

        try:
            # construct the url
            imgurl = "http://www.gravatar.com/avatar/"
            imgurl += hashlib.md5(
                self.email.lower()).hexdigest() + "?" + urllib.urlencode(
                    {
                        'd': default,
                        's': str(size),
                        'r': 'G'
                    })

            return imgurl
        except:
            return default

    def save(self):

        self.put()
        self.comment_order = self.entry.commentcount
        self.entry.commentcount += 1
        if (self.ctype == COMMENT_TRACKBACK) or (self.ctype
                                                 == COMMENT_PINGBACK):
            self.entry.trackbackcount += 1
        self.entry.put()
        memcache.delete("/" + self.entry.link)
        return True

    def delit(self):
        self.entry.commentcount -= 1
        if self.entry.commentcount < 0:
            self.entry.commentcount = 0
        if (self.ctype == COMMENT_TRACKBACK) or (self.ctype
                                                 == COMMENT_PINGBACK):
            self.entry.trackbackcount -= 1
        if self.entry.trackbackcount < 0:
            self.entry.trackbackcount = 0
        self.entry.put()
        self.delete()

    def put(self):
        g_blog.tigger_action("pre_comment", self)
        db.Model.put(self)
        g_blog.tigger_action("save_comment", self)

    def delete(self):
        db.Model.delete(self)
        g_blog.tigger_action("delete_comment", self)

    @property
    def children(self):
        key = self.key()
        comments = Comment.all().ancestor(self)
        return [c for c in comments if c.parent_key() == key]

    def store(self, **kwargs):
        rpc = datastore.GetRpcFromKwargs(kwargs)
        self._populate_internal_entity()
        return datastore.Put(self._entity, rpc=rpc)
示例#30
0
class StudentProposal(soc.models.linkable.Linkable):
    """Model for a student proposal used in the GSoC workflow.
  """

    #: Required field indicating the "title" of the proposal
    title = db.StringProperty(required=True,
                              verbose_name=ugettext('Project Title'))
    title.help_text = ugettext('Title of the proposal')

    #: required, text field used for different purposes,
    #: depending on the specific type of the proposal
    abstract = db.TextProperty(required=True,
                               verbose_name=ugettext('Short Description'))
    abstract.help_text = ugettext(
        'Short abstract, summary, or snippet;'
        ' 500 characters or less, plain text displayed publicly')

    #: Required field containing the content of the proposal.
    content = db.TextProperty(required=True, verbose_name=ugettext('Content'))
    content.help_text = ugettext('This contains your actual proposal')

    #: an URL linking to more information about this students proposal
    additional_info = db.URLProperty(required=False,
                                     verbose_name=ugettext('Additional Info'))
    additional_info.help_text = ugettext(
        'Link to a resource containing more information about your proposal')

    #: indicates whether the proposal's content may be publicly seen or not
    is_publicly_visible = db.BooleanProperty(
        required=False, default=False, verbose_name=ugettext('Make public'))
    is_publicly_visible.help_text = ugettext(
        'If you check here, the content of your proposal will be visible '
        'for others. Please note that they still will not be able to see '
        'any public comments and reviews of the proposal.')

    #: A property containing which mentor has assigned himself to this proposal.
    #: Only a proposal with an assigned mentor can be turned into
    #: a accepted proposal. A proposal can only have one mentor.
    mentor = db.ReferenceProperty(reference_class=soc.models.role.Role,
                                  required=False,
                                  collection_name='student_proposals')

    #: A property containing a list of possible Mentors for this proposal
    possible_mentors = db.ListProperty(item_type=db.Key, default=[])

    #: the current score of this proposal, used to determine which proposals
    #: should be assigned a project slot.
    score = db.IntegerProperty(required=True, default=0)

    #: the status of this proposal
    #: new : the proposal has not been ranked/scored yet
    #: pending: the proposal is in the process of being ranked/scored
    #: accepted: the proposal has been assigned a project slot
    #: rejected: the proposal has not been assigned a slot
    #: invalid: the student or org admin marked this as an invalid proposal.
    status = db.StringProperty(
        required=True,
        default='new',
        choices=['new', 'pending', 'accepted', 'rejected', 'invalid'])

    #: organization to which this proposal is directed
    org = db.ReferenceProperty(
        reference_class=soc.models.organization.Organization,
        required=True,
        collection_name='student_proposals')

    #: program in which this proposal has been created
    program = db.ReferenceProperty(reference_class=soc.models.program.Program,
                                   required=True,
                                   collection_name='student_proposals')

    #: date when the proposal was created
    created_on = db.DateTimeProperty(required=True, auto_now_add=True)

    #: date when the proposal was last modified, should be set manually on edit
    last_modified_on = db.DateTimeProperty(required=True, auto_now_add=True)