示例#1
0
def update_reviewers(change, old_review_status, new_users):
    """Update the reviewers for a change

  ****
  Should be called in a transaction.  You need to call put()
  for each of the ReviewStatus objects in added_review_status and
  delete() for each of the ReviewStatus objects in deleted_review_status.
  ****

  Returns:
    A tuple of ReviewStatus objects of:
      0 - the new ones that were added
      1 - the ones that were deleted
      2 - the new set of review status objects
  """
    new_review_status = []
    added_review_status = []
    deleted_review_status = []
    for u in new_users:
        rs = _find_review_status_for_user(old_review_status, u)
        if not rs:
            rs = models.ReviewStatus.insert_status(change, u)
            rs.lgtm = 'abstain'
            rs.verified = False
            added_review_status.append(rs)
        new_review_status.append(rs)
    for rs in old_review_status:
        if rs not in new_review_status:
            deleted_review_status.append(rs)
    change.set_reviewers(
        [db.Email(rs.user.email()) for rs in new_review_status])

    return (added_review_status, deleted_review_status, new_review_status)
示例#2
0
    def post(self):
        if not users.is_current_user_admin():
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.response.headers['Content-Type'] = 'text/html'

        # TODO(benvanik): validate email
        email = self.request.get('email')

        # Find server with email - if present, return that
        existing_server = ServerRegistration.gql('WHERE email=:1', email).get()
        if existing_server:
            self.response.out.write('Server already exists: %s' %
                                    (existing_server.uuid))
            return

        server_registration = ServerRegistration(email=db.Email(email),
                                                 uuid=str(uuid.uuid4()),
                                                 private_key=str(uuid.uuid4()))
        server_registration.put()

        self.response.out.write('<br/>'.join([
            'Server registered:',
            'UUID: %s' % (cgi.escape(server_registration.uuid)),
            'E-mail: %s' % (cgi.escape(server_registration.email)),
            'Private Key: %s' % (cgi.escape(server_registration.private_key)),
        ]))

        self.response.out.write('<br/><a href="/admin/"><< Back</a>')
示例#3
0
def addStudent(name, emails, status, username=None, advisors=None):
    '''
	@param name
	@param emails
	@param status
	@param username
	@param advisors
	'''

    # key is key from name + 'student'
    key = str(name.key()) + 'student'

    # if this student member already exists, return the object
    student = Student.get_by_key_name(key)
    if student is not None:
        return student

    if advisors is None: advisors = []
    if type(advisors) is Faculty:
        advisors = [advisors]

    # Create and return a new instance if necessary
    emails = [db.Email(email) for email in emails]
    advisors = [advisor.key() for advisor in advisors]
    student = Student(key_name=key, name=name, emails=emails, status=status)
    student.username = username
    student.advisors = advisors
    db.put(student)
    for advisor in db.get(student.advisors):
        if student.key() not in advisor.advisees:
            advisor.advisees.append(student.key())
        db.put(advisor)

    return student
示例#4
0
  def post(self, path):
    user = users.get_current_user()
    if user is None or (user and not self.user_can_edit(user)):
      common.handle_401(self.request, self.response, Exception)
      return

    owner_addrs = self.split_input('owner', delim=',')
    owners = [db.Email(addr) for addr in owner_addrs]

    blink_components = (
        self.split_input('blink_components', delim=',') or
        [models.BlinkComponent.DEFAULT_COMPONENT])

    # TODO(jrobbins): Validate input, even though it is done on client.

    feature = models.Feature(
        category=int(self.request.get('category')),
        name=self.request.get('name'),
        feature_type=int(self.request.get('feature_type', 0)),
        intent_stage=models.INTENT_NONE,
        summary=self.request.get('summary'),
        owner=owners,
        impl_status_chrome=models.NO_ACTIVE_DEV,
        standardization=models.EDITORS_DRAFT,
        unlisted=self.request.get('unlisted') == 'on',
        web_dev_views=models.DEV_NO_SIGNALS,
        blink_components=blink_components)
    key = feature.put()

    # TODO(jrobbins): enumerate and remove only the relevant keys.
    memcache.flush_all()

    redirect_url = '/guide/edit/' + str(key.id())
    return self.redirect(redirect_url)
示例#5
0
    def test_entity_to_dict(self):
        """Converts a datastore.Entity instance to a JSON encodable dict."""

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

        entity = datastore.Entity("Test")
        entity.update({
            "string": "A string.",
            "byte_string": datastore_types.ByteString("Byte String"),
            "boolean": True,
            "int": 42,
            "float": 1.82,
            "date": datetime(2011, 01, 06),
            "list": [1, 2, 3, 4],
            "key": db.Key.from_path("Kind", "name"),
            "user": users.User("*****@*****.**"),
            "email": db.Email("*****@*****.**"),
            "location": db.GeoPt(52.500556, 13.398889),
            "category": db.Category("coding"),
            "link": db.Link("http://www.google.com"),
            "im": db.IM("sip", "foobar"),
            "phone": db.PhoneNumber("1 (206) 555-1212"),
            "address": db.PostalAddress("Address"),
            "rating": db.Rating(99)
        })
