Exemple #1
0
	def get(self, *args):
		if (isAccessible('', 'listClubs')):
			clubs = Club.all()
			vars = dict (clubs=Club.all(), cluburl=viewurlconf.path('')[:-1])
			if (isAccessible('', 'createClub')):
				nowdt = datetime.now()
				newslug = "newclb_%d%d%d%d%d%d%d" % (nowdt.year, nowdt.month, nowdt.day, nowdt.hour, nowdt.minute, nowdt.second, nowdt.microsecond)
				newcluburl = editurlconf.path(newslug) 
				vars['newcluburl'] = newcluburl
			self.response.out.write (render(self.template, vars, self.request.url) )
		else:
			errorPage( self.response,  "Not Accessible",   users.create_login_url(self.request.uri))
Exemple #2
0
    def visit(self):
        if self.club and self.user:
            return True
            # Analyze req path first
        slug, pathuser = urlconf.analyze(self.request.path)
        # Get club
        club = Club.getClubBySlug(slug)
        if not club:
            return errorPage(self.response, "No such club " + slug, "/clubs", 404)

            # Check user status
        user = users.get_current_user()
        if not user:
            return errorPage(
                self.response, "User not login", users.create_login_url(self.request.uri), self.response, 403
            )

            # That the one we modify is the path user. if omitted, user current user as target
        if pathuser:
            pathuser = users.User(pathuser)
        else:
            pathuser = user
            # @warning: I don't know is it correct to add access control code here
        if not hasClubPrivilige(user, club, "membership", pathuser.email()):
            return errorPage(self.response, "Can not access", "/", 403)
        self.user = user
        self.club = club
        self.member = Membership.between(pathuser, club)
        self.targetUser = pathuser
        return True
Exemple #3
0
    def visit(self):
        if (self.club and self.user):
            return True
        #Analyze req path first
        slug, pathuser = urlconf.analyze(self.request.path)
        #Get club
        club = Club.getClubBySlug(slug)
        if (not club):
            return errorPage(self.response, "No such club " + slug, '/clubs',
                             404)

        #Check user status
        user = users.get_current_user()
        if (not user):
            return errorPage(self.response, "User not login",
                             users.create_login_url(self.request.uri),
                             self.response, 403)

        #That the one we modify is the path user. if omitted, user current user as target
        if (pathuser):
            pathuser = users.User(pathuser)
        else:
            pathuser = user
        #@warning: I don't know is it correct to add access control code here
        if (not hasClubPrivilige(user, club, 'membership', pathuser.email())):
            return errorPage(self.response, "Can not access", '/', 403)
        self.user = user
        self.club = club
        self.member = Membership.between(pathuser, club)
        self.targetUser = pathuser
        return True
Exemple #4
0
 def initRequest(self):
     urlconf = urldict[type(self).__name__]
     slug, useremail = urlconf.analyze(self.request.path)
     club = Club.getClubBySlug(slug)
     if (not club):
         return errorPage(self.response, "No Such Club: '%s'" % slug,
                          urldict['ClubList'].path(), 404)
     user = users.get_current_user()
     pathuser = user
     if (useremail):
         getuser = users.User(useremail)
         if (getuser):
             pathuser = getuser
     if (hasClubPrivilige(user, club, "privGrant", pathuser)):
         self.user = user
         self.target = Membership.between(pathuser, club)
         if (self.target):
             return True
         else:
             return errorPage(
                 self.response,
                 "User %s is not a member of club %s" % (pathuser, slug),
                 urldict['ClubView'].path(slug), 403)
     else:
         return errorPage(
             self.response,
             "Access Deny For Privilige Grant Operation on Club %s, to user %s"
             % (slug, pathuser), urldict['ClubView'].path(slug), 403)
Exemple #5
0
 def get(self, club_id, email_id):
     # check credentials
     if not(check_admin(club_id)):
         add_notify("Error", "You do not have the appropriate permissions")
         self.redirect("/")
         return
     user = users.get_current_user()
     club = Club.get_by_key_name(club_id)
     
     # get the email to be admin-ified
     email = Email.get_by_key_name(email_id)
     if not(email):
         add_notify("Error", "No email to be promoted!")
         self.redirect("/club/%s" % club.slug)
         return
     # find the link to promote it
     query = EmailToClub.all()
     query.filter("email =", email)
     query.filter("club =", club)
     link = query.get()
     if not(link):
         add_notify("Error", "No email to be promoted!")
         self.redirect("/club/%s" % club.slug)
         return
     if not link.enable:
         add_notify("Error", "Can't promote a disabled email")
         self.redirect("/club/%s" % club.slug)
         return
     # flip the admin bit
     link.admin = not(link.admin)
     link.put()
     # make sure we have at least one admin
     query = EmailToClub.all()
     query.filter("club =", club)
     query.filter("admin =", True)
     admin_check = query.get()
     if not(admin_check):
         # reverse the admin
         link.admin = True
         link.put()
     # send an email if you've just been promoted
     if link.admin:
         domain = "http://%s.appspot.com" % get_application_id()
         msg = mail.EmailMessage()
         fromaddr = "noreply@%s.appspotmail.com" % get_application_id()
         msg.sender  = "Flyer Guy <%s>" % fromaddr
         msg.to      = email.email
         msg.subject = "[Flyer] You've an admin of %s!" % club.name
         msg.html    = template.render("templates/email_admin.html",
                                       {"domain":domain,
                                        "club":club.name,
                                        "email":email.id})
         try:
             msg.send()
         except apiproxy_errors.OverQuotaError, (message,):
             # Log the error
             add_notify("Error", "Could not send email")
             logging.error("Could not send email")
             logging.error(message)
Exemple #6
0
    def post(self, club_id):
        # check credentials
        if not(check_admin(club_id)):
            add_notify("Error", "You do not have the appropriate permissions")
            self.redirect("/")
            return
        club = Club.get_by_key_name(club_id)

        # make a flyer
        flyer, made = None, None
        while not(flyer) or not(made):
            # randomly generate a flyer key
            flyer_key = generate_random_hash(club_id)[:10]
            flyer, made = get_or_make(Flyer, flyer_key)
        flyer.id = flyer_key
        # get the parameters
        file_obj = self.request.POST["flyer"]
        file_name = file_obj.filename
        flyer_name = self.request.get("name")
        event_date = self.request.get("date")
        if not(flyer_name):
            flyer_name = file_name[:-4]
        # check if the filename is a pdf
        if file_name[-3:] != "pdf":
            add_notify("Error", "File is not a pdf")
            self.redirect("/flyer/%s" % club.slug)
            return
        # fetch the blobstore key, save it
        upload = self.get_uploads("flyer")
        logging.info(upload)
        flyer.flyer = upload[0]
        # set everything else
        flyer.name = flyer_name
        flyer.club = club
        flyer.upload_date = datetime.today()
        # change the time to right before midnight
        event_date = datetime.strptime(event_date, "%Y/%m/%d")
        event_date = event_date.replace(hour=23, minute=59)
        flyer.event_date = event_date
        flyer.put()

        # make a bunch of jobs from the club and flyer
        emails = [e.email
                  for e in prefetch_refprop(club.emails, EmailToClub.club)]
        for email in emails:
            # generate a key
            job_obj, made = None, None
            while not(job_obj) or not(made):
                # randomly generate a key
                job_key = generate_random_hash(str(email))
                job_obj, made = get_or_make(Job, job_key)
                if made:
                    job_obj.id = job_key
                    job_obj.flyer = flyer
                    job_obj.email = email
                    job_obj.put()
        # and write out the response
        self.response.out.write(template.render("templates/finish_upload.html",
                                                {}))
 def ClubList(self, request):
   query = Club.query()
   if request.order == ClubListRequest.Order.TEXT:
     query = query.order(Club.name)
   elif request.order == ClubListRequest.Order.WHEN:
     query = query.order(-Club.creation_time)
   clubs = [entity.ToMessage() for entity in query.fetch(request.limit)]
   return ClubListResponse(clubs=clubs)
Exemple #8
0
 def get(self):
     clubs = []
     for c in Club.all().filter('category IN', ("J1", "J2")):
         clubs.append(c)
     random.shuffle(clubs)
     params = {'clubs': clubs}
     t = JINJA2_ENV.get_template('club-list.html')
     self.response.out.write(t.render(params))
Exemple #9
0
	def getActModel(self):
		urlcfg = urldict['ActivityNew']
		slug, = urlcfg.analyze(self.request.path)
		user = get_current_user()
		club = Club.getClubBySlug(slug)
		if (user and club):
			newact = Activity.createDefault(user, club)
			if (newact): newact.bill = [('Filed Expense', 80), ('Balls Expense', 30)]
			return newact
		else:
			return None
Exemple #10
0
	def can_createClub(self, *args):
		cq = Club.all()
		if (not self.user):
			return False
		cq.filter('owner =', self.user)
		if (cq.count() < conf.MaxClubsPerUser):
			return True
		elif ( users.is_current_user_admin() and self.user == users.get_current_user()):
			return True
		else:
			return False
def get_club():
    for page_id in range(1, 2):
        try:
            url = CK_API_URL_PAGE.format('clubs', page_id)
            response = get_request(url)
            for club_data in response:
                try:
                    return DB.open().query(Club).filter(Club.api_url == club_data['api']).one()
                except:
                    obj = get_request(club_data['api'])
                    if 'id' in obj:
                        club = Club()
                        club.parse_json(obj)
                        DB.save(club)
                    
                    if club:
                        print('SAVED CLUB ID {}'.format(club.id))
                        print('+++++++++++++++++')
        except:
            pass
Exemple #12
0
 def getActModel(self):
     urlcfg = urldict['ActivityNew']
     slug, = urlcfg.analyze(self.request.path)
     user = get_current_user()
     club = Club.getClubBySlug(slug)
     if (user and club):
         newact = Activity.createDefault(user, club)
         if (newact):
             newact.bill = [('Filed Expense', 80), ('Balls Expense', 30)]
         return newact
     else:
         return None
def make_club(ownerid,name,university,about="",members=[],admins=[],private=True,callback=None):
    if len(name) <= 0:
        return 500
    admins = admins
    logger.debug("Name "+ name)
    logger.debug("Admins " + str(admins))
    logger.debug("Members " + str(members))
    if ownerid not in admins:
        admins.append(ownerid)
    if ownerid not in members:
        members.append(ownerid)
    club = Club(Admins=admins,Members=members,About=about,Name=name,University=university,Private=private)
    club.save()
    for userid in members:
        user = User.objects(id=userid).first()
        subc = SubClub(Id=club.id,Name=name)
        user.Clubs.append(subc)
        user.save()
    if callback != None:
        return callback(200)
    return 200
Exemple #14
0
def newClub():
    if 'username' not in login_session:
        return redirect('/login')

    if request.method == 'POST':
        newClub = Club(name=request.form['name'],
                       user_id=login_session['user_id'])
        session.add(newClub)
        session.commit()
        flash("New Club Created!")
        return redirect(url_for('showClubs'))
    else:
        return render_template("newClub.html")
Exemple #15
0
def check_admin(club_id):
    """See if we have admin access to a certain club's pages"""
    user = users.get_current_user()
    email = get_email(user)
    club = Club.get_by_key_name(club_id)
    if not(user) or not(email) or not(club) or not(email.user_enable):
        return False
    # do a joint query
    query = EmailToClub.all()
    query.filter("email =", email)
    query.filter("club =", club)
    joint = query.get()
    if not(joint):
        return False
    return joint.admin
Exemple #16
0
def createNewClub(request):
	u_id = request.POST['u_id']
	name = request.POST['club_name']
	intro = request.POST['club_intro']
	c_name = request.POST['c_name']
	tel = request.POST['club_tel']
	email = request.POST['club_email']
	cb_type = request.POST['club_type']
	numMembers = request.POST['numMembers']

	u = User_C.objects.get(id=u_id)
	school = u.school

	today = str(date.today().year)+'-'+str(date.today().month)+'-'+str(date.today().day)

	#basic information
	information = clubInfo()
	information.name = name
	information.create_name = c_name
	information.introduction = intro
	information.cb_type = cb_type
	information.dateFound = today
	information.tel = tel
	information.email = email
	information.numMember = numMembers
	
	form = uploadLogoForm(request.POST,request.FILES)
	if form.is_valid():
		information.logo = request.FILES['logo']

	information.save()

	#founder information
	founder = founderInfo(FI_user=u)
	founder.save()

	#record
	record = recordInfo()
	record.save()

	#create Club
	new_club = Club()
	new_club.information = information
	new_club.founder = founder
	new_club.school = school
	new_club.record = record
	new_club.save()

	createGlobalNews(u_id,new_club.id,'1')

	return HttpResponse('1')
Exemple #17
0
 def get(self, name):
     c = Club.get_by_key_name(name)
     if c is None:
         self.response.set_status(404)
         t = JINJA2_ENV.get_template('404.html')
         self.response.out.write(t.render({}))
         return
     cal = CalendarWrap(c.display)
     q = Match.all().filter('home = ', c)
     for match in q:
         cal.add(match)
     q = Match.all().filter('away = ', c)
     for match in q:
         cal.add(match)
     self.response.headers["Content-Type"] = "text/calendar; charset=utf-8"
     self.response.out.write(cal.to_string())
Exemple #18
0
    def get(self, club_id):
        # check credentials
        if not(check_admin(club_id)):
            add_notify("Error", "You do not have the appropriate permissions")
            self.redirect("/")
            return
        club = Club.get_by_key_name(club_id)

        values = {"name": club.name, "slug": club.slug}
        session = get_current_session()
        if session:
            values["notifications"] = session["notify"]
            session["notify"] = None
        # create a blobstore url
        upload_url = blobstore.create_upload_url('/flyer/%s' % club.slug)
        values["upload_url"] = upload_url
        self.response.out.write(template.render("templates/upload.html", values))
Exemple #19
0
    def post(self, club_id):
        # check credentials
        if not(check_admin(club_id)):
            add_notify("Error", "You do not have the appropriate permissions")
            self.redirect("/")
            return
        user = users.get_current_user()
        club = Club.get_by_key_name(club_id)
        email = get_email(user)

        # add emails
        email_block = self.request.get("newemails")
        emails_raw = [e for e in re.split("[\s\,\n]", email_block) if e]
        emails = [normalize_email(e) for e in emails_raw]
        emails = [e for e in emails if e]
        for email in emails:
            # add a suffix
            email = normalize_email(email)
            # use a hash for emails, assume it is unique
            email_key = generate_hash(email)[:10]
            email_obj, made = get_or_make(Email, email_key)
            if not(made):
                logging.info("Email already in the system")
                continue
            email_obj.email = email
            email_obj.id = email_key
            email_obj.put()
            # make sure this pair is unique
            query = EmailToClub.all()
            query.filter('email =', email_obj)
            query.filter('club =', club)
            join = query.get()
            if not(join):
                join = EmailToClub(email=email_obj, club=club)
                join.put()

        # create message
        if emails:
            add_notify("Notice", "Emails added")
        if len(emails) != len(emails_raw):
            add_notify("Notice", "Not all emails added")
        self.redirect("/club/%s" % club.slug)
Exemple #20
0
 def get(self):
     include_club = False
     v = self.request.get('include')
     if v == 'club':
         include_club = True
     stadiums = []
     for s in Stadium.all().order('-location'):
         # Hand-made GeoJSON.
         p = {
             'type': 'Feature',
             'id': None,
             'properties': {
                 'abbr': s.abbr,
                 'name': s.display_name,
                 'wikipedia': s.wikipedia_url
             },
             'geometry': {
                 'type': 'Point',
                 'coordinates': [
                     s.location.lon, s.location.lat
                 ]
             }
         }
         if include_club:
             q = Club.all().filter('stadium =', s.abbr)
             clubs = []
             for c in q:
                 clubs.append({
                     'key': c.key().name(),
                     'category': c.category,
                     'url': c.url,
                     'name': c.display
                 })
             if len(clubs) > 0:
                 p['properties']['clubs'] = clubs
         stadiums.append(p)
     # See IANA official document.
     # http://www.iana.org/assignments/media-types/application/vnd.geo+json
     self.response.headers["Content-Type"] = "application/vnd.geo+json"
     json.dump({'type': 'FeatureCollection', 'features': stadiums},
               self.response.out)
Exemple #21
0
	def get(self, *args):
		path = self.request.path
		slug = lastWordOfUrl(path)
		if (slug):
			club = Club.getClubBySlug(slug)
		if (club):
			templatevars = dict(club = club )
			user = users.get_current_user()
			membership = Membership.between (user, club)
			if (membership):
				templatevars['membership'] = membership
			elif (user and hasClubPrivilige(user, club, 'join')): #Could Join
				templatevars['action'] = memberurlconf.path(club.slug, user.email())
				templatevars['userName'] = user.nickname()
				templatevars['userEmail'] = user.email()
			else:
				templatevars['loginUrl'] = users.create_login_url(self.request.uri)
			if (membership and hasClubPrivilige(user, club, 'newAct')):
				templatevars['newAct'] = urldict['ActivityNew'].path(slug)
			if (hasClubPrivilige(user, club, "edit")):
				templatevars['editurl'] = urldict['ClubEdit'].path(club.slug)
			mq = Membership.all()
			mq.filter ('club = ', club)
			memset = []
			for mem in mq:
				if (hasClubPrivilige(user, club, "privGrant")):
					mem.privEdit = urldict['ClubPrivilige'].path(slug, mem.user.email())
				memset.append(mem)
			templatevars['members'] = memset
			aq = Activity.all()
			aq.filter ('club = ', club)
			avpath = urldict['ActivityView'].path
			actlist = []
			for act in aq:
				act.linkpath = avpath (act.key().id())
				actlist.append (act)
			templatevars['acts'] = actlist
			self.response.out.write (render(self.template, templatevars, self.request.url) )
		else:
			self.response.set_status(404)
			errorPage( self.response,  "Club Not Found",   listurlconf.path())
Exemple #22
0
	def initRequest(self):
		urlconf = urldict[type(self).__name__]
		slug, useremail = urlconf.analyze(self.request.path)
		club = Club.getClubBySlug(slug)
		if (not club):
			return errorPage(self.response, "No Such Club: '%s'" % slug, urldict['ClubList'].path(), 404)
		user = users.get_current_user()
		pathuser = user
		if (useremail):
			getuser = users.User(useremail)
			if (getuser):
				pathuser = getuser
		if (hasClubPrivilige(user, club, "privGrant", pathuser)):
			self.user = user
			self.target = Membership.between(pathuser, club)
			if (self.target):
				return True
			else:
				return errorPage(self.response, "User %s is not a member of club %s" % (pathuser, slug), urldict['ClubView'].path(slug), 403 )
		else:
			return errorPage(self.response, "Access Deny For Privilige Grant Operation on Club %s, to user %s" % (slug, pathuser), urldict['ClubView'].path(slug), 403 )
Exemple #23
0
    def get(self, club_id):
        """Get the editor page"""
        # check credentials
        if not(check_admin(club_id)):
            add_notify("Error", "You do not have the appropriate permissions")
            self.redirect("/")
            return
        user = users.get_current_user()
        club = Club.get_by_key_name(club_id)

        # prefetch the emails
        email_refs = club.emails
        email_refs = [e for e in email_refs] # check enabled
        emails = [e.email
                  for e in prefetch_refprop(email_refs, EmailToClub.email)]
        email_addrs = [e.email for e in emails]
        email_ids = [e.id for e in emails]
        status = []
        for eref in email_refs:
            if not(eref.enable):
                status.append(-1)
            elif eref.admin:
                status.append(1)
            else:
                status.append(0)
        messages = [e.message for e in email_refs]
        email_info = zip(email_ids, status, email_addrs, messages)
        # sort on status (admin first, opt-out last)
        email_info.sort(key=itemgetter(1), reverse=True)
        # pack up the values
        vals = {"emails": email_info,
                "club": club.name,
                "clubslug": club.slug}
        # get the notifications
        session = get_current_session()
        if session:
            vals["notifications"] = session["notify"]
            session["notify"] = None
        self.response.out.write(template.render("templates/club_edit.html",
                                                vals))
Exemple #24
0
def reg_osc():
    if request.method == 'POST':
        data = request.get_json()
        card_id = data['card_id']
        password = data['password']
        user = User.objects(card_id=card_id).first()
        result = validate(card_id, password)
        phone = data['phone']
        email = data['email']
        club = Club.objects(name='开源社区').first()
        if result['success']:
            if user is None:
                user = User(name=result['name'],
                            card_id=card_id, role='student', phone=phone, email=email)
                user.save()
            if club not in user.clubs:
                user.clubs.append(club)
                user.save()
                Member(club=club, member=user).save()
        else:
            abort(401)
        return jsonify(name=user.name)
    else:
        return render_template('reg.html')
Exemple #25
0
def api_clubs():
    if request.method == "POST":
        name = request.json['name']
        description = request.json['description']
        tags = request.json['tags']
        print(name, description, tags)
        club = Club(club_name=name, description=description)
        db_session.add(club)
        db_session.commit()
        for tag in tags:
            t_new = Tag(tag=tag,
                        club_id=db_session.query(Club).filter_by(
                            club_name=name).first().id)
            db_session.add(t_new)
            db_session.commit()
        flash("Added club " + name + " to the database.", "success")
        return jsonify(dict(redirect='/'))
    else:
        clubs = db_session.query(Club).all()
        club_list = []
        for club in clubs:
            # print(club)
            d = collections.OrderedDict()
            d['id'] = club.id
            d['club_name'] = club.club_name
            tags = club.tags
            ts = []
            for t in tags:
                tg = str(t.tag)
                ts.append(tg)
            d['tags'] = ts
            d['description'] = club.description
            # d['favorites'] = club[4]
            club_list.append(d)
        j = json.dumps(club_list)
        return j
Exemple #26
0
    def get(self, club_id, email_id):
        # check credentials
        if not(check_admin(club_id)):
            add_notify("Error", "You do not have the appropriate permissions")
            self.redirect("/")
            return
        club = Club.get_by_key_name(club_id)

        # get the email link to be deleted
        email = Email.get_by_key_name(email_id)
        if not(email):
            add_notify("Error", "No email to be deleted!")
            self.redirect("/club/%s" % club.slug)
            return
        # find the link
        query = EmailToClub.all()
        query.filter("email =", email)
        query.filter("club =", club)
        link = query.get()
        if not(link):
            add_notify("Error", "No email to be deleted!")
            self.redirect("/club/%s" % club.slug)
            return
        # make sure it's not the last admin
        query = EmailToClub.all()
        query.filter("club =", club)
        admins = query.fetch(2)
        if len(admins) < 2 and link.admin:
            add_notify("Error", "Will not delete the last club admin")
            self.redirect("/club/%s" % club.slug)
            return
        # delete the link
        link.delete()
        # hail our success
        add_notify("Notice", "Email deleted")
        self.redirect("/club/%s" % club.slug)
 def ClubGet(self, request):
   entity = Club.get_by_id(request.id)
   if entity is None:
     raise endpoints.NotFoundException('club not found.')
   return entity.ToMessage()
Exemple #28
0
def build_clubs():
    for c in clubs:
        club = Club(name=c)
        club.save()
Exemple #29
0
def put_club():
    name = request.args.get('name')
    club = Club(name=name)
    db.session.add(club)
    db.session.commit()
    return jsonify(club.json())
Exemple #30
0
        session.rollback()
        exisiting_user = session.query(User).filter_by(id=user['id']).first()
        exisiting_user.name = user['name']
        exisiting_user.email = user['email']
        exisiting_user.picture = user['picture']
        session.add(exisiting_user)
        session.commit()

print("All users updated!")

teams = json.load(open('epldata_teams.json'))
for team in teams:
    club_name = team['club'].replace("+", " ")
    try:
        club = Club(id=team['club_id'],
                    name=club_name,
                    is_big_club=bool(team['big_club']),
                    user_id=team['user_id'])
        session.add(club)
        session.commit()
    except:
        # Club already present
        session.rollback()
        existing_club = session.query(Club).filter_by(
            id=team['club_id']).first()
        existing_club.name = club_name
        existing_club.is_big_club = bool(team['big_club'])
        existing_club.user_id = team['user_id']
        session.add(existing_club)
        session.commit()

print("All clubs updated!")
Exemple #31
0
	def makeClubModel(self, slug=''):
		if (not slug):
			slug = self.request.get('slug', '')
		if (slug):
			return Club.getClub(slug)
		return Club()
Exemple #32
0
try:
    f = open('pennclubs.db')
    f.close()
except FileNotFoundError:
    Base.metadata.create_all(engine)
    html = get_clubs_html()
    s = soupify(html)
    soups = get_clubs(s)
    for soup in soups:
        name = get_club_name(soup)
        desc = get_club_description(soup)
        tags = get_club_tags(soup)
        favorites = 0
        t = []
        club = Club(club_name=name, description=desc)
        db_session.add(club)
        db_session.commit()
        for tag in tags:
            t_new = Tag(tag=tag,
                        club_id=db_session.query(Club).filter_by(
                            club_name=name).first().id)
            db_session.add(t_new)
            db_session.commit()


@app.route('/')
def main():
    is_loggedin = False
    username = None
    jen = db_session.query(User).filter_by(username="******").first()
 def ClubInsert(self, request):
   entity = Club(name=request.name)
   entity.put()
   return entity.ToMessage()
Exemple #34
0
from flask import Flask

from models import db, Footballer, Club
from routes import api, index

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
app.register_blueprint(api)
app.register_blueprint(index)
db.init_app(app)

with app.app_context():
    db.create_all()
    barcelona = Club(name='Barcelona')
    juventus = Club(name='Juventus')
    db.session.add(barcelona)
    db.session.add(juventus)
    db.session.commit()
    db.session.add(
        Footballer(name='Lionel', surname='Messi', club_id=barcelona.id))
    db.session.add(
        Footballer(name='Cristiano', surname='Ronaldo', club_id=juventus.id))
    db.session.commit()

if __name__ == '__main__':
    app.run()
Exemple #35
0
    def get(self):
        timestamp = time.mktime(datetime.now().timetuple())-24*3600
        yesterday = datetime.fromtimestamp(timestamp)
        # count how many flyers are going out
        current_date = datetime.now(CurrentTimeZone())
        day = current_date.weekday() # starts 0=monday... 6=sunday
        if day < 5:
            job_query = Job.all()
            job_query.filter("active =", True)
            job_query.filter("state !=", DONE)
            flyer_count = job_query.count()
        else:
            flyer_count = 0
        # get new clubs
        club_query = Club.all()
        club_query.filter("created_at >", yesterday)
        new_clubs = club_query.fetch(20)
        # get new emails
        email_query = Email.all()
        email_query.filter("created_at >", yesterday)
        new_emails = email_query.fetch(100)
        # get new flyers
        flyer_query = Flyer.all()
        flyer_query.filter("created_at >", yesterday)
        new_flyers = flyer_query.fetch(50)
        # get new EmailToClub
        joint_query = EmailToClub.all()
        joint_query.filter("created_at >", yesterday)
        new_joints = joint_query.fetch(100)
        # and get the newly disabled links
        joint_query = EmailToClub.all()
        joint_query.filter("updated_at >", yesterday)
        joint_query.filter("enable =", False)
        dead_joints = joint_query.fetch(100)

        if (not(new_clubs) and not(new_emails) and not(new_flyers)
            and not(new_joints)):
            self.response.out.write("Nothing to email")
            return

        # email sending pre-computation
        fromaddr = "noreply@%s.appspotmail.com" % get_application_id()
        date = time.strftime("%Y/%m/%d")

        # send the emails
        msg = mail.EmailMessage(sender = "Flyer Guy <%s>" % fromaddr,
                                to = ADMIN_EMAIL)
        msg.subject = "[Flyer] Admin stats (%s)" % date
        msg.html    = template.render("templates/email_stats.html",
                                      {"flyer_count": flyer_count,
                                       "clubs": new_clubs,
                                       "emails": new_emails,
                                       "flyers": new_flyers,
                                       "joints": new_joints,
                                       "dead_joints": dead_joints})
        try:
            msg.send()
        except apiproxy_errors.OverQuotaError, (message,):
            # Log the error.
            logging.error("Could not send email")
            logging.error(message)
Exemple #36
0
def auth(req, provider, token):  # pragma: no cover
    """
    ``GET`` @ |ta| ``/auth/<provider>/<token>``

    This function handles the authentication via social networks

    .. note::

        supports:

            - facebook
            - google


    :param req: the request
    :param provider: the provider, e.g., ``facebook``
    :param token: the token
    :return: a webApp2 Response object
    """

    # the pragma no cover is to skip the testing on this method, which can't be tested
    # get user infos
    d_user, token, error = GCAuth.handle_oauth_callback(token, provider)
    if error:
        raise AuthenticationError(error)
    # check if user exists..
    # logging.debug("%s %s %s" % (d_user, token, error))
    auth_id = str(provider) + ":" + d_user['id']
    user = User.get_by_auth_id(auth_id)
    email = d_user['email']
    # we check if users access with another social network
    user_via_mail = User.query(ndb.GenericProperty('email') == email).get()
    if user_via_mail:
        user_via_mail.add_auth_id(auth_id)
        user = user_via_mail
    # create the user..
    created = False
    if not user:
        if provider == 'google':
            created, user = User.create_user(auth_id, 
                                            # unique_properties=['email'],
                                             name=d_user.get('name', 'unknown'),
                                             nickname="",
                                             gender=d_user.get('gender', 'unknown')[0],
                                             picture=d_user.get('picture', None),
                                             avatar="",
                                             birthday=datetime.datetime.now(),
                                             country="",
                                             city="",
                                             language=d_user.get('locale', 'en'),
                                             email=d_user.get('email', '*****@*****.**'),
                                             phone="",
                                             active_club=None,
                                             owner_club=None,
                                             sensors=[])
        elif provider == 'facebook':
            created, user = User.create_user(auth_id, 
                                            # unique_properties=['email'],
                                             name=d_user.get('name', 'unknown'),
                                             nickname="",
                                             gender=d_user.get('gender', 'unknown')[0],
                                             picture="http://graph.facebook.com/%s/picture?type=large" % d_user.get(
                                                 'id', None),
                                             avatar="",
                                             birthday=datetime.datetime.now(),
                                             country="",
                                             city="",
                                             language=d_user.get('locale', 'en'),
                                             email=d_user.get('email', '*****@*****.**'),
                                             phone="",
                                             active_club=None,
                                             owner_club=None,
                                             sensors=[])
        else:
            raise AuthenticationError("provider not allowed")
        if not created:
            logging.error(
                "something is wrong with user %s with this token %s and this provider %s - unique %s" % (
                    d_user, token, provider, user))
            raise AuthenticationError(
                "Something is wrong with your account, these properties must be unique %s." % user)
        else:
            free_club = Club.query(Club.name == cfg.DEMO_CLUB).get()
            if free_club:
                courses = APIDB.get_club_courses(free_club)
                for course in courses:
                    APIDB.add_member_to_course(user, course, status="ACCEPTED")

    s_token = GCAuth.auth_user_token(user)
    # if we crate the response, then we need the cors stuff.
    # response = webapp2.Response(content_type='application/json', charset='UTF-8')
    # if created:
    # response.status = 201
    # cookie = GCAuth.get_secure_cookie(token)
    # response.set_cookie('gc_token', cookie, secure=False,
    # max_age=int(cfg.AUTH_TOKEN_MAX_AGE), domain="/")
    token = GCAuth.get_token(s_token)
    # resp.headers.update({
    #             'Access-Control-Allow-Origin': origin,
    #             'Access-Control-Allow-Credentials': 'true'})
    # response.write(json.dumps(token))
    deferred.defer(sync_user, user, s_token)
    return token
Exemple #37
0
 def get(self, home, away):
     h = Club.get_by_key_name(home)
     a = Club.get_by_key_name(away)
     params = {'home': h, 'away': a}
     t = JINJA2_ENV.get_template('match.html')
     self.response.out.write(t.render(params))
Exemple #38
0
from pprint import pprint

from base import DbManager
from models import Club

DB = DbManager()

API_URL = 'http://35.153.66.157/api/{}/{}'


def get_reqest(url):
    response = requests.get(url)
    return json.loads(response.text)


def get_reqests(obj, page):
    response = requests.get(API_URL.format(obj, page))
    return json.loads(response.text)


def fill_table(model_name, counter, new_model):
    for i in range(1, counter + 1):
        url = API_URL.format(model_name, i)
        model = new_model
        model.parse_json(get_reqest(url))
        DB.save(model)
        print('{}. -----------------------'.format(i))


fill_table('club', 10, Club())