Пример #1
0
 def post(self):
     if len(self.request.POST) == 4 and 'handle' in self.request.POST \
             and 'real_name' in self.request.POST \
             and 'email' in self.request.POST \
             and 'bio' in self.request.POST:
         
         handle = self.request.POST.getall('handle')[0]
         template_dict = {}
         hacker = Hacker.get_current_hacker()
         other = Hacker.gql('WHERE handle = :1', handle).get()
         
         if (not handle or len(handle) > 12 or
             any(l not in self.valid_letters for l in handle)):
             template_dict['error'] = 'Pick something sensible, you moron.'
         
         elif other and other.user_id != hacker.user_id:
             template_dict['error'] = 'Sorry, already taken.'
         
         elif handle.lower() in self.banned_names:
             template_dict['error'] = self.banned_names[handle]
         
         else:
             real_name = self.request.POST.getall('real_name')[0]
             if real_name:
                 hacker.real_name = real_name
             email = self.request.POST.getall('email')[0]
             if email:
                 hacker.email = email
             bio = self.request.POST.getall('bio')[0]
             if bio:
                 hacker.bio = bio
             hacker.handle = handle
             hacker.save()
             template_dict['error'] = 'Profile updated'
         self.render_template('account', template_dict=template_dict)
Пример #2
0
    def post(self):
        if len(self.request.POST) == 4 and 'handle' in self.request.POST \
                and 'real_name' in self.request.POST \
                and 'email' in self.request.POST \
                and 'bio' in self.request.POST:

            handle = self.request.POST.getall('handle')[0]
            template_dict = {}
            hacker = Hacker.get_current_hacker()
            other = Hacker.gql('WHERE handle = :1', handle).get()

            if (not handle or len(handle) > 12
                    or any(l not in self.valid_letters for l in handle)):
                template_dict['error'] = 'Pick something sensible, you moron.'

            elif other and other.user_id != hacker.user_id:
                template_dict['error'] = 'Sorry, already taken.'

            elif handle.lower() in self.banned_names:
                template_dict['error'] = self.banned_names[handle]

            else:
                real_name = self.request.POST.getall('real_name')[0]
                if real_name:
                    hacker.real_name = real_name
                email = self.request.POST.getall('email')[0]
                if email:
                    hacker.email = email
                bio = self.request.POST.getall('bio')[0]
                if bio:
                    hacker.bio = bio
                hacker.handle = handle
                hacker.save()
                template_dict['error'] = 'Profile updated'
            self.render_template('account', template_dict=template_dict)
Пример #3
0
 def post(self):
     post = self.request.POST
     if post['kind'] == 'badge':
         b = Badge(name=post['name'],
                   description=post['description'],
                   category=post['category'],
                   image=post['image'],
                   value=int(post['value']))
         b.save()
     elif post['kind'] == 'article':
         a = NewsArticle(title=post['title'],
                         author=post['author'],
                         body=post['body'],
                         date=datetime.date.today())
         a.save()
     elif post['kind'] == 'award':
         badge = Badge.gql('WHERE name = :1', post['badge']).get()
         for h in post.getall('hackers'):
             hacker = Hacker.gql('WHERE handle = :1', h).get()
             a = Award(hacker=hacker,
                       badge=badge,
                       date=datetime.date.today(),
                       proof=post['proof'])
             a.save()
             hacker.score_cache = hacker.score + badge.value
             hacker.save()
     self.get()
Пример #4
0
 def get(self):
     id = request.args['id']
     try:
         hacker = Hacker.get_by_id(id)
     except:
         abort(404, message = "Hacker not found")
     item = self.choose_next(hacker)
     if item != None:
         try:
             if hacker.next_proj != None and hacker.next_proj != item:
                 hacker.prev_proj = hacker.next_proj
             hacker.next_proj = item
             hacker.save()
         except:
             abort(409, message = "Unable to save next project to hacker")
         res = jsonify({
             "table": item.table,
             "title": item.name,
             "url": item.url
         })
         res.status_code = 200
         return res
     else:
         res = jsonify({"table": None})
         res.status_code = 200
         return res
Пример #5
0
 def get(self):
     if 'url' in self.request.GET:
         hacker = Hacker.get_current_hacker()
         if hacker.handle.isdigit() and len(hacker.handle) == 21:
             self.redirect('/account')
         else:
             self.redirect(self.request.GET.getall('url')[0])
     else:
         self.redirect('/')
Пример #6
0
 def get(self):
     if 'url' in self.request.GET:
         hacker = Hacker.get_current_hacker()
         if hacker.handle.isdigit() and len(hacker.handle) == 21:
             self.redirect('/account')
         else:
             self.redirect(self.request.GET.getall('url')[0])
     else:
         self.redirect('/')
Пример #7
0
    def get(self):
        self._current_user = self.require_login()
        if not self._current_user:
            self.response.out.write(json.dumps({"error": "please log in"}))
            return

        newhacker = Hacker(first_name = self.request.get("first_name"),
                           last_name = self.request.get("last_name"),
                           user = self._current_user.id,
                           catchphrase = self.request.get("catchphrase"),
                           imageset = self.request.get("image"),
                           level = 1,
                           base_energy = int(self.request.get("energy")),
                           base_productivity = int(self.request.get("productivity")),
                           base_teamwork = int(self.request.get("teamwork")))
        if self.request.get("clss"):
            newhacker.talents = [self.request.get("clss")]
        newhacker.put()
        self.response.out.write(json.dumps({"success": "new hacker created"}))
Пример #8
0
    def get(self):
        self._current_user = self.require_login()
        if not self._current_user:
            self.authenticate()
            return

        self._current_user.hackers = Hacker.all().filter("user ="******"user": self._current_user}))
Пример #9
0
def create_or_update_hacker(strategy, details, response, user, *args, **kwargs):
    if hasattr(user, 'hacker'):
        # If there's a hacker already, this is an existing user, and we'll
        # update the hacker.
        hacker = user.hacker
    else:
        # If there's no hacker, that means this is a new user. Let's make the
        # hacker.
        hacker = Hacker(user=user)

    changed = False

    for name, value in details.items():
        if name in HACKER_ATTRIBUTES:
            setattr(hacker, name, value)
            changed = True

    if changed:
        hacker.save()
Пример #10
0
    def get(self):
        self._current_user = self.require_login()
        if not self._current_user:
            self.authenticate()
            return

        match = getCurrentMatchByUser(self._current_user.id)
        if not match:
            self.redirect("/loadout")
            return

        #Resolve hacker ids to actual hacker data
        hacker_list = {}
        for hacker in match.hacker_list:
            hacker_instance = Hacker.get(hacker)
            hacker_list[str(hacker_instance.key())] = {"first_name": hacker_instance.first_name,
                             "last_name": hacker_instance.last_name,
                             "talents": hacker_instance.talents,
                             "imgset": hacker_instance.imageset,
                             "base": {"energy": hacker_instance.base_energy,
                                      "productivity": hacker_instance.base_productivity,
                                      "teamwork": hacker_instance.base_teamwork}}

        #Resolve hackers for this user
        self._current_user.hackers = Hacker.all().filter("user ="******"user": self._current_user,
                                                        "users": users,
                                                        "hackathon": match,
                                                        "hackers": json.dumps(hacker_list),
                                                        "project": project,
                                                        "token": token}))
Пример #11
0
    def post(self):

        # logging.info("Inside the DB handler stufff now in group.")
        # solo_hacker_name = self.request.get("name")
        # solo_hacker_slackid = self.request.get("slackid")
        solo_hacker_skills = json.loads(self.request.get("skill"))
        # logging.warning(solo_hacker_skills)

        new_hacker = Hacker (
            hacker_name =  self.request.get("name"),
            slack_id =  self.request.get("slackid"),
            skills = json.loads(self.request.get("skill"))
        )
        new_hacker.put()

        groups_matching = Group.query(Group.skills_needed.IN(solo_hacker_skills))

        for matchedgroup in groups_matching :
            logging.warning(matchedgroup)
            GROUPS_ENTRIES.append({'groupname': matchedgroup.group_name,'description' : matchedgroup.description,'skills_needed' : matchedgroup.skills_needed})
Пример #12
0
def create_or_update_hacker(strategy, details, response, user, *args,
                            **kwargs):
    if hasattr(user, 'hacker'):
        # If there's a hacker already, this is an existing user, and we'll
        # update the hacker.
        hacker = user.hacker
    else:
        # If there's no hacker, that means this is a new user. Let's make the
        # hacker.
        hacker = Hacker(user=user)

    changed = False

    for name, value in details.items():
        if name in HACKER_ATTRIBUTES:
            setattr(hacker, name, value)
            changed = True

    if changed:
        hacker.save()
Пример #13
0
 def get(self):
     id = request.args['id']
     try:
         hacker = Hacker.get_by_id(id)
         if hacker.verified:
             res = jsonify({"verified": "True"})
             res.status_code = 200
             return res
         raise DoesNotExit()
     except DoesNotExist:
         res = jsonify({"verified": "False"})
         res.status_code = 200
         return res
Пример #14
0
 def post(self):
     post = self.request.POST
     if len(post) == 2 and 'badge' in post and 'proof' in post:
         body = 'Hacker: %s\nBadge: %s\nProof:\n%s' % (
             Hacker.get_current_hacker().handle, post['badge'], 
             post['proof'])
         send_mail(
             sender='*****@*****.**',
             to='*****@*****.**',
             subject='Badge application',
             body=body)
         self.render_template('badge_application', template_dict={'message':
             'Application submitted. It will be reviewed as soon as possible.'})
Пример #15
0
 def get(self):
     hackers = list(Hacker.all())
     if hackers:
         hackers.sort(key=lambda h:(h.score,h.handle))
         rank = 0
         ranked_hackers = [(rank, hackers[-1])]
         for i in range(len(hackers)-2, 0, -1):
             if hackers[i + 1].score_cache != hackers[i].score_cache:
                 rank += 1
             ranked_hackers.append((rank, hackers[i]))
     else:
         ranked_hackers = []
         
     self.render_template('members', {'hackers': ranked_hackers})
Пример #16
0
def register(request):
    if request.method == "GET":
        return render(request, "user_register.html")
    else:
        if not request.POST.get("inputUsername") or not request.POST.get("inputEmail") \
                or not request.POST.get("inputPassword") or not request.POST.get("inputRePassword") \
                or not request.POST.get("inputSex") or not request.POST.get("inputAge"):
            return redirect("/user/register")
        elif check_email(request.POST["inputEmail"].strip()):
            return redirect("/user/register")
        elif request.POST["inputPassword"].strip() != request.POST["inputRePassword"].strip():
            return redirect("/user/register")
        else:
            username = request.POST["inputUsername"].strip()
            email = request.POST["inputEmail"].strip()
            password = request.POST["inputPassword"].strip()
            new_user = User.objects.create_user(username=username, email=email, password=password)
            sex = request.POST["inputSex"].strip()
            age = request.POST["inputAge"].strip()
            avatar_name = username+"-40"
            new_hacker = Hacker(hacker=new_user, sex=sex, age=age, avatar_name=avatar_name)
            new_hacker.save()
        return render(request, "user_register.html")
Пример #17
0
    def get(self):
        hackers = list(Hacker.all())
        if hackers:
            hackers.sort(key=lambda h: (h.score, h.handle))
            rank = 0
            ranked_hackers = [(rank, hackers[-1])]
            for i in range(len(hackers) - 2, 0, -1):
                if hackers[i + 1].score_cache != hackers[i].score_cache:
                    rank += 1
                ranked_hackers.append((rank, hackers[i]))
        else:
            ranked_hackers = []

        self.render_template('members', {'hackers': ranked_hackers})
Пример #18
0
    def get(self, hacker_id, skill):

        self._current_user = self.require_login()
        if not self._current_user:
            self.response.out.write(json.dumps({"error": "please log in"}))
            return

        hacker = Hacker.get_by_id(hacker_id)
        if not hacker or hacker.user != self._current_user.id:
            self.response.out.write(json.dumps({"error": "could not find hacker or hacker not owned by you"}))
            return

        hacker.talents.append(skill)
        hacker.put()
        self.response.out.write(json.dumps({"success": "level up successful"}))
Пример #19
0
    def get(self):
        self._current_user = self.require_login()
        if not self._current_user:
            self.authenticate()
            return

        token = initChannel(self._current_user.id)
        #Resolve hackers for this user
        self._current_user.hackers = Hacker.all().filter("user ="******"/create")

        path = os.path.join(os.path.dirname(__file__), 'loadout.html')
        self.response.out.write(template.render(path, {"user": self._current_user, "token": token}))
Пример #20
0
 def post(self):
     id = request.args['id']
     try:
         hacker = Hacker.get_by_id(id)
     except:
         abort(404, message = "Hacker not found")
     if hacker.next_proj.table == int(request.args['table']):
         try:
             View.create(hacker = hacker, project = hacker.next_proj)
             res = jsonify({"status" : "View recorded"})
             res.status_code = 201
             return res
         except:
             abort(409, message = "Unable to submit view")
     else:
         abort(409, message = "Submission and database mismatch")
Пример #21
0
 def post(self):
     post = self.request.POST
     if len(post) == 2 and 'badge' in post and 'proof' in post:
         body = 'Hacker: %s\nBadge: %s\nProof:\n%s' % (
             Hacker.get_current_hacker().handle, post['badge'],
             post['proof'])
         send_mail(sender='*****@*****.**',
                   to='*****@*****.**',
                   subject='Badge application',
                   body=body)
         self.render_template(
             'badge_application',
             template_dict={
                 'message':
                 'Application submitted. It will be reviewed as soon as possible.'
             })
Пример #22
0
    def preferred_items(self, hacker):
        seen = {i.project.table for i in View.select().where(View.hacker == hacker)}
        # They haven't even seen the last one we gave them!
        if hacker.next_proj != None and hacker.next_proj.table not in seen:
            return [hacker.next_proj]
        if seen:
            items = Project.select().where(Project.active, ~Project.table.in_(seen))
        else:
            items = Project.select().where(Project.active)

        hackers = Hacker.select().where(Hacker.next_proj != None, Hacker.updated_vote != None)
        busy = {i.next_proj.table for i in hackers if ((datetime.datetime.utcnow() - i.updated_vote).total_seconds() < TIMEOUT * 60)}
        if busy:
            items = items.select().where(~Project.table.in_(busy))

        less_items = [i for i in items if len(i.views) < MIN_VIEWS]
        return less_items if less_items else [i for i in items]
Пример #23
0
    def post(self):
        id = request.args['id']
        code = request.args['code']
        try:
            hacker = Hacker.get_by_id(id)
            # If the account exists and is verified return an error
            if hacker.verified:
                abort(409, message="Hacker already verified")
        except DoesNotExist:
            abort(409, message="Verification not started")

        if code == hacker.verification and datetime.datetime.now(
        ) < hacker.verification_expiration:
            hacker.verified = True
            hacker.save()
            res = jsonify({"status": "Hacker verified", "code": 0})
            res.status_code = 201
            return res
        abort(403, message="Invalid or expired code")
Пример #24
0
    def post(self):
        email = request.args['email']
        # Gets or creates a new entry for a hacker
        hacker, created = Hacker.get_or_create(
            id=request.args['id'],
            username=request.args['username'],
            discriminator=request.args['discriminator'])
        # If the account exists and is verified return an error
        if not created and hacker.verified:
            abort(409, message="Hacker already verified")

        # Get all registration entries under that email
        entries = Registration.select().where(
            fn.Lower(Registration.email) == email.lower()).order_by(
                Registration.submit_time)
        if entries.exists():
            if entries[0].hacker_discord != None and entries[
                    0].hacker_discord != hacker:
                abort(409,
                      message=
                      "Registration verification started with another hacker")
            # Start hacker verification
            hacker.verification = secrets.token_hex(8)
            hacker.verification_expiration = datetime.datetime.now(
            ) + datetime.timedelta(hours=1)
            hacker.save()
            query = Registration.update(hacker_discord=hacker).where(
                Registration.email == email)

            # Email hacker!
            response = mail.send_verification_email(entries[0],
                                                    hacker.verification)
            if response:
                query.execute()
                res = jsonify({"status": "Email sent!", "code": 0})
                res.status_code = 201
                return res
            else:
                abort(501, message="Unable to send email")
        else:
            abort(404, message="Unable to find registration")
Пример #25
0
    def get(self):
        self._current_user = self.require_login()
        if not self._current_user:
            self.response.out.write(json.dumps({"error": "please log in"}))
            return

        q = Queue.all().get()
        if not q:
            q = Queue()

        #Push onto queue
        if str(self._current_user.id) in q.users:
            self.response.out.write(json.dumps({"success": "already in queue"}))
        elif len(q.users) == 0:
            q.users = [self._current_user.id]
            self.response.out.write(json.dumps({"success": "added to queue"}))
        else: #Found a match. Pop & Serve
            matched = q.users[0]
            q.users = q.users[1:]

            #Randomly choose a project
            projects = Project.all().fetch(1000)
            random.seed()
            project = random.choice(projects)

            #Actually create the match
            match = Match(project_id = str(project.key()),
                          users = [self._current_user.id, matched],
                          outcome = [0, 0])

            hackers = Hacker.all().filter("user IN", match.users).fetch(8)
            match.hacker_list = []
            for hacker in hackers:
                match.hacker_list.append(str(hacker.key()))

            match.put()

            #Notify the users via socket
            broadcast(match, json.dumps({"success": "match found"}))
            self.response.out.write("herp")
        q.put()
Пример #26
0
    def post(self):
        id = request.args['id']
        next_won = request.args['next_won'] == 'True'
        try:
            hacker = Hacker.get_by_id(id)
        except:
            abort(404, message = "Hacker not found")
        if hacker.prev_proj.table == int(request.args['prev_table']) and hacker.next_proj.table == int(request.args['next_table']):
            if hacker.prev_proj.active and hacker.next_proj.active:
                self.perform_vote(hacker, next_won)
                if next_won:
                    Vote.create(hacker = hacker, winner = hacker.next_proj, loser = hacker.prev_proj)
                else:
                    Vote.create(hacker = hacker, winner = hacker.prev_proj, loser = hacker.next_proj)
            hacker.prev_proj = None
            hacker.save()
            res = jsonify({"status" : "Vote recorded"})

            res.status_code = 201
            return res
        else:
            abort(409, message = "Submission and database mismatch")
Пример #27
0
    def render_template(self, template_name, template_dict=None):
        next_meeting = Meeting.get_next_meeting()
        if next_meeting:
            tag_line = '%s: %s, %s' % (next_meeting.name,
                                       next_meeting.start_date,
                                       next_meeting.location)
        else:
            tag_line = 'Evening Hack: 14/4/2011 5pm LF15'

        if template_dict is None:
            template_dict = {}

        user = Hacker.get_current_hacker()

        if user:
            if self.login_required:
                redirect_target = '/'
            else:
                redirect_target = self.request.path
            url_creator = users.create_logout_url
        else:
            redirect_target = '/login?url=%s' % self.request.path
            url_creator = users.create_login_url

        defaults = {
            'user': user,
            'log_url': url_creator(redirect_target),
            'tag_line': tag_line,
            'title': self.title
        }

        for key in defaults:
            if key not in template_dict:
                template_dict[key] = defaults[key]

        template_path = get_path(
            os.path.join('templates', '%s.html' % template_name))
        self.response.out.write(template.render(template_path, template_dict))
Пример #28
0
 def post(self):
     post =  self.request.POST
     if post['kind'] == 'badge':
         b = Badge(name=post['name'], description=post['description'], 
                   category=post['category'], image=post['image'],
                   value=int(post['value']))
         b.save()
     elif post['kind'] == 'article':
         a = NewsArticle(title=post['title'], author=post['author'],
                          body=post['body'], date=datetime.date.today())
         a.save()
     elif post['kind'] == 'award':
         badge = Badge.gql('WHERE name = :1', post['badge']).get()
         for h in post.getall('hackers'):
             hacker = Hacker.gql('WHERE handle = :1', h).get()
             a=Award(hacker=hacker, 
                     badge=badge,
                     date=datetime.date.today(),
                     proof=post['proof'])
             a.save()
             hacker.score_cache = hacker.score + badge.value
             hacker.save()
     self.get()
Пример #29
0
 def render_template(self, template_name, template_dict=None):
     next_meeting = Meeting.get_next_meeting()
     if next_meeting:
         tag_line = '%s: %s, %s' % (next_meeting.name, next_meeting.start_date, next_meeting.location)
     else:
         tag_line = 'Evening Hack: 14/4/2011 5pm LF15'
 
     if template_dict is None:
         template_dict = {}
     
     user = Hacker.get_current_hacker()
     
     if user:
         if self.login_required:
             redirect_target = '/'
         else:
             redirect_target = self.request.path
         url_creator = users.create_logout_url
     else:
         redirect_target = '/login?url=%s' % self.request.path
         url_creator = users.create_login_url
         
     defaults = {
         'user': user,
         'log_url': url_creator(redirect_target),
         'tag_line': tag_line,
         'title': self.title
     }
     
     for key in defaults:
         if key not in template_dict:
             template_dict[key] = defaults[key]
     
     template_path = get_path(
         os.path.join('templates', '%s.html' % template_name))
     self.response.out.write(
         template.render(template_path, template_dict))
Пример #30
0
 def post(self):
     id = request.args['id']
     table = request.args.get('table', None)
     try:
         hacker = Hacker.get_by_id(id)
     except:
         abort(404, message = "Hacker not found")
     hacker.updated_vote = datetime.datetime.utcnow()
     if table != None:
         try:
             hacker.own_proj = Project.get_by_id(table)
             View.create(hacker = hacker, project = hacker.own_proj)
         except:
             abort(404, message = "Project not found")
     try:
         hacker.save()
     except:
         abort(501, message = "Unable to create hacker entry")
     status = {"status": "Setup hacker to start voting"}
     if table != None:
         status["title"] = Project.get_by_id(table).name
     res = jsonify(status)
     res.status_code = 201
     return res
Пример #31
0
 def get(self):
     self.render_template('admin', {'badges': Badge.all(),
                                    'hackers': Hacker.all()})
Пример #32
0
    def get(self):
        handle = self.request.get('handle', None)
        if handle is None:
            # First request, just get the first handle out of the datastore.
            hacker = Hacker.gql('ORDER BY handle DESC').get()
            if not hacker:
                # No hackers in database
                self.response.headers['Content-Type'] = 'text/plain'
                self.response.out.write("No Hackers in database")
                return
            handle = hacker.handle

        query = Hacker.gql('WHERE handle <= :1 ORDER BY handle DESC', handle)
        hackers = query.fetch(limit=2)
        current_hacker = hackers[0]
        if len(hackers) == 2:
            next_handle = hackers[1].handle
            next_url = '/admin/hacker_migration?handle=%s' % urllib.quote(
                next_handle)
        else:
            next_handle = 'FINISHED'
            next_url = '/'  # Finished processing, go back to main page.

        awards_updated = 0
        talks_updated = 0
        updated_hacker = False
        # Add a new member if this Hacker has not been migrated
        if not Member.gql('WHERE handle = :1', current_hacker.handle).get():
            new_member = Member(user_id=current_hacker.user_id,
                                email=current_hacker.email,
                                handle=current_hacker.handle,
                                bio=current_hacker.bio,
                                real_name=current_hacker.real_name)
            new_member.put()

            # Find any award or talk entities that reference the old hacker
            # and remap them
            awards = Award.gql('WHERE hacker = :1', current_hacker)
            for award in awards:
                award.member = new_member
                if hasattr(award, 'hacker'):
                    del award.hacker
                award.put()
                awards_updated += 1
            talks = Talk.gql('WHERE member = :1', current_hacker)
            for talk in talks:
                talk.member = new_member
                talk.put()
                talks_updated += 1

            updated_hacker = True

        # Delete the Hacker
        current_hacker.delete()

        context = {
            'current_handle': handle,
            'updated_hacker': updated_hacker,
            'awards_updated': awards_updated,
            'talks_updated': talks_updated,
            'next_handle': next_handle,
            'next_url': next_url,
        }

        self.render_template('hacker_migration', context)
Пример #33
0
 def get(self):
     handle = self.request.get('handle', None)
     if handle is None:
         # First request, just get the first handle out of the datastore.
         hacker = Hacker.gql('ORDER BY handle DESC').get()
         if not hacker:
             # No hackers in database
             self.response.headers['Content-Type'] = 'text/plain'
             self.response.out.write("No Hackers in database")
             return
         handle = hacker.handle
 
     query = Hacker.gql('WHERE handle <= :1 ORDER BY handle DESC', handle)
     hackers = query.fetch(limit=2)
     current_hacker = hackers[0]
     if len(hackers) == 2:
         next_handle = hackers[1].handle
         next_url = '/admin/hacker_migration?handle=%s' % urllib.quote(next_handle)
     else:
         next_handle = 'FINISHED'
         next_url = '/'  # Finished processing, go back to main page.
         
         
     awards_updated = 0
     talks_updated = 0
     updated_hacker = False
     # Add a new member if this Hacker has not been migrated
     if not Member.gql('WHERE handle = :1', current_hacker.handle).get():
         new_member = Member(user_id=current_hacker.user_id,
                             email=current_hacker.email,
                             handle=current_hacker.handle,
                             bio=current_hacker.bio,
                             real_name=current_hacker.real_name)
         new_member.put()
         
         # Find any award or talk entities that reference the old hacker 
         # and remap them
         awards = Award.gql('WHERE hacker = :1', current_hacker)
         for award in awards:
             award.member = new_member
             if hasattr(award, 'hacker'):
                 del award.hacker
             award.put()
             awards_updated += 1
         talks = Talk.gql('WHERE member = :1', current_hacker)
         for talk in talks:
             talk.member = new_member
             talk.put()
             talks_updated += 1
                 
         updated_hacker = True
 
     # Delete the Hacker
     current_hacker.delete()
 
     context = {
         'current_handle': handle,
         'updated_hacker': updated_hacker,
         'awards_updated': awards_updated,
         'talks_updated': talks_updated,
         'next_handle': next_handle,
         'next_url': next_url,
     }
     
     self.render_template('hacker_migration', context)
Пример #34
0
 def get(self, handle):
     query = Hacker.gql('WHERE handle = :1', urllib.unquote(handle))
     hacker = iter(query).next() if query.count() else None
     self.render_template('member', {'hacker': hacker})
Пример #35
0
    def post(self):
        # grab argument to know what operation we want
        operation = request.args.get('operation')
        try:
            amount = int(request.args.get('amount'))
        except:
            return {
                'status': 'error',
                'message': 'amount arg needs to be an int'
            }, 400

        if not (amount or operation):
            return {
                'status': 'error',
                'message': 'no operation or amount argument given'
            }, 400

        if operation == 'delete all':
            Team.query.delete()
            Submission.query.delete()
            Hacker.query.delete()
            Grade.query.delete()
            db.session.commit()
            return {'status': 'success'}, 200

        if operation == 'single full build':
            for index in range(amount):
                # create team
                team = Team('Team number {}'.format(index))
                submission = Submission('this is a description',
                                        'this is a devpost link',
                                        'this is a youtube link')
                team.submission = submission
                # create hacker
                hacker = Hacker('hacker name {}'.format(index),
                                'email{}@gmail.com'.format(index))
                team.team_members.append(hacker)

                # add new objects to db
                db.session.add(team)
            db.session.commit()
            return {'status': 'success'}, 200

        if operation == 'multi full build':
            # grab second amount
            try:
                second_amount = int(request.args.get('second_amount'))
            except:
                return {
                    'status': 'error',
                    'message': 'second_amount arg needs to be an int'
                }, 400
            if not second_amount:
                return {
                    'status':
                    'error',
                    'message':
                    'no second_amount argument given for multi operation'
                }, 400

            for index in range(amount):
                # create team
                team = Team('Team number {}'.format(index))
                submission = Submission('this is a description',
                                        'this is a devpost link',
                                        'this is a youtube link')
                team.submission = submission
                # create hacker
                for num in range(second_amount):
                    hacker = Hacker('hacker name {} - {}'.format(index, num),
                                    'email{}_{}@gmail.com'.format(index, num))
                    team.team_members.append(hacker)

                # add new objects to db
                db.session.add(team)
            db.session.commit()
            return {'status': 'success'}, 200
Пример #36
0
import random
import operator
from models import Bank, Hacker, Muscle, Locker_Picker

if __name__ == "__main__":
    print('Python Heist')
    rolodex = []
    garrett = Muscle("garrett", 75, 10)
    william = Hacker("william", 75, 10)
    asia = Locker_Picker("asia", 100, 25)
    rolodex.append(garrett)
    rolodex.append(william)
    rolodex.append(asia)

    print(f'The rolodex currently has {len(rolodex)} heisters to select!')
    # build crew
    while True:
        user_Input_Name = input(
            'Please add a new crew member. Or press enter to choose your team    '
        )
        if user_Input_Name == "":
            break
        while True:
            user_Input_Specialty = input(
                f'What is {user_Input_Name}\'s specialty: hacker, muscle or lock picker??    '
            )
            if user_Input_Specialty.lower() == 'muscle':
                user_Input_skill = input('What is their skill level?   ')
                user_Input_Cut = input('What is their take on this score   ')
                new_Muscle = Muscle(user_Input_Name, int(user_Input_skill),
                                    int(user_Input_Cut))
Пример #37
0
 def get(self):
     self.render_template('admin', {
         'badges': Badge.all(),
         'hackers': Hacker.all()
     })
Пример #38
0
 def get(self, handle):
     query = Hacker.gql('WHERE handle = :1', urllib.unquote(handle))
     hacker = iter(query).next() if query.count() else None
     self.render_template('member', {'hacker': hacker})
Пример #39
0
 def get(self):
     for h in Hacker.all().fetch(1000):
         h.delete()
     for m in Match.all().fetch(1000):
         m.delete()
     self.response.out.write("Datastore cleared of matches & hackers");