示例#6
0
def addStudent (name, emails, status, username = None, advisors = None):
	'''
	@param name
	@param emails
	@param status
	@param username
	@param advisors
	'''
	if advisors is None: advisors = []

	# See if this student is already in the data store
	query = Student.all()
	query = query.filter('name = ', name)
	for email in emails:
		query = query.filter('emails = ', email)
	query = query.filter('status = ', status)
	query = query.filter('username = '******'advisors = ', advisor)

	# Return the instance if it already exists
	student = query.get()
	if student is not None:
		return student
	
	# Create and return a new instance if necessary
	emails = [db.Email(email) for email in emails]
	advisors = [advisor.key() for advisor in advisors]
	student = Student(name = name, emails = emails, status = status)
	student.username = username
	student.advisors = advisors
	db.put(student)

	return student
示例#7
0
def addFaculty (name, emails, title, username = None):
	'''
	@param name
	@param emails
	@param title
	@param username
	'''
	# See if this student is already in the data store
	query = Faculty.all()
	query = query.filter('name = ', name)
	for email in emails:
		query = query.filter('emails = ', email)
	query = query.filter('title = ', title)
	query = query.filter('username = ', username)

	# Return the instance if it already exists
	faculty = query.get()
	if faculty is not None:
		return faculty
	
	# Create and return a new instance if necessary
	emails = [db.Email(email) for email in emails]
	faculty = Faculty(name = name, emails = emails, title = title)
	faculty.username = username
	db.put(faculty)

	return faculty
示例#8
0
    def post(self, error=None):
        email = self.request.get("email")
        name = self.request.get("name")
        password = self.request.get("password")
        confirm = self.request.get("confirm-password")
        salt = self.make_salt()

        # Ensure all required fields have been submitted
        if len(email) == 0 or len(password) == 0 or len(confirm) == 0:
            error = "Missing one or more required fields."
        # Ensure the password and confirm password fields match
        elif password != confirm:
            error = "Your passwords do not match."
        # Ensure the email is in a valid email format
        elif not (re.match(
                r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email)):
            error = "You did not enter a valid email address."
        # Ensure the email does not match a current user
        elif User.get_by_email(email):
            error = "A user with that email already exists."
        # Register the new user
        else:
            pw_hash = self.make_pw_hash(email, password, salt)
            user = User(email=db.Email(email),
                        name=name,
                        pw_hash=pw_hash,
                        salt=salt)
            user_key = user.put()
            uid = user_key.id()
            self.set_cookie("user", str(uid), "/", True)
            self.redirect("/")
        self.render("signup.html", error=error)
示例#9
0
 def setUp(self):
     """Create two test issues and users."""
     super(TestSearch, self).setUp()
     user = User('*****@*****.**')
     models.Account.get_account_for_user(user)
     user = User('*****@*****.**')
     models.Account.get_account_for_user(user)
     self.user = User('*****@*****.**')
     self.login('*****@*****.**')
     issue1 = models.Issue(subject='test')
     issue1.reviewers = [db.Email('*****@*****.**'),
                         db.Email('*****@*****.**')]
     issue1.local_base = False
     issue1.put()
     issue2 = models.Issue(subject='test')
     issue2.reviewers = [db.Email('*****@*****.**'),
                         db.Email('*****@*****.**')]
     issue2.local_base = False
     issue2.put()
示例#10
0
文件: email.py 项目: Shrews/PyGerrit
def send_change_message(request,
                        change,
                        template,
                        template_args,
                        sender,
                        send_email=True,
                        email_template=None,
                        additional_to=[]):
  # sender
  default = get_default_sender()
  if not sender:
    sender = default
  sender_string = to_email_string(sender)

  # to
  to_users = set(  [change.owner]
                 + change.reviewers
                 + change.cc
                 + [default]
                 + additional_to)
  if sender in to_users:
    to_users.remove(sender)
  to_strings = make_to_strings(to_users)
  to_emails = [db.Email(s) for s in to_strings]

  # subject
  subject = make_change_subject(change)

  # body
  uri = library.change_url(change)
  if template_args is None:
    template_args = dict()
  else:
    template_args = dict(template_args)
  template_args['change'] = change

  if not email_template:
    email_template = template
  body = django.template.loader.render_to_string(email_template,
                                                 template_args)

  # don't send emails without all of these fields
  if not sender_string or not to_strings or not subject or not body:
    return None

  # send the email
  if send_email:
    message_body = "%s\n--\n%s\n" % (body, uri)
    try:
      mail.send_mail(sender=sender_string,
                     to=to_strings,
                     subject=subject,
                     body=message_body)
    except apiproxy_errors.OverQuotaError, e:
      logging.error(str(e), exc_info=True)
示例#11
0
文件: util.py 项目: Shrews/PyGerrit
def commit_to_revision(proj, commit):
    """Converts a GitCommit into a RevisionId data store object.
  """
    p_a = commit.author
    p_c = commit.committer

    return models.RevisionId.get_or_insert_revision(
        project=proj,
        id=commit.id,
        ancestors=[p for p in commit.parent_id],
        message=db.Text(u(commit.message)),
        author_name=u(p_a.name),
        author_email=db.Email(u(p_a.email)),
        author_when=datetime.datetime.utcfromtimestamp(p_a.when),
        author_tz=p_a.tz,
        committer_name=u(p_c.name),
        committer_email=db.Email(u(p_c.email)),
        committer_when=datetime.datetime.utcfromtimestamp(p_c.when),
        committer_tz=p_a.tz,
    )
    def testListProperties(self):
        """Tests list properties."""

        raise SkipTest  # TODO: Implement correct db.ListProperty behaviour.

        class Numbers(db.Model):
            values = db.ListProperty(int)

        Numbers().put()
        Numbers(values=[0, 1, 2, 3]).put()
        Numbers(values=[4, 5, 6, 7]).put()

        query = Numbers.all().filter('values =', 0)
        self.assertEqual([0, 1, 2, 3], query.get().values)

        query = db.GqlQuery(
            "SELECT * FROM Numbers WHERE values > :1 AND values < :2", 4, 7)
        self.assertEqual([4, 5, 6, 7], query.get().values)

        class Issue(db.Model):
            reviewers = db.ListProperty(db.Email)

        me = db.Email('*****@*****.**')
        you = db.Email('*****@*****.**')
        issue = Issue(reviewers=[me, you])
        issue.put()

        query = db.GqlQuery("SELECT * FROM Issue WHERE reviewers = :1",
                            db.Email('*****@*****.**'))

        self.assertEqual(1, query.count())

        query = db.GqlQuery("SELECT * FROM Issue WHERE reviewers = :1",
                            '*****@*****.**')

        self.assertEqual(1, query.count())

        query = db.GqlQuery("SELECT * FROM Issue WHERE reviewers = :1",
                            db.Email('*****@*****.**'))

        self.assertEqual(0, query.count())
示例#13
0
    def __init__(self, db_client, base_dir='/Dropsite', site_yaml='site.yaml'):
        from google.appengine.ext import db
        from google.appengine.api import users

        self._db_client = db_client
        self.dropbox_access_token = 'oauth_token_secret=fakesecret&oauth_token=vc1okyqpio7irgy'
        self.dropbox_base_dir = base_dir.lower()
        self.dropbox_site_yaml = site_yaml.lower()
        self.dropbox_display_name = 'DB Owner'
        self.dropbox_email = db.Email('*****@*****.**')
        self.owner = users.User(email='*****@*****.**')
        self.owner_id = 'ownerid'
示例#14
0
 def add_message(self, sender, recipients, seconds, text):
   """Adds a Message."""
   msg = models.Message(
       parent=self.issue.key,
       issue_key=self.issue.key,
       subject='Your code is great',
       sender=sender,
       recipients=[db.Email(r) for r in recipients],
       date=self.now + datetime.timedelta(seconds=seconds),
       text=text)
   msg.put()
   self.messages.append(msg)
示例#15
0
def add_task(email, url, xpath, html):
    e = db.Email(email)
    u = db.Link(url)
    if isduplicated(e, u, xpath) == False:
        task = Task(email=e, url=u, xpath=xpath, html=_set_task_html(html))
        try:
            task.put()
            return True
        except db.Error:
            return 'Datastore save error'
    else:
        return "You have inspected this portion."
示例#16
0
 def add(form):
     image_thumb = images.resize(form['image'], 100, 100)
     image_medium = images.resize(form['image'], 480, 480)
     image_small = images.resize(form['image'], 200, 200)
     billboard = Billboard(title=form['title'])
     billboard.phone = db.PhoneNumber(form['phone'])
     billboard.email = db.Email(form['email'])
     billboard.image = db.Blob(form.get('image'))
     billboard.image_thumb = db.Blob(image_thumb)
     billboard.image_medium = db.Blob(image_medium)
     billboard.image_small = db.Blob(image_small)
     billboard.put()
def hook(dct):
    clsType = dct[CLASS_TYPE_STR]
    if clsType == 'date':
        return datetime.date.fromtimestamp(dct[CLASS_VALUE_STR])
    if clsType == 'email':
        return db.Email(dct[CLASS_VALUE_STR])
    if clsType == 'phone':
        return db.PhoneNumber(dct[CLASS_VALUE_STR])
    elif clsType == 'rating':
        return db.Rating(dct[CLASS_VALUE_STR])
    # The constructor can't handle the clsType tag, so delete it!
    dictCopy = dict((key, value) for key, value in dct.iteritems()
                    if not key.startswith('__'))
    return globals()[clsType](**dictCopy).put()
示例#18
0
def user(request):
    user = users.get_current_user()
    
    if user:
        usetting = UserSetting.gql('WHERE userid = :1', user.user_id())
        if usetting.count() == 0:
            usetting = UserSetting(userid=user.user_id(), email=db.Email(user.email()), is_contrib=False)
            usetting.put()
        userurl = users.create_logout_url(request.get_full_path())
    else:
        userurl = users.create_login_url(request.get_full_path())
        
    return {
        "user": user,
        "userurl": userurl
    }
示例#19
0
    def post(self):
        title = self.request.get('title')
        blurb = self.request.get('blurb')
        phone = self.request.get('phone')
        image = self.request.get('image')
        email = self.request.get('email')
        price = self.request.get('price')

        image_thumb = images.resize(image, 100, 100)
        image_medium = images.resize(image, 480, 480)
        image_small = images.resize(image, 200, 200)
        billboards = self.request.get('selected_billboards')
        billboards = [db.Key(key) for key in billboards.split(' ')]

        ad = Ad(title=title)
        ad.ip = self.request.remote_addr
        ad.sold = False
        ad.blurb = blurb
        ad.image = db.Blob(image)
        ad.image_thumb = db.Blob(image_thumb)
        ad.image_medium = db.Blob(image_medium)
        ad.image_small = db.Blob(image_small)
        ad.phone = db.PhoneNumber(phone)
        ad.email = db.Email(email)
        ad.price2 = int(price)
        ad.billboards = billboards
        ad.put()

        ad.password = hashlib.md5(SALT + ad.ip + str(ad.key())).hexdigest()
        ad.save()

        for billboard in db.get(billboards):
            billboard.ads.append(ad.key())
            billboard.put()

        path = os.path.join(os.path.dirname(__file__), 'success.html')
        self.response.out.write(
            template.render(
                path, {
                    'ad':
                    ad,
                    'secret_link':
                    'http://%s/ads/%s/edit?password=%s' %
                    (self.request.host, ad.key(), ad.password)
                }))
示例#20
0
def task_member_restore(items):

    for item in items:
        member = Member()
        member.number = item['number']
        member.address = item['address']
        if item['email'] != '' and item['email'] != None:
            member.email = db.Email(item['email'])
        member.name = item['name']
        member.member_since = string_to_date(item['memberSince'])
        if item['phone'] != '' and item['phone'] != None:
            member.phone = db.PhoneNumber(item['phone'])
        if item['phoneWork'] != '' and item['phoneWork'] != None:
            member.phone_work = item['phoneWork']
        if item['phoneHome'] != '' and item['phoneHome'] != None:
            member.phone_home = item['phoneHome']
        member.notes = item['notes']
        member.zipcode = item['zipcode']
        member.city = item['city']
        member.county = item['county']
        member.country = db.get(db.Key.from_path('Country', item['countryId']))
        member.status = db.get(db.Key.from_path('Status', item['statusId']))
        member.membertype = db.get(
            db.Key.from_path('MemberType', item['typeId']))
        member.put()

        for itemdue in item['membershipDues']:
            due = MembershipDues(parent=member,
                                 year=itemdue['year'],
                                 paid=itemdue['paid'])
            due.put()

        for itemcar in item['cars']:
            car = Car()
            car.member = member
            car.registration = itemcar['registration']
            car.model = db.get(db.Key.from_path('CarModel',
                                                itemcar['modelId']))
            car.bought_year = itemcar['boughtYear']
            car.sold_year = itemcar['soldYear']
            car.year = itemcar['year']
            car.notes = itemcar['notes']
            car.serial_no = itemcar['serialNo']
            car.put()
    def testVariousPropertiyTypes(self):
        """Tests various property types."""
        class Note(db.Model):
            timestamp = db.DateTimeProperty(auto_now=True)
            description = db.StringProperty()
            author_email = db.EmailProperty()
            location = db.GeoPtProperty()
            user = db.UserProperty()

        Note(description="My first note.",
             author_email="*****@*****.**",
             location="52.518,13.408",
             user=users.get_current_user()).put()

        query = db.GqlQuery("SELECT * FROM Note ORDER BY timestamp DESC")
        self.assertEqual(1, query.count())

        query = db.GqlQuery("SELECT * FROM Note WHERE timestamp <= :1",
                            datetime.datetime.now())

        self.assertEqual(1, query.count())

        note = query.get()

        self.assertEqual("My first note.", note.description)

        self.assertEqual(db.Email("*****@*****.**"), note.author_email)
        self.assertEqual("*****@*****.**", note.author_email)

        self.assertEqual(
            datastore_types.GeoPt(52.518000000000001, 13.407999999999999),
            note.location)
        self.assertEqual("52.518,13.408", note.location)

        del note

        query = Note.all().filter(
            'location =',
            datastore_types.GeoPt(52.518000000000001, 13.407999999999999))
        self.assertEqual(1, query.count())

        query = Note.all().filter('location =', db.GeoPt("52.518,13.408"))
        self.assertEqual(1, query.count())
示例#22
0
    def post(self):
        # Variables
        user_error = ''
        pass_error = ''
        verify_error = ''
        email_error = ''

        username = self.request.get('username')
        password = self.request.get('password')
        verify = self.request.get('verify')
        email = self.request.get('email')

        users = User.gql("WHERE name = '%s';" % username)

        # Validation
        if not valid_username(username):
            user_error = "That's not a valid username."

        elif users.get():
            user_error = 'That user already exists.'

        if not valid_password(password):
            pass_error = "That's not a valid password."

        elif not (password == verify):
            verify_error = "Your passwords didn't match."

        if email and (not valid_email(email)):
            email_error = "That's not a valid email."

        # Output
        if (user_error + pass_error + verify_error + email_error):
            self.run(user_error, pass_error, verify_error, email_error,
                     username, email)
        else:
            pw = make_pw_hash(username, password)
            u = User(name=username, password=pw)

            if email: u.email = db.Email(email)

            u.put()
            self.to_welcome(username)
示例#23
0
 def create_issue(self, date, reviewers=None, cc=None):
   """Creates an issue by self.author with self.reviewer1 as a reviewer."""
   date = datetime.datetime.strptime('2011-03-' + date, '%Y-%m-%d %H:%M')
   issue = models.Issue(
       subject='test',
       owner=self.author.user,
       reviewers=[r.email for r in reviewers or [self.reviewer1]],
       cc=[db.Email('*****@*****.**')] + [c.email for c in cc or []],
       created=date,
       modified=date)
   issue.put()
   # Verify that our auto_now hack works.
   self.assertEqual(issue.key.get().created, date)
   self.assertEqual(issue.key.get().modified, date)
   ps = models.PatchSet(
     parent=issue.key, issue_key=issue.key, created=date, modified=date)
   ps.data = utils.load_file('ps1.diff')
   ps.put()
   patches = engine.ParsePatchSet(ps)
   ndb.put_multi(patches)
   return issue
示例#24
0
 def post(self, post_id):
     #name = self.request.get('name')
     #email = self.request.get('email')
     comment = self.request.get('comment')
     id = str(self.request.cookies.get("name"))
     user = memcache.get(id)
     blogid = int(post_id)
     if 'picture' in user.keys():
         picture = user['picture']
     else:
         picture = "https://placehold.it/150"
     c = Comments(blogid=blogid,
                  name=user['name'],
                  email=db.Email(user['email']),
                  comment=comment,
                  picture=picture)
     c.put()
     data = Blog.get_by_id(int(post_id))
     data.comments = data.comments + 1
     data.put()
     self.redirect('/blog/' + post_id)
示例#25
0
    def post(self, path, user_id=None):
        if user_id:
            self._delete(user_id)
            self.redirect('/admin/users/new')
            return

        email = self.request.get('email')

        # Don't add a duplicate email address.
        user = models.AppUser.all(keys_only=True).filter('email = ',
                                                         email).get()
        if not user:
            user = models.AppUser(email=db.Email(email))
            user.put()

            self.response.set_status(201, message='Created user')
            self.response.headers['Content-Type'] = 'application/json'
            return self.response.write(json.dumps(user.format_for_template()))
        else:
            self.response.set_status(200, message='User already exists')
            self.response.write(json.dumps({'id': user.id()}))
示例#26
0
    def post(self, member_no):
        member = self.get_member(member_no)

        member.name = self.get_required('name')
        member.address = self.get_required('address')
        member.zipcode = self.get_required('zip')
        member.city = self.get_required('city')
        country = Country.get(self.get_required('country'))

        email = self.get_required('email')
        if email != '':
            member.email = db.Email(email)

        mobile = self.get_required('mobile')
        if mobile != '':
            member.phone = db.PhoneNumber(mobile)

        home = self.request.get('fixed')
        if home != '':
            member.phone_home = db.PhoneNumber(home)

        work = self.request.get('work')
        if work != '':
            member.phone_work = db.PhoneNumber(work)

        member.put()
        member.update_index()

        template = JINJA_ENVIRONMENT.get_template(
            'templates/selfservice/profile_edit.html')
        countries = Country.all().order('order').fetch(FETCH_LIMIT)

        data = {
            'message': 'Medlemsprofilen din er oppdatert.',
            'member': member,
            'countries': countries
        }
        self.response.write(template.render(data))
示例#27
0
def addFaculty(name, emails, title, username=None):
    '''
	@param name
	@param emails
	@param title
	@param username
	'''

    # key is concatenation of all present name identifiers
    key = str(name.key()) + 'faculty'

    # if this faculty member already exists, return the object
    faculty = Faculty.get_by_key_name(key)
    if faculty is not None:
        return faculty

    emails = [db.Email(email) for email in emails]

    faculty = Faculty(key_name=key, name=name, emails=emails, title=title)
    faculty.username = username

    db.put(faculty)

    return faculty
示例#28
0
  def post(self, path, feature_id=None):
    user = users.get_current_user()
    if user is None or (user and not self.user_can_edit(user)):
      common.handle_401(self.request, self.response, Exception)
      return

    spec_link = self.__FullQualifyLink('spec_link')

    explainer_links = self.request.get('explainer_links') or []
    if explainer_links:
      explainer_links = filter(bool, [x.strip() for x in re.split('\\r?\\n', explainer_links)])

    bug_url = self.__FullQualifyLink('bug_url')
    launch_bug_url = self.__FullQualifyLink('launch_bug_url')
    initial_public_proposal_url = self.__FullQualifyLink(
        'initial_public_proposal_url')
    intent_to_implement_url = self.__FullQualifyLink('intent_to_implement_url')
    origin_trial_feedback_url = self.__FullQualifyLink('origin_trial_feedback_url')

    ff_views_link = self.__FullQualifyLink('ff_views_link')
    ie_views_link = self.__FullQualifyLink('ie_views_link')
    safari_views_link = self.__FullQualifyLink('safari_views_link')
    web_dev_views_link = self.__FullQualifyLink('web_dev_views_link')

    # Cast incoming milestones to ints.
    shipped_milestone = self.__ToInt('shipped_milestone')
    shipped_android_milestone = self.__ToInt('shipped_android_milestone')
    shipped_ios_milestone = self.__ToInt('shipped_ios_milestone')
    shipped_webview_milestone = self.__ToInt('shipped_webview_milestone')
    shipped_opera_milestone = self.__ToInt('shipped_opera_milestone')
    shipped_opera_android_milestone = self.__ToInt('shipped_opera_android_milestone')

    owners = self.request.get('owner') or []
    if owners:
      owners = [db.Email(x.strip()) for x in owners.split(',')]

    doc_links = self.request.get('doc_links') or []
    if doc_links:
      doc_links = filter(bool, [x.strip() for x in re.split('\\r?\\n', doc_links)])

    sample_links = self.request.get('sample_links') or []
    if sample_links:
      sample_links = filter(bool, [x.strip() for x in re.split('\\r?\\n', sample_links)])

    search_tags = self.request.get('search_tags') or []
    if search_tags:
      search_tags = filter(bool, [x.strip() for x in search_tags.split(',')])

    blink_components = self.request.get('blink_components') or models.BlinkComponent.DEFAULT_COMPONENT
    if blink_components:
      blink_components = filter(bool, [x.strip() for x in blink_components.split(',')])

    devrel = self.request.get('devrel') or []
    if devrel:
      devrel = [db.Email(x.strip()) for x in devrel.split(',')]

    try:
      intent_stage = int(self.request.get('intent_stage'))
    except:
      logging.error('Invalid intent_stage \'{}\'' \
                    .format(self.request.get('intent_stage')))

      # Default the intent stage to 1 (Prototype) if we failed to get a valid
      # intent stage from the request. This should be removed once we
      # understand what causes this.
      intent_stage = 1

    if feature_id: # /admin/edit/1234
      feature = models.Feature.get_by_id(long(feature_id))

      if feature is None:
        return self.redirect(self.request.path)

      if 'delete' in path:
        feature.delete()
        memcache.flush_all()
        return # Bomb out early for AJAX delete. No need to redirect.

      # Update properties of existing feature.
      feature.category = int(self.request.get('category'))
      feature.name = self.request.get('name')
      feature.intent_stage = intent_stage
      feature.summary = self.request.get('summary')
      feature.unlisted = self.request.get('unlisted') == 'on'
      feature.intent_to_implement_url = intent_to_implement_url
      feature.origin_trial_feedback_url = origin_trial_feedback_url
      feature.motivation = self.request.get('motivation')
      feature.explainer_links = explainer_links
      feature.owner = owners
      feature.bug_url = bug_url
      feature.launch_bug_url = launch_bug_url
      feature.initial_public_proposal_url = initial_public_proposal_url
      feature.blink_components = blink_components
      feature.devrel = devrel
      feature.impl_status_chrome = int(self.request.get('impl_status_chrome'))
      feature.shipped_milestone = shipped_milestone
      feature.shipped_android_milestone = shipped_android_milestone
      feature.shipped_ios_milestone = shipped_ios_milestone
      feature.shipped_webview_milestone = shipped_webview_milestone
      feature.shipped_opera_milestone = shipped_opera_milestone
      feature.shipped_opera_android_milestone = shipped_opera_android_milestone
      feature.footprint = int(self.request.get('footprint'))
      feature.interop_compat_risks = self.request.get('interop_compat_risks')
      feature.ergonomics_risks = self.request.get('ergonomics_risks')
      feature.activation_risks = self.request.get('activation_risks')
      feature.security_risks = self.request.get('security_risks')
      feature.debuggability = self.request.get('debuggability')
      feature.all_platforms = self.request.get('all_platforms') == 'on'
      feature.all_platforms_descr = self.request.get('all_platforms_descr')
      feature.wpt = self.request.get('wpt') == 'on'
      feature.wpt_descr = self.request.get('wpt_descr')
      feature.ff_views = int(self.request.get('ff_views'))
      feature.ff_views_link = ff_views_link
      feature.ff_views_notes = self.request.get('ff_views_notes')
      feature.ie_views = int(self.request.get('ie_views'))
      feature.ie_views_link = ie_views_link
      feature.ie_views_notes = self.request.get('ie_views_notes')
      feature.safari_views = int(self.request.get('safari_views'))
      feature.safari_views_link = safari_views_link
      feature.safari_views_notes = self.request.get('safari_views_notes')
      feature.web_dev_views = int(self.request.get('web_dev_views'))
      feature.web_dev_views_link = web_dev_views_link
      feature.web_dev_views_notes = self.request.get('web_dev_views_notes')
      feature.prefixed = self.request.get('prefixed') == 'on'
      feature.spec_link = spec_link
      feature.tag_review = self.request.get('tag_review')
      feature.standardization = int(self.request.get('standardization'))
      feature.doc_links = doc_links
      feature.sample_links = sample_links
      feature.search_tags = search_tags
      feature.comments = self.request.get('comments')
      feature.experiment_goals = self.request.get('experiment_goals')
      feature.experiment_timeline = self.request.get('experiment_timeline')
      feature.experiment_risks = self.request.get('experiment_risks')
      feature.experiment_extension_reason = self.request.get('experiment_extension_reason')
      feature.ongoing_constraints = self.request.get('ongoing_constraints')
    else:
      # Check bug for existing blink component(s) used to label the bug. If
      # found, use the first component name instead of the generic "Blink" name.
      try:
        blink_components = self.__get_blink_component_from_bug(blink_components, bug_url)
      except Exception:
        pass

      feature = models.Feature(
          category=int(self.request.get('category')),
          name=self.request.get('name'),
          intent_stage=intent_stage,
          summary=self.request.get('summary'),
          intent_to_implement_url=intent_to_implement_url,
          origin_trial_feedback_url=origin_trial_feedback_url,
          motivation=self.request.get('motivation'),
          explainer_links=explainer_links,
          owner=owners,
          bug_url=bug_url,
          launch_bug_url=launch_bug_url,
          initial_public_proposal_url=initial_public_proposal_url,
          blink_components=blink_components,
          devrel=devrel,
          impl_status_chrome=int(self.request.get('impl_status_chrome')),
          shipped_milestone=shipped_milestone,
          shipped_android_milestone=shipped_android_milestone,
          shipped_ios_milestone=shipped_ios_milestone,
          shipped_webview_milestone=shipped_webview_milestone,
          shipped_opera_milestone=shipped_opera_milestone,
          shipped_opera_android_milestone=shipped_opera_android_milestone,
          interop_compat_risks=self.request.get('interop_compat_risks'),
          ergonomics_risks=self.request.get('ergonomics_risks'),
          activation_risks=self.request.get('activation_risks'),
          security_risks=self.request.get('security_risks'),
          debuggability=self.request.get('debuggability'),
          all_platforms=self.request.get('all_platforms') == 'on',
          all_platforms_descr=self.request.get('all_platforms_descr'),
          wpt=self.request.get('wpt') == 'on',
          wpt_descr=self.request.get('wpt_descr'),
          footprint=int(self.request.get('footprint')),
          ff_views=int(self.request.get('ff_views')),
          ff_views_link=ff_views_link,
          ff_views_notes=self.request.get('ff_views_notes'),
          ie_views=int(self.request.get('ie_views')),
          ie_views_link=ie_views_link,
          ie_views_notes=self.request.get('ie_views_notes'),
          safari_views=int(self.request.get('safari_views')),
          safari_views_link=safari_views_link,
          safari_views_notes=self.request.get('safari_views_notes'),
          web_dev_views=int(self.request.get('web_dev_views')),
          web_dev_views_link=web_dev_views_link,
          web_dev_views_notes=self.request.get('web_dev_views_notes'),
          prefixed=self.request.get('prefixed') == 'on',
          spec_link=spec_link,
          tag_review=self.request.get('tag_review'),
          standardization=int(self.request.get('standardization')),
          doc_links=doc_links,
          sample_links=sample_links,
          search_tags=search_tags,
          comments=self.request.get('comments'),
          experiment_goals=self.request.get('experiment_goals'),
          experiment_timeline=self.request.get('experiment_timeline'),
          experiment_risks=self.request.get('experiment_risks'),
          experiment_extension_reason=self.request.get('experiment_extension_reason'),
          ongoing_constraints=self.request.get('ongoing_constraints'),
          )

    params = []
    if self.request.get('create_launch_bug') == 'on':
      params.append(self.LAUNCH_PARAM)
    if self.request.get('intent_to_implement') == 'on':
      params.append(self.INTENT_PARAM)

      feature.intent_template_use_count += 1

    key = feature.put()

    # TODO(ericbidelman): enumerate and remove only the relevant keys.
    memcache.flush_all()

    redirect_url = '/feature/' + str(key.id())

    if len(params):
      redirect_url = '%s/%s?%s' % (self.LAUNCH_URL, key.id(),
                                   '&'.join(params))

    return self.redirect(redirect_url)
示例#29
0
e1 = Everything(
    str=u"hello",
    bool=True,
    int=10,
    float=5.05,
    datetime=d,
    date=d.date(),
    time=d.time(),
    list=[1, 2, 3],
    strlist=["hello", u'world'],
    user=users.User("*****@*****.**"),
    blob=db.Blob("somerandomdata"),
    text=db.Text("some random text"),
    category=db.Category("awesome"),
    link=db.Link("http://www.10gen.com"),
    email=db.Email("*****@*****.**"),
    geopt=db.GeoPt(40.74067, -73.99367),
    im=db.IM("http://aim.com/", "example"),
    phonenumber=db.PhoneNumber("1 (999) 123-4567"),
    postaladdress=db.PostalAddress("40 W 20th St., New York, NY"),
    rating=db.Rating(99),
)
out = db.get(e1.put())


def failIfNot(reference, value, type):
    assert value == reference
    assert isinstance(value, type)


failIfNot(e1.str, out.str, types.UnicodeType)
示例#30
0
    def post(self):
        signed_request = utility.parse_signed_request(
            self.request.get('signed_request'), FACEBOOK_APP_SECRET)

        if signed_request:
            if signed_request.has_key('user_id'):
                # if user is Authorized and has user id, then capture new information
                # and update if they exist if not put them into datastore.
                self.session['oauth_token'] = signed_request['oauth_token']
                self.session['member_id'] = signed_request['user_id']
                member_id = signed_request['user_id']
                member = Member.gql("WHERE id = :member_id",
                                    member_id=member_id).get()
                render_parameters = {}
                # if not member add member.
                graph = facebook.GraphAPI(signed_request['oauth_token'])
                me = graph.get_object("me")
                member = self.current_member()
                if not member:
                    member = Member(key_name=me['id'])
                    member.id = me['id']
                    member.username = me['username']
                    member.first_name = me['first_name']
                    member.last_name = me['last_name']
                    member.name = me['name']
                    member.email = db.Email(
                        me['email']
                    )  # It might be null if user did not provide an email
                    member.country = Country.country_name(
                        signed_request['user']['country'])
                    member.put()
                if member.aiesec_email:  #Already an AIESECer!
                    #Get current member and see if she already has a home_entity
                    render_parameters = {'member': member}
                    if member.home_committee:  # Member already has a home_entity
                        param = self.render_parameters()
                        param[
                            "body_function"] = "committee_body('{0}');".format(
                                member.home_committee.key())
                        self.show_page("base", param)
                    else:  # Member is not in a commmittee
                        param = self.render_parameters()
                        param["body_function"] = "entity_welcome_body();"
                        self.show_page("base", param)
                else:  #Member is not verified to be an AIESECer yet
                    # 1 - First method, to see if user email is an aiesec.net email
                    if (member.email.find("@aiesec.net") > -1):
                        render_parameters['aiesec_email_found'] = member.email
                    # 2 - Second method of getting aiesec email, user authorize the app to access
                    # if user is already signed in then get his email
                    if users.get_current_user():
                        current_user = users.get_current_user()
                        url_linktext = ''
                        current_email = str(current_user.email())
                        if current_email.find("@aiesec.net") > -1:
                            #keep the email in a login_aiesec_email and pass to form
                            render_parameters[
                                'login_aiesec_email'] = current_email
                        else:
                            #Ask for logout
                            url_linktext = 'Logout from ' + current_email
                        url = users.create_logout_url(self.request.uri)
                        render_parameters['url'] = url
                        render_parameters['url_linktext'] = url_linktext
                    else:
                        url = users.create_login_url(self.request.uri)
                        render_parameters['url'] = url
                        url_linktext = 'Login to aiesec.net account'
                        render_parameters['url_linktext'] = url_linktext
                    # 3 - Third method: Sending verification code
                    if member.temp_email_code:
                        if member.temp_email_code.find("@aiesec.net"):
                            render_parameters[
                                'code_sent_email'] = member.temp_email_code.split(
                                    ';')[0]
                    render_parameters['member'] = member
                    self.show_page(r"register/welcome", render_parameters)
            else:
                #if user is not signed in the application he will be prompted to sign in
                self.show_page(r'register/login', {